You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by jc...@apache.org on 2020/08/03 15:00:15 UTC

[hive] branch master updated: HIVE-23949: Introduce caching layer in HS2 to accelerate query compilation (Soumyakanti Das, reviewed by Vineet Garg, Jesus Camacho Rodriguez)

This is an automated email from the ASF dual-hosted git repository.

jcamacho pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git


The following commit(s) were added to refs/heads/master by this push:
     new 6267520  HIVE-23949: Introduce caching layer in HS2 to accelerate query compilation (Soumyakanti Das, reviewed by Vineet Garg, Jesus Camacho Rodriguez)
6267520 is described below

commit 6267520a50ba8c12ae5cee8fb27a6746376a21c6
Author: Soumyakanti Das <42...@users.noreply.github.com>
AuthorDate: Mon Aug 3 11:00:07 2020 -0400

    HIVE-23949: Introduce caching layer in HS2 to accelerate query compilation (Soumyakanti Das, reviewed by Vineet Garg, Jesus Camacho Rodriguez)
    
    Closes apache/hive#1351
    
    Closes apache/hive#1317
---
 .../java/org/apache/hadoop/hive/cli/CliDriver.java |   7 +
 .../java/org/apache/hadoop/hive/conf/HiveConf.java |   7 +
 .../org/apache/hadoop/hive/ql/log/PerfLogger.java  |  13 +
 data/conf/hive-site.xml                            |  18 +
 data/conf/llap/hive-site.xml                       |  18 +
 data/conf/rlist/hive-site.xml                      |  18 +
 ...licationScenariosIncrementalLoadAcidTables.java |   6 +
 .../ql/parse/TestStatsReplicationScenarios.java    |   5 +
 .../java/org/apache/hadoop/hive/ql/QTestUtil.java  |   6 +
 .../org/apache/hadoop/hive/ql/metadata/Hive.java   | 199 ++++++---
 .../ql/metadata/SessionHiveMetaStoreClient.java    |  18 +-
 .../hadoop/hive/metastore/TestMetastoreExpr.java   |  39 +-
 .../hadoop/hive/ql/TxnCommandsBaseForTests.java    |   6 +
 .../ql/lockmgr/DbTxnManagerEndToEndTestBase.java   |   5 +
 ...HiveMetastoreClientListPartitionsTempTable.java | 121 ++++--
 .../apache/hive/service/server/HiveServer2.java    |   6 +
 standalone-metastore/metastore-common/pom.xml      |   4 +
 .../metastore-common/spotbugs/spotbugs-exclude.xml |   3 +
 .../hadoop/hive/metastore/HiveMetaStoreClient.java | 468 ++++++++++++++-------
 .../HiveMetaStoreClientWithLocalCache.java         | 274 ++++++++++++
 .../hadoop/hive/metastore/IMetaStoreClient.java    |  30 +-
 .../hadoop/hive/metastore/conf/MetastoreConf.java  |  10 +
 .../hive/metastore/utils/MetaStoreUtils.java       |  10 +
 .../hadoop/hive/metastore/metrics/PerfLogger.java  |  17 +
 .../metastore/HiveMetaStoreClientPreCatalog.java   |  18 +-
 .../hive/metastore/client/TestListPartitions.java  |  72 ++--
 standalone-metastore/pom.xml                       |   6 +
 standalone-metastore/spotbugs/spotbugs-exclude.xml |   3 +
 28 files changed, 1065 insertions(+), 342 deletions(-)

diff --git a/cli/src/java/org/apache/hadoop/hive/cli/CliDriver.java b/cli/src/java/org/apache/hadoop/hive/cli/CliDriver.java
index 1bc9865..005e689 100644
--- a/cli/src/java/org/apache/hadoop/hive/cli/CliDriver.java
+++ b/cli/src/java/org/apache/hadoop/hive/cli/CliDriver.java
@@ -54,7 +54,9 @@ import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
 import org.apache.hadoop.hive.conf.HiveVariableSource;
 import org.apache.hadoop.hive.conf.Validator;
 import org.apache.hadoop.hive.conf.VariableSubstitution;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
 import org.apache.hadoop.hive.ql.IDriver;
 import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
 import org.apache.hadoop.hive.ql.exec.mr.HadoopJobExecHelper;
@@ -794,6 +796,11 @@ public class CliDriver {
     // Create views registry
     HiveMaterializedViewsRegistry.get().init();
 
+    // init metastore client cache
+    if (conf.getBoolVar(ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
+
     // execute cli driver work
     try {
       executeDriver(ss, conf, oproc);
diff --git a/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java b/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
index 1fd5640..bba2656 100644
--- a/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
+++ b/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
@@ -487,6 +487,13 @@ public class HiveConf extends Configuration {
    * in the underlying Hadoop configuration.
    */
   public static enum ConfVars {
+    MSC_CACHE_ENABLED("hive.metastore.client.cache.enabled", true,
+            "This property enables a Caffeiene Cache for Metastore client"),
+    MSC_CACHE_MAX_SIZE("hive.metastore.client.cache.maxSize", "1Gb", new SizeValidator(),
+            "Set the maximum size (number of bytes) of the metastore client cache (DEFAULT: 1GB). " +
+                    "Only in effect when the cache is enabled"),
+    MSC_CACHE_RECORD_STATS("hive.metastore.client.cache.recordStats", false,
+            "This property enables recording metastore client cache stats in DEBUG logs"),
     // QL execution stuff
     SCRIPTWRAPPER("hive.exec.script.wrapper", null, ""),
     PLAN("hive.exec.plan", "", ""),
diff --git a/common/src/java/org/apache/hadoop/hive/ql/log/PerfLogger.java b/common/src/java/org/apache/hadoop/hive/ql/log/PerfLogger.java
index d06960a..478a2a5 100644
--- a/common/src/java/org/apache/hadoop/hive/ql/log/PerfLogger.java
+++ b/common/src/java/org/apache/hadoop/hive/ql/log/PerfLogger.java
@@ -95,6 +95,19 @@ public class PerfLogger {
   public static final String LOAD_PARTITION = "LoadPartition";
   public static final String LOAD_DYNAMIC_PARTITIONS = "LoadDynamicPartitions";
 
+  public static final String HIVE_GET_TABLE = "getTablesByType";
+  public static final String HIVE_GET_DATABASE = "getDatabase";
+  public static final String HIVE_GET_DATABASE_2 = "getDatabase2";
+  public static final String HIVE_GET_PARTITIONS = "getPartitions";
+  public static final String HIVE_GET_PARTITIONS_2 = "getPartitions2";
+  public static final String HIVE_GET_PARTITIONS_BY_EXPR = "getPartitionsByExpr";
+  public static final String HIVE_GET_TABLE_COLUMN_STATS = "getTableColumnStatistics";
+  public static final String HIVE_GET_AGGR_COL_STATS = "getAggrColStatsFor";
+  public static final String HIVE_GET_PK = "getPrimaryKeys";
+  public static final String HIVE_GET_FK = "getForeignKeys";
+  public static final String HIVE_GET_UNIQ_CONSTRAINT = "getUniqueConstraints";
+  public static final String HIVE_GET_NOT_NULL_CONSTRAINT = "getNotNullConstraints";
+
   protected final Map<String, Long> startTimes = new HashMap<String, Long>();
   protected final Map<String, Long> endTimes = new HashMap<String, Long>();
 
diff --git a/data/conf/hive-site.xml b/data/conf/hive-site.xml
index 63f46de..53a38c8 100644
--- a/data/conf/hive-site.xml
+++ b/data/conf/hive-site.xml
@@ -19,6 +19,24 @@
 
 <configuration>
 
+  <property>
+    <name>hive.metastore.client.cache.maxSize</name>
+    <value>10Mb</value>
+    <description>Max size for hive metastore client local cache</description>
+  </property>
+
+  <property>
+    <name>hive.metastore.client.cache.enabled</name>
+    <value>true</value>
+    <description>This property enables a Caffeiene Cache for Metastore client</description>
+  </property>
+
+  <property>
+    <name>hive.metastore.client.cache.recordStats</name>
+    <value>true</value>
+    <description>This property enables recording metastore client cache stats in DEBUG logs</description>
+  </property>
+
 <property>
   <name>hive.in.test</name>
   <value>true</value>
diff --git a/data/conf/llap/hive-site.xml b/data/conf/llap/hive-site.xml
index 6b28fef..fe4337b 100644
--- a/data/conf/llap/hive-site.xml
+++ b/data/conf/llap/hive-site.xml
@@ -19,6 +19,24 @@
 
 <configuration>
 
+  <property>
+    <name>hive.metastore.client.cache.maxSize</name>
+    <value>10Mb</value>
+    <description>Max size for hive metastore client local cache</description>
+  </property>
+
+  <property>
+    <name>hive.metastore.client.cache.enabled</name>
+    <value>true</value>
+    <description>This property enables a Caffeiene Cache for Metastore client</description>
+  </property>
+
+  <property>
+    <name>hive.metastore.client.cache.recordStats</name>
+    <value>true</value>
+    <description>This property enables recording metastore client cache stats in DEBUG logs</description>
+  </property>
+
 <property>
   <name>hive.in.test</name>
   <value>true</value>
diff --git a/data/conf/rlist/hive-site.xml b/data/conf/rlist/hive-site.xml
index 48c5653..78159df 100644
--- a/data/conf/rlist/hive-site.xml
+++ b/data/conf/rlist/hive-site.xml
@@ -19,6 +19,24 @@
 
 <configuration>
 
+  <property>
+    <name>hive.metastore.client.cache.maxSize</name>
+    <value>10Mb</value>
+    <description>Max size for hive metastore client local cache</description>
+  </property>
+
+  <property>
+    <name>hive.metastore.client.cache.enabled</name>
+    <value>true</value>
+    <description>This property enables a Caffeiene Cache for Metastore client</description>
+  </property>
+
+  <property>
+    <name>hive.metastore.client.cache.recordStats</name>
+    <value>true</value>
+    <description>This property enables recording metastore client cache stats in DEBUG logs</description>
+  </property>
+
 <property>
   <name>hive.in.test</name>
   <value>true</value>
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenariosIncrementalLoadAcidTables.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenariosIncrementalLoadAcidTables.java
index bcab190..7669a8c 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenariosIncrementalLoadAcidTables.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenariosIncrementalLoadAcidTables.java
@@ -20,6 +20,7 @@ package org.apache.hadoop.hive.ql.parse;
 import org.apache.hadoop.hdfs.MiniDFSCluster;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.messaging.json.gzip.GzipJSONMessageEncoder;
 import org.apache.hadoop.hive.shims.Utils;
 import static org.apache.hadoop.hive.metastore.ReplChangeManager.SOURCE_OF_REPLICATION;
@@ -106,6 +107,11 @@ public class TestReplicationScenariosIncrementalLoadAcidTables {
 
   @Before
   public void setup() throws Throwable {
+    // set up metastore client cache
+    if (conf.getBoolVar(HiveConf.ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
+
     primaryDbName = testName.getMethodName() + "_" + +System.currentTimeMillis();
     replicatedDbName = "replicated_" + primaryDbName;
     primary.run("create database " + primaryDbName + " WITH DBPROPERTIES ( '" +
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestStatsReplicationScenarios.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestStatsReplicationScenarios.java
index b2733d1..db2d3a4 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestStatsReplicationScenarios.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestStatsReplicationScenarios.java
@@ -20,6 +20,7 @@ package org.apache.hadoop.hive.ql.parse;
 import org.apache.hadoop.hdfs.MiniDFSCluster;
 import org.apache.hadoop.hive.common.StatsSetupConst;
 import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.Warehouse;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
 import org.apache.hadoop.hive.metastore.api.NotificationEvent;
@@ -125,6 +126,10 @@ public class TestStatsReplicationScenarios {
 
   @Before
   public void setup() throws Throwable {
+    // set up metastore client cache
+    if (conf.getBoolVar(HiveConf.ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
     primaryDbName = testName.getMethodName() + "_" + +System.currentTimeMillis();
     replicatedDbName = "replicated_" + primaryDbName;
     primary.run("create database " + primaryDbName + " WITH DBPROPERTIES ( '" +
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java
index 3268015..6f42bbe 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java
@@ -52,6 +52,7 @@ import org.apache.hadoop.hive.common.io.CachingPrintStream;
 import org.apache.hadoop.hive.common.io.SessionStream;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
 import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
 import org.apache.hadoop.hive.ql.cache.results.QueryResultsCache;
@@ -569,6 +570,11 @@ public class QTestUtil {
 
     initMaterializedViews(); // Create views registry
     firstStartSessionState();
+
+    // setup metastore client cache
+    if (conf.getBoolVar(ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
   }
 
   private void initMaterializedViews() {
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
index 53b9a43..0d01d5f 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
@@ -231,6 +231,7 @@ import org.slf4j.LoggerFactory;
 public class Hive {
 
   static final private Logger LOG = LoggerFactory.getLogger("hive.ql.metadata.Hive");
+  private final String CLASS_NAME = Hive.class.getName();
 
   private HiveConf conf = null;
   private IMetaStoreClient metaStoreClient;
@@ -1611,26 +1612,33 @@ public class Hive {
    */
   public List<String> getTablesByType(String dbName, String pattern, TableType type)
       throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_TABLE);
+
     if (dbName == null) {
       dbName = SessionState.get().getCurrentDatabase();
     }
 
     try {
+      List<String> result;
       if (type != null) {
         if (pattern != null) {
-          return getMSC().getTables(dbName, pattern, type);
+          result = getMSC().getTables(dbName, pattern, type);
         } else {
-          return getMSC().getTables(dbName, ".*", type);
+          result = getMSC().getTables(dbName, ".*", type);
         }
       } else {
         if (pattern != null) {
-          return getMSC().getTables(dbName, pattern);
+          result = getMSC().getTables(dbName, pattern);
         } else {
-          return getMSC().getTables(dbName, ".*");
+          result = getMSC().getTables(dbName, ".*");
         }
       }
+      return result;
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_TABLE, "HS2-cache");
     }
   }
 
@@ -2131,12 +2139,16 @@ public class Hive {
    * @throws HiveException
    */
   public Database getDatabase(String dbName) throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_DATABASE);
     try {
       return getMSC().getDatabase(dbName);
     } catch (NoSuchObjectException e) {
       return null;
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_DATABASE, "HS2-cache");
     }
   }
 
@@ -2148,12 +2160,16 @@ public class Hive {
    * @throws HiveException
    */
   public Database getDatabase(String catName, String dbName) throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_DATABASE_2);
     try {
       return getMSC().getDatabase(catName, dbName);
     } catch (NoSuchObjectException e) {
       return null;
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_DATABASE_2, "HS2-cache");
     }
   }
 
@@ -3665,33 +3681,41 @@ private void constructOneLBLocationMap(FileStatus fSta,
    * @return list of partition objects
    */
   public List<Partition> getPartitions(Table tbl) throws HiveException {
-    if (tbl.isPartitioned()) {
-      List<org.apache.hadoop.hive.metastore.api.Partition> tParts;
-      try {
-        GetPartitionsPsWithAuthRequest req = new GetPartitionsPsWithAuthRequest();
-        req.setTblName(tbl.getTableName());
-        req.setDbName(tbl.getDbName());
-        req.setUserName(getUserName());
-        req.setMaxParts((short) -1);
-        req.setGroupNames(getGroupNames());
-        if (AcidUtils.isTransactionalTable(tbl)) {
-          ValidWriteIdList validWriteIdList = getValidWriteIdList(tbl.getDbName(), tbl.getTableName());
-          req.setValidWriteIdList(validWriteIdList != null ? validWriteIdList.toString() : null);
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_PARTITIONS);
+
+    try {
+      if (tbl.isPartitioned()) {
+        List<org.apache.hadoop.hive.metastore.api.Partition> tParts;
+        try {
+          GetPartitionsPsWithAuthRequest req = new GetPartitionsPsWithAuthRequest();
+          req.setTblName(tbl.getTableName());
+          req.setDbName(tbl.getDbName());
+          req.setUserName(getUserName());
+          req.setMaxParts((short) -1);
+          req.setGroupNames(getGroupNames());
+          if (AcidUtils.isTransactionalTable(tbl)) {
+            ValidWriteIdList validWriteIdList = getValidWriteIdList(tbl.getDbName(), tbl.getTableName());
+            req.setValidWriteIdList(validWriteIdList != null ? validWriteIdList.toString() : null);
+          }
+          GetPartitionsPsWithAuthResponse res = getMSC().listPartitionsWithAuthInfoRequest(req);
+          tParts = res.getPartitions();
+
+        } catch (Exception e) {
+          LOG.error(StringUtils.stringifyException(e));
+          throw new HiveException(e);
+        }
+        List<Partition> parts = new ArrayList<>(tParts.size());
+        for (org.apache.hadoop.hive.metastore.api.Partition tpart : tParts) {
+          parts.add(new Partition(tbl, tpart));
         }
-        GetPartitionsPsWithAuthResponse res = getMSC().listPartitionsWithAuthInfoRequest(req);
-        tParts = res.getPartitions();
 
-      } catch (Exception e) {
-        LOG.error(StringUtils.stringifyException(e));
-        throw new HiveException(e);
-      }
-      List<Partition> parts = new ArrayList<>(tParts.size());
-      for (org.apache.hadoop.hive.metastore.api.Partition tpart : tParts) {
-        parts.add(new Partition(tbl, tpart));
+        return parts;
+      } else {
+        return Collections.singletonList(new Partition(tbl));
       }
-      return parts;
-    } else {
-      return Collections.singletonList(new Partition(tbl));
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_PARTITIONS, "HS2-cache");
     }
   }
 
@@ -3733,26 +3757,32 @@ private void constructOneLBLocationMap(FileStatus fSta,
   public List<Partition> getPartitions(Table tbl, Map<String, String> partialPartSpec,
       short limit)
   throws HiveException {
-    if (!tbl.isPartitioned()) {
-      throw new HiveException(ErrorMsg.TABLE_NOT_PARTITIONED, tbl.getTableName());
-    }
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_PARTITIONS_2);
+    try {
+      if (!tbl.isPartitioned()) {
+        throw new HiveException(ErrorMsg.TABLE_NOT_PARTITIONED, tbl.getTableName());
+      }
 
-    List<String> partialPvals = MetaStoreUtils.getPvals(tbl.getPartCols(), partialPartSpec);
+      List<String> partialPvals = MetaStoreUtils.getPvals(tbl.getPartCols(), partialPartSpec);
 
-    List<org.apache.hadoop.hive.metastore.api.Partition> partitions = null;
-    try {
-      partitions = getMSC().listPartitionsWithAuthInfo(tbl.getDbName(), tbl.getTableName(),
-          partialPvals, limit, getUserName(), getGroupNames());
-    } catch (Exception e) {
-      throw new HiveException(e);
-    }
+      List<org.apache.hadoop.hive.metastore.api.Partition> partitions = null;
+      try {
+        partitions = getMSC().listPartitionsWithAuthInfo(tbl.getDbName(), tbl.getTableName(),
+                partialPvals, limit, getUserName(), getGroupNames());
+      } catch (Exception e) {
+        throw new HiveException(e);
+      }
 
-    List<Partition> qlPartitions = new ArrayList<Partition>();
-    for (org.apache.hadoop.hive.metastore.api.Partition p : partitions) {
-      qlPartitions.add( new Partition(tbl, p));
-    }
+      List<Partition> qlPartitions = new ArrayList<Partition>();
+      for (org.apache.hadoop.hive.metastore.api.Partition p : partitions) {
+        qlPartitions.add(new Partition(tbl, p));
+      }
 
-    return qlPartitions;
+      return qlPartitions;
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_PARTITIONS_2, "HS2-cache");
+    }
   }
 
   /**
@@ -3967,22 +3997,43 @@ private void constructOneLBLocationMap(FileStatus fSta,
    */
   public boolean getPartitionsByExpr(Table tbl, ExprNodeGenericFuncDesc expr, HiveConf conf,
       List<Partition> partitions) throws HiveException, TException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_PARTITIONS_BY_EXPR);
+    try {
+      Preconditions.checkNotNull(partitions);
+      byte[] exprBytes = SerializationUtilities.serializeExpressionToKryo(expr);
+      String defaultPartitionName = HiveConf.getVar(conf, ConfVars.DEFAULTPARTITIONNAME);
+      List<org.apache.hadoop.hive.metastore.api.PartitionSpec> msParts =
+              new ArrayList<>();
+      ValidWriteIdList validWriteIdList = null;
+      if (AcidUtils.isTransactionalTable(tbl)) {
+        validWriteIdList = getValidWriteIdList(tbl.getDbName(), tbl.getTableName());
+      }
 
-    Preconditions.checkNotNull(partitions);
-    byte[] exprBytes = SerializationUtilities.serializeExpressionToKryo(expr);
-    String defaultPartitionName = HiveConf.getVar(conf, ConfVars.DEFAULTPARTITIONNAME);
-    List<org.apache.hadoop.hive.metastore.api.PartitionSpec> msParts =
-        new ArrayList<>();
-    ValidWriteIdList validWriteIdList = null;
-    if (AcidUtils.isTransactionalTable(tbl)) {
-      validWriteIdList = getValidWriteIdList(tbl.getDbName(), tbl.getTableName());
+      PartitionsByExprRequest req = buildPartitionByExprRequest(tbl, exprBytes, defaultPartitionName, conf,
+              validWriteIdList != null ? validWriteIdList.toString() : null);
+
+      boolean hasUnknownParts = getMSC().listPartitionsSpecByExpr(req, msParts);
+      partitions.addAll(convertFromPartSpec(msParts.iterator(), tbl));
+
+      return hasUnknownParts;
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_PARTITIONS_BY_EXPR, "HS2-cache");
     }
-    boolean hasUnknownParts = getMSC().listPartitionsSpecByExpr(tbl.getDbName(),
-        tbl.getTableName(), exprBytes, defaultPartitionName, (short)-1, msParts,
-        validWriteIdList != null ? validWriteIdList.toString() : null);
-    partitions.addAll(convertFromPartSpec(msParts.iterator(), tbl));
-    return hasUnknownParts;
+  }
+
+  private PartitionsByExprRequest buildPartitionByExprRequest(Table tbl, byte[] exprBytes, String defaultPartitionName,
+                                                              HiveConf conf, String validWriteIdList) {
+    PartitionsByExprRequest req = new PartitionsByExprRequest(tbl.getDbName(), tbl.getTableName(),
+            ByteBuffer.wrap(exprBytes));
+    if (defaultPartitionName != null) {
+      req.setDefaultPartitionName(defaultPartitionName);
+    }
+    req.setCatName(getDefaultCatalog(conf));
+    req.setValidWriteIdList(validWriteIdList);
+    req.setId(tbl.getTTable().getId());
 
+    return req;
   }
 
   /**
@@ -5329,6 +5380,8 @@ private void constructOneLBLocationMap(FileStatus fSta,
       String dbName, String tableName, List<String> colNames, boolean checkTransactional)
       throws HiveException {
 
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_TABLE_COLUMN_STATS);
     List<ColumnStatisticsObj> retv = null;
     try {
       if (checkTransactional) {
@@ -5339,10 +5392,13 @@ private void constructOneLBLocationMap(FileStatus fSta,
       } else {
         retv = getMSC().getTableColumnStatistics(dbName, tableName, colNames, Constants.HIVE_ENGINE);
       }
+
       return retv;
     } catch (Exception e) {
       LOG.debug(StringUtils.stringifyException(e));
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_TABLE_COLUMN_STATS, "HS2-cache");
     }
   }
 
@@ -5368,6 +5424,8 @@ private void constructOneLBLocationMap(FileStatus fSta,
 
   public AggrStats getAggrColStatsFor(String dbName, String tblName,
      List<String> colNames, List<String> partName, boolean checkTransactional) {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_AGGR_COL_STATS);
     String writeIdList = null;
     try {
       if (checkTransactional) {
@@ -5375,10 +5433,15 @@ private void constructOneLBLocationMap(FileStatus fSta,
         AcidUtils.TableSnapshot tableSnapshot = AcidUtils.getTableSnapshot(conf, tbl);
         writeIdList = tableSnapshot != null ? tableSnapshot.getValidWriteIdList() : null;
       }
-      return getMSC().getAggrColStatsFor(dbName, tblName, colNames, partName, Constants.HIVE_ENGINE, writeIdList);
+      AggrStats result = getMSC().getAggrColStatsFor(dbName, tblName, colNames, partName, Constants.HIVE_ENGINE,
+              writeIdList);
+
+      return result;
     } catch (Exception e) {
       LOG.debug(StringUtils.stringifyException(e));
       return new AggrStats(new ArrayList<ColumnStatisticsObj>(),0);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_AGGR_COL_STATS, "HS2-cache");
     }
   }
 
@@ -5748,6 +5811,8 @@ private void constructOneLBLocationMap(FileStatus fSta,
 
   private PrimaryKeyInfo getPrimaryKeys(String dbName, String tblName, boolean onlyReliable)
       throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_PK);
     try {
       List<SQLPrimaryKey> primaryKeys = getMSC().getPrimaryKeys(new PrimaryKeysRequest(dbName, tblName));
       if (onlyReliable && primaryKeys != null && !primaryKeys.isEmpty()) {
@@ -5755,9 +5820,12 @@ private void constructOneLBLocationMap(FileStatus fSta,
           .filter(pk -> pk.isRely_cstr())
           .collect(Collectors.toList());
       }
+
       return new PrimaryKeyInfo(primaryKeys, tblName, dbName);
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_PK, "HS2-cache");
     }
   }
 
@@ -5787,6 +5855,8 @@ private void constructOneLBLocationMap(FileStatus fSta,
 
   private ForeignKeyInfo getForeignKeys(String dbName, String tblName, boolean onlyReliable)
       throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_FK);
     try {
       List<SQLForeignKey> foreignKeys = getMSC().getForeignKeys(new ForeignKeysRequest(null, null, dbName, tblName));
       if (onlyReliable && foreignKeys != null && !foreignKeys.isEmpty()) {
@@ -5794,9 +5864,12 @@ private void constructOneLBLocationMap(FileStatus fSta,
           .filter(fk -> fk.isRely_cstr())
           .collect(Collectors.toList());
       }
+
       return new ForeignKeyInfo(foreignKeys, tblName, dbName);
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_FK, "HS2-cache");
     }
   }
 
@@ -5826,6 +5899,8 @@ private void constructOneLBLocationMap(FileStatus fSta,
 
   private UniqueConstraint getUniqueConstraints(String dbName, String tblName, boolean onlyReliable)
       throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_UNIQ_CONSTRAINT);
     try {
       List<SQLUniqueConstraint> uniqueConstraints = getMSC().getUniqueConstraints(
               new UniqueConstraintsRequest(getDefaultCatalog(conf), dbName, tblName));
@@ -5834,9 +5909,12 @@ private void constructOneLBLocationMap(FileStatus fSta,
           .filter(uk -> uk.isRely_cstr())
           .collect(Collectors.toList());
       }
+
       return new UniqueConstraint(uniqueConstraints, tblName, dbName);
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_UNIQ_CONSTRAINT, "HS2-cache");
     }
   }
 
@@ -5937,6 +6015,8 @@ private void constructOneLBLocationMap(FileStatus fSta,
 
   private NotNullConstraint getNotNullConstraints(String dbName, String tblName, boolean onlyReliable)
       throws HiveException {
+    PerfLogger perfLogger = SessionState.getPerfLogger();
+    perfLogger.PerfLogBegin(CLASS_NAME, PerfLogger.HIVE_GET_NOT_NULL_CONSTRAINT);
     try {
       List<SQLNotNullConstraint> notNullConstraints = getMSC().getNotNullConstraints(
               new NotNullConstraintsRequest(getDefaultCatalog(conf), dbName, tblName));
@@ -5945,9 +6025,12 @@ private void constructOneLBLocationMap(FileStatus fSta,
           .filter(nnc -> nnc.isRely_cstr())
           .collect(Collectors.toList());
       }
+
       return new NotNullConstraint(notNullConstraints, tblName, dbName);
     } catch (Exception e) {
       throw new HiveException(e);
+    } finally {
+      perfLogger.PerfLogEnd(CLASS_NAME, PerfLogger.HIVE_GET_NOT_NULL_CONSTRAINT, "HS2-cache");
     }
   }
 
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
index ecb2a28..55939e5 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/SessionHiveMetaStoreClient.java
@@ -43,7 +43,7 @@ import org.apache.hadoop.hive.common.StatsSetupConst;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.io.HdfsUtils;
 import org.apache.hadoop.hive.metastore.HiveMetaHookLoader;
-import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.IMetaStoreClient;
 import org.apache.hadoop.hive.metastore.PartFilterExprUtil;
 import org.apache.hadoop.hive.metastore.PartitionDropOptions;
@@ -79,7 +79,6 @@ import org.apache.hadoop.hive.metastore.api.UnknownTableException;
 import org.apache.hadoop.hive.metastore.client.builder.PartitionBuilder;
 import org.apache.hadoop.hive.metastore.parser.ExpressionTree;
 import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy;
-import org.apache.hadoop.hive.metastore.utils.FilterUtils;
 import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
 import org.apache.hadoop.hive.ql.parse.SemanticAnalyzer;
 import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
@@ -112,7 +111,7 @@ import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.isExternalTa
  * so the readers of the objects in these maps should have the most recent view of the object.
  * But again, could be fragile.
  */
-public class SessionHiveMetaStoreClient extends HiveMetaStoreClient implements IMetaStoreClient {
+public class SessionHiveMetaStoreClient extends HiveMetaStoreClientWithLocalCache implements IMetaStoreClient {
   private static final Logger LOG = LoggerFactory.getLogger(SessionHiveMetaStoreClient.class);
 
   SessionHiveMetaStoreClient(Configuration conf, Boolean allowEmbedded) throws MetaException {
@@ -1203,20 +1202,17 @@ public class SessionHiveMetaStoreClient extends HiveMetaStoreClient implements I
   }
 
   @Override
-  public boolean listPartitionsSpecByExpr(String catName, String dbName, String tblName, byte[] expr,
-      String defaultPartitionName, short maxParts, List<PartitionSpec> result,
-      String validWriteIdList) throws TException {
-    org.apache.hadoop.hive.metastore.api.Table table = getTempTable(dbName, tblName);
+  public boolean listPartitionsSpecByExpr(PartitionsByExprRequest req, List<PartitionSpec> result) throws TException {
+    org.apache.hadoop.hive.metastore.api.Table table = getTempTable(req.getDbName(), req.getTblName());
     if (table == null) {
-      return super.listPartitionsSpecByExpr(catName, dbName, tblName, expr,
-          defaultPartitionName, maxParts, result, validWriteIdList);
+      return super.listPartitionsSpecByExpr(req, result);
     }
     assert result != null;
 
     result.addAll(
         MetaStoreServerUtils.getPartitionspecsGroupedByStorageDescriptor(table,
-            getPartitionsForMaxParts(tblName, getPartitionedTempTable(table).listPartitionsByFilter(
-                generateJDOFilter(table, expr, defaultPartitionName)), maxParts)));
+            getPartitionsForMaxParts(req.getTblName(), getPartitionedTempTable(table).listPartitionsByFilter(
+                generateJDOFilter(table, req.getExpr(), req.getDefaultPartitionName())), req.getMaxParts())));
     return result.isEmpty();
   }
 
diff --git a/ql/src/test/org/apache/hadoop/hive/metastore/TestMetastoreExpr.java b/ql/src/test/org/apache/hadoop/hive/metastore/TestMetastoreExpr.java
index 7160b9f..d0da0f8 100644
--- a/ql/src/test/org/apache/hadoop/hive/metastore/TestMetastoreExpr.java
+++ b/ql/src/test/org/apache/hadoop/hive/metastore/TestMetastoreExpr.java
@@ -18,6 +18,7 @@
 
 package org.apache.hadoop.hive.metastore;
 
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -31,6 +32,7 @@ import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
 import org.apache.hadoop.hive.metastore.api.Order;
 import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.PartitionSpec;
+import org.apache.hadoop.hive.metastore.api.PartitionsByExprRequest;
 import org.apache.hadoop.hive.metastore.api.SerDeInfo;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
@@ -137,26 +139,26 @@ public class TestMetastoreExpr {
 
     ExprBuilder e = new ExprBuilder(tblName);
 
-    checkExpr(3, dbName, tblName, e.val(0).intCol("p2").pred(">", 2).build());
-    checkExpr(3, dbName, tblName, e.intCol("p2").val(0).pred("<", 2).build());
-    checkExpr(1, dbName, tblName, e.intCol("p2").val(0).pred(">", 2).build());
-    checkExpr(2, dbName, tblName, e.val(31).intCol("p2").pred("<=", 2).build());
-    checkExpr(3, dbName, tblName, e.val("p11").strCol("p1").pred(">", 2).build());
+    checkExpr(3, dbName, tblName, e.val(0).intCol("p2").pred(">", 2).build(), tbl);
+    checkExpr(3, dbName, tblName, e.intCol("p2").val(0).pred("<", 2).build(), tbl);
+    checkExpr(1, dbName, tblName, e.intCol("p2").val(0).pred(">", 2).build(), tbl);
+    checkExpr(2, dbName, tblName, e.val(31).intCol("p2").pred("<=", 2).build(), tbl);
+    checkExpr(3, dbName, tblName, e.val("p11").strCol("p1").pred(">", 2).build(), tbl);
     checkExpr(1, dbName, tblName, e.val("p11").strCol("p1").pred(">", 2)
-        .intCol("p2").val(31).pred("<", 2).pred("and", 2).build());
+        .intCol("p2").val(31).pred("<", 2).pred("and", 2).build(), tbl);
     checkExpr(3, dbName, tblName,
-        e.val(32).val(31).intCol("p2").val(false).pred("between", 4).build());
+        e.val(32).val(31).intCol("p2").val(false).pred("between", 4).build(), tbl);
 
     addPartition(client, tbl, Lists.newArrayList("__HIVE_DEFAULT_PARTITION__", "36"), "part5");
     addPartition(client, tbl, Lists.newArrayList("p16", "__HIVE_DEFAULT_PARTITION__"), "part6");
 
     // Apply isnull and instr (not supported by pushdown) via name filtering.
     checkExpr(5, dbName, tblName, e.val("p").strCol("p1")
-        .fn("instr", TypeInfoFactory.intTypeInfo, 2).val(0).pred("<=", 2).build());
-    checkExpr(1, dbName, tblName, e.intCol("p2").pred("isnull", 1).build());
-    checkExpr(1, dbName, tblName, e.val("__HIVE_DEFAULT_PARTITION__").intCol("p2").pred("=", 2).build());
-    checkExpr(5, dbName, tblName, e.intCol("p1").pred("isnotnull", 1).build());
-    checkExpr(5, dbName, tblName, e.val("__HIVE_DEFAULT_PARTITION__").strCol("p1").pred("!=", 2).build());
+        .fn("instr", TypeInfoFactory.intTypeInfo, 2).val(0).pred("<=", 2).build(), tbl);
+    checkExpr(1, dbName, tblName, e.intCol("p2").pred("isnull", 1).build(), tbl);
+    checkExpr(1, dbName, tblName, e.val("__HIVE_DEFAULT_PARTITION__").intCol("p2").pred("=", 2).build(), tbl);
+    checkExpr(5, dbName, tblName, e.intCol("p1").pred("isnotnull", 1).build(), tbl);
+    checkExpr(5, dbName, tblName, e.val("__HIVE_DEFAULT_PARTITION__").strCol("p1").pred("!=", 2).build(), tbl);
 
     // Cannot deserialize => throw the specific exception.
     try {
@@ -168,7 +170,7 @@ public class TestMetastoreExpr {
 
     // Invalid expression => throw some exception, but not incompatible metastore.
     try {
-      checkExpr(-1, dbName, tblName, e.val(31).intCol("p3").pred(">", 2).build());
+      checkExpr(-1, dbName, tblName, e.val(31).intCol("p3").pred(">", 2).build(), tbl);
       fail("Should have thrown");
     } catch (IMetaStoreClient.IncompatibleMetastoreException ignore) {
       fail("Should not have thrown IncompatibleMetastoreException");
@@ -177,17 +179,20 @@ public class TestMetastoreExpr {
   }
 
   public void checkExpr(int numParts,
-      String dbName, String tblName, ExprNodeGenericFuncDesc expr) throws Exception {
+      String dbName, String tblName, ExprNodeGenericFuncDesc expr, Table t) throws Exception {
     List<Partition> parts = new ArrayList<Partition>();
     client.listPartitionsByExpr(dbName, tblName,
         SerializationUtilities.serializeExpressionToKryo(expr), null, (short)-1, parts);
     assertEquals("Partition check failed: " + expr.getExprString(), numParts, parts.size());
 
     // check with partition spec as well
+    PartitionsByExprRequest req = new PartitionsByExprRequest(dbName, tblName,
+            ByteBuffer.wrap(SerializationUtilities.serializeExpressionToKryo(expr)));
+    req.setMaxParts((short)-1);
+    req.setId(t.getId());
+
     List<PartitionSpec> partSpec = new ArrayList<>();
-    client.listPartitionsSpecByExpr(dbName, tblName,
-        SerializationUtilities.serializeExpressionToKryo(expr),
-        null, (short)-1, partSpec, null);
+    client.listPartitionsSpecByExpr(req, partSpec);
     int partSpecSize = 0;
     if(!partSpec.isEmpty()) {
       partSpecSize = partSpec.iterator().next().getSharedSDPartitionSpec().getPartitionsSize();
diff --git a/ql/src/test/org/apache/hadoop/hive/ql/TxnCommandsBaseForTests.java b/ql/src/test/org/apache/hadoop/hive/ql/TxnCommandsBaseForTests.java
index a59b364..c801d7f 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/TxnCommandsBaseForTests.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/TxnCommandsBaseForTests.java
@@ -35,6 +35,7 @@ import org.apache.hadoop.fs.LocatedFileStatus;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.RemoteIterator;
 import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.txn.TxnDbUtil;
 import org.apache.hadoop.hive.metastore.txn.TxnStore;
 import org.apache.hadoop.hive.metastore.txn.TxnUtils;
@@ -88,6 +89,11 @@ public abstract class TxnCommandsBaseForTests {
   @Before
   public void setUp() throws Exception {
     setUpInternal();
+
+    // set up metastore client cache
+    if (hiveConf.getBoolVar(HiveConf.ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
   }
   void initHiveConf() {
     hiveConf = new HiveConf(this.getClass());
diff --git a/ql/src/test/org/apache/hadoop/hive/ql/lockmgr/DbTxnManagerEndToEndTestBase.java b/ql/src/test/org/apache/hadoop/hive/ql/lockmgr/DbTxnManagerEndToEndTestBase.java
index 1979a19..bbbd365 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/lockmgr/DbTxnManagerEndToEndTestBase.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/lockmgr/DbTxnManagerEndToEndTestBase.java
@@ -18,6 +18,7 @@
 package org.apache.hadoop.hive.ql.lockmgr;
 
 import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.txn.TxnDbUtil;
 import org.apache.hadoop.hive.metastore.txn.TxnStore;
 import org.apache.hadoop.hive.metastore.txn.TxnUtils;
@@ -57,6 +58,10 @@ public abstract class DbTxnManagerEndToEndTestBase {
 
   @Before
   public void setUp() throws Exception {
+    // set up metastore client cache
+    if (conf.getBoolVar(HiveConf.ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
     SessionState.start(conf);
     ctx = new Context(conf);
     driver = new Driver(new QueryState.Builder().withHiveConf(conf).nonIsolated().build());
diff --git a/ql/src/test/org/apache/hadoop/hive/ql/metadata/TestSessionHiveMetastoreClientListPartitionsTempTable.java b/ql/src/test/org/apache/hadoop/hive/ql/metadata/TestSessionHiveMetastoreClientListPartitionsTempTable.java
index f6e7136..2c70aac 100644
--- a/ql/src/test/org/apache/hadoop/hive/ql/metadata/TestSessionHiveMetastoreClientListPartitionsTempTable.java
+++ b/ql/src/test/org/apache/hadoop/hive/ql/metadata/TestSessionHiveMetastoreClientListPartitionsTempTable.java
@@ -19,6 +19,7 @@
 package org.apache.hadoop.hive.ql.metadata;
 
 import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.IMetaStoreClient;
 import org.apache.hadoop.hive.metastore.TestMetastoreExpr;
 import org.apache.hadoop.hive.metastore.annotation.MetastoreCheckinTest;
@@ -26,6 +27,7 @@ import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
 import org.apache.hadoop.hive.metastore.api.Partition;
 import org.apache.hadoop.hive.metastore.api.PartitionSpec;
+import org.apache.hadoop.hive.metastore.api.PartitionsByExprRequest;
 import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet;
 import org.apache.hadoop.hive.metastore.api.PrivilegeGrantInfo;
 import org.apache.hadoop.hive.metastore.api.Table;
@@ -44,6 +46,7 @@ import org.junit.experimental.categories.Category;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
 
+import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -74,6 +77,10 @@ public class TestSessionHiveMetastoreClientListPartitionsTempTable
   public void setUp() throws Exception {
     initHiveConf();
     SessionState.start(conf);
+    // setup metastore client cache
+    if (conf.getBoolVar(HiveConf.ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
     setClient(Hive.get(conf).getMSC());
     getClient().dropDatabase(DB_NAME, true, true, true);
     getMetaStore().cleanWarehouseDirs();
@@ -316,100 +323,140 @@ public class TestSessionHiveMetastoreClientListPartitionsTempTable
 
   @Test
   public void testListPartitionsSpecByExpr() throws Exception {
-    createTable4PartColsParts(getClient());
+    Table t = createTable4PartColsParts(getClient()).table;
     TestMetastoreExpr.ExprBuilder e = new TestMetastoreExpr.ExprBuilder(TABLE_NAME);
-    checkExprPartitionSpec(2, e.strCol("yyyy").val("2017").pred("=", 2).build());
-    checkExprPartitionSpec(3, e.strCol("mm").val("11").pred(">", 2).build());
-    checkExprPartitionSpec(4, e.strCol("dd").val("29").pred(">=", 2).build());
-    checkExprPartitionSpec(2, e.strCol("yyyy").val("2017").pred("!=", 2).build());
+    checkExprPartitionSpec(2, e.strCol("yyyy").val("2017").pred("=", 2).build(), t);
+    checkExprPartitionSpec(3, e.strCol("mm").val("11").pred(">", 2).build(), t);
+    checkExprPartitionSpec(4, e.strCol("dd").val("29").pred(">=", 2).build(), t);
+    checkExprPartitionSpec(2, e.strCol("yyyy").val("2017").pred("!=", 2).build(), t);
     checkExprPartitionSpec(1, e.strCol("yyyy").val("2017").pred("=", 2)
-        .strCol("mm").val("10").pred(">=", 2).pred("and", 2).build());
+        .strCol("mm").val("10").pred(">=", 2).pred("and", 2).build(), t);
     checkExprPartitionSpec(3, e.strCol("dd").val("10").pred("<", 2).strCol("yyyy")
-        .val("2009").pred("!=", 2).pred("or", 2).build());
-    checkExprPartitionSpec(0, e.strCol("yyyy").val("2019").pred("=", 2).build());
+        .val("2009").pred("!=", 2).pred("or", 2).build(), t);
+    checkExprPartitionSpec(0, e.strCol("yyyy").val("2019").pred("=", 2).build(), t);
   }
 
   @Test(expected = AssertionError.class)
   public void testListPartitionsSpecByExprNullResult() throws Exception {
-    createTable4PartColsParts(getClient());
+    Table t = createTable4PartColsParts(getClient()).table;
+
     TestMetastoreExpr.ExprBuilder e = new TestMetastoreExpr.ExprBuilder(TABLE_NAME);
-    getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME, SerializationUtilities.serializeExpressionToKryo(
-        e.strCol("yyyy").val("2017").pred("=", 2).build()), null,
-        (short)-1, null, null);
+
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, TABLE_NAME,
+            ByteBuffer.wrap(SerializationUtilities.serializeExpressionToKryo(
+                    e.strCol("yyyy").val("2017").pred("=", 2).build())));
+    req.setMaxParts((short)-1);
+    req.setId(t.getId());
+
+    getClient().listPartitionsSpecByExpr(req, null);
   }
 
 
 
   @Test
   public void testListPartitionsSpecByExprDefMaxParts() throws Exception {
-    createTable4PartColsParts(getClient());
+    Table t = createTable4PartColsParts(getClient()).table;
     TestMetastoreExpr.ExprBuilder e = new TestMetastoreExpr.ExprBuilder(TABLE_NAME);
     List<PartitionSpec> result = new ArrayList<>();
-    getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME, SerializationUtilities.serializeExpressionToKryo(
-        e.strCol("yyyy").val("2017").pred(">=", 2).build()),
-        null, (short)3, result, null);
+
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, TABLE_NAME,
+            ByteBuffer.wrap(SerializationUtilities.serializeExpressionToKryo(
+                    e.strCol("yyyy").val("2017").pred(">=", 2).build())));
+    req.setMaxParts((short)3);
+    req.setId(t.getId());
+
+    getClient().listPartitionsSpecByExpr(req, result);
     assertEquals(3, result.iterator().next().getSharedSDPartitionSpec().getPartitionsSize());
   }
 
   @Test
   public void testListPartitionsSpecByExprHighMaxParts() throws Exception {
-    createTable4PartColsParts(getClient());
+    Table t = createTable4PartColsParts(getClient()).table;
     TestMetastoreExpr.ExprBuilder e = new TestMetastoreExpr.ExprBuilder(TABLE_NAME);
     List<PartitionSpec> result = new ArrayList<>();
-    getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME, SerializationUtilities.serializeExpressionToKryo(
-        e.strCol("yyyy").val("2017").pred(">=", 2).build()),
-        null, (short)100, result, null);
+
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, TABLE_NAME,
+            ByteBuffer.wrap(SerializationUtilities.serializeExpressionToKryo(
+                    e.strCol("yyyy").val("2017").pred(">=", 2).build())));
+    req.setMaxParts((short)100);
+    req.setId(t.getId());
+
+    getClient().listPartitionsSpecByExpr(req, result);
     assertEquals(4, result.iterator().next().getSharedSDPartitionSpec().getPartitionsSize());
   }
 
   @Test(expected = NoSuchObjectException.class)
   public void testListPartitionsSpecByExprNoDb() throws Exception {
     getClient().dropDatabase(DB_NAME);
-    getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME, new byte[] {'f', 'o', 'o'},
-        null, (short)-1, new ArrayList<>(), null);
+
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, TABLE_NAME,
+            ByteBuffer.wrap(new byte[] {'f', 'o', 'o'}));
+    req.setMaxParts((short)-1);
+
+    getClient().listPartitionsSpecByExpr(req, null);
   }
 
   @Test(expected = MetaException.class)
   public void testListPartitionsSpecByExprNoTbl() throws Exception {
-    getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME, new byte[] {'f', 'o', 'o'},
-        null, (short)-1, new ArrayList<>(), null);
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, TABLE_NAME,
+            ByteBuffer.wrap(new byte[] {'f', 'o', 'o'}));
+    req.setMaxParts((short)-1);
+
+    getClient().listPartitionsSpecByExpr(req, new ArrayList<>());
   }
 
   @Test(expected = MetaException.class)
   public void testListPartitionsSpecByExprEmptyDbName() throws Exception {
-    getClient().listPartitionsSpecByExpr("", TABLE_NAME, new byte[] {'f', 'o', 'o'},
-        null, (short)-1, new ArrayList<>(), null);
+    PartitionsByExprRequest req = new PartitionsByExprRequest("", TABLE_NAME,
+            ByteBuffer.wrap(new byte[] {'f', 'o', 'o'}));
+    req.setMaxParts((short)-1);
+
+    getClient().listPartitionsSpecByExpr(req, new ArrayList<>());
   }
 
   @Test(expected = MetaException.class)
   public void testListPartitionsSpecByExprEmptyTblName() throws Exception {
-    createTable3PartCols1Part(getClient());
-    getClient().listPartitionsSpecByExpr(DB_NAME, "", new byte[] {'f', 'o', 'o'},
-        null, (short)-1, new ArrayList<>(), null);
+    Table t = createTable3PartCols1Part(getClient());
+
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, "",
+            ByteBuffer.wrap(new byte[] {'f', 'o', 'o'}));
+    req.setMaxParts((short)-1);
+    req.setId(t.getId());
+
+    getClient().listPartitionsSpecByExpr(req, new ArrayList<>());
   }
 
   @Test(expected = MetaException.class)
   public void testListPartitionsSpecByExprNullDbName() throws Exception {
-    getClient().listPartitionsSpecByExpr(null, TABLE_NAME, new byte[] {'f', 'o', 'o'},
-        null, (short)-1, new ArrayList<>(), null);
+    PartitionsByExprRequest req = new PartitionsByExprRequest(null, TABLE_NAME,
+            ByteBuffer.wrap(new byte[] {'f', 'o', 'o'}));
+    req.setMaxParts((short)-1);
+
+    getClient().listPartitionsSpecByExpr(req, null);
   }
 
   @Test(expected = MetaException.class)
   public void testListPartitionsSpecByExprNullTblName() throws Exception {
-    getClient().listPartitionsSpecByExpr(DB_NAME, null, new byte[] {'f', 'o', 'o' },
-        null, (short)-1, new ArrayList<>(), null);
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, null,
+            ByteBuffer.wrap(new byte[] {'f', 'o', 'o'}));
+    req.setMaxParts((short)-1);
+
+    getClient().listPartitionsSpecByExpr(req, null);
   }
 
-  private void checkExprPartitionSpec(int numParts, ExprNodeGenericFuncDesc expr) throws Exception {
+  private void checkExprPartitionSpec(int numParts, ExprNodeGenericFuncDesc expr, Table t) throws Exception {
     List<Partition> parts = new ArrayList<>();
     getClient().listPartitionsByExpr(DB_NAME, TABLE_NAME, SerializationUtilities.serializeExpressionToKryo(expr),
         null, (short) -1, parts);
     assertEquals("Partition check failed: " + expr.getExprString(), numParts, parts.size());
     // check with partition spec as well
+    PartitionsByExprRequest req = new PartitionsByExprRequest(DB_NAME, TABLE_NAME,
+            ByteBuffer.wrap(SerializationUtilities.serializeExpressionToKryo(expr)));
+    req.setMaxParts((short)-1);
+    req.setId(t.getId());
+
     List<PartitionSpec> partSpec = new ArrayList<>();
-    getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME,
-        SerializationUtilities.serializeExpressionToKryo(expr), null,
-        (short)-1, partSpec, null);
+    getClient().listPartitionsSpecByExpr(req, partSpec);
     int partSpecSize = 0;
     if(!partSpec.isEmpty()) {
       partSpecSize = partSpec.iterator().next().getSharedSDPartitionSpec().getPartitionsSize();
diff --git a/service/src/java/org/apache/hive/service/server/HiveServer2.java b/service/src/java/org/apache/hive/service/server/HiveServer2.java
index 404f161..6c7ad74 100644
--- a/service/src/java/org/apache/hive/service/server/HiveServer2.java
+++ b/service/src/java/org/apache/hive/service/server/HiveServer2.java
@@ -62,6 +62,7 @@ import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
 import org.apache.hadoop.hive.conf.HiveServer2TransportMode;
 import org.apache.hadoop.hive.llap.coordinator.LlapCoordinator;
 import org.apache.hadoop.hive.llap.registry.impl.LlapRegistryService;
+import org.apache.hadoop.hive.metastore.HiveMetaStoreClientWithLocalCache;
 import org.apache.hadoop.hive.metastore.api.WMFullResourcePlan;
 import org.apache.hadoop.hive.metastore.api.WMPool;
 import org.apache.hadoop.hive.metastore.api.WMResourcePlan;
@@ -286,6 +287,11 @@ public class HiveServer2 extends CompositeService {
       }
     }
 
+    // setup metastore client cache
+    if (hiveConf.getBoolVar(ConfVars.MSC_CACHE_ENABLED)) {
+      HiveMetaStoreClientWithLocalCache.init();
+    }
+
     try {
       NotificationEventPoll.initialize(hiveConf);
     } catch (Exception err) {
diff --git a/standalone-metastore/metastore-common/pom.xml b/standalone-metastore/metastore-common/pom.xml
index 521e92b..827c1e9 100644
--- a/standalone-metastore/metastore-common/pom.xml
+++ b/standalone-metastore/metastore-common/pom.xml
@@ -239,6 +239,10 @@
       </exclusions>
     </dependency>
     <dependency>
+    <groupId>com.github.ben-manes.caffeine</groupId>
+    <artifactId>caffeine</artifactId>
+    </dependency>
+    <dependency>
       <groupId>org.apache.curator</groupId>
       <artifactId>curator-recipes</artifactId>
       <version>${curator.version}</version>
diff --git a/standalone-metastore/metastore-common/spotbugs/spotbugs-exclude.xml b/standalone-metastore/metastore-common/spotbugs/spotbugs-exclude.xml
index e2c76d0..446c91a 100644
--- a/standalone-metastore/metastore-common/spotbugs/spotbugs-exclude.xml
+++ b/standalone-metastore/metastore-common/spotbugs/spotbugs-exclude.xml
@@ -21,4 +21,7 @@
     <Match>
         <Class name="~org.apache.hadoop.hive.metastore.api.*" />
     </Match>
+    <Match>
+        <Class name="~org.apache.hadoop.hive.metastore.metrics.*" />
+    </Match>
 </FindBugsFilter>
diff --git a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
index 84a86c5..e7c339c 100644
--- a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
+++ b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClient.java
@@ -100,6 +100,9 @@ import com.google.common.collect.Lists;
 @InterfaceAudience.Public
 @InterfaceStability.Evolving
 public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
+
+  private final String CLASS_NAME = HiveMetaStoreClient.class.getName();
+
   /**
    * Capabilities of the current client. If this client talks to a MetaStore server in a manner
    * implying the usage of some expanded features that require client-side support that this client
@@ -1042,14 +1045,25 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
   public AggrStats getAggrColStatsFor(String catName, String dbName, String tblName, List<String> colNames,
       List<String> partNames, String engine, String writeIdList)
       throws NoSuchObjectException, MetaException, TException {
-    if (colNames.isEmpty() || partNames.isEmpty()) {
-      LOG.debug("Columns is empty or partNames is empty : Short-circuiting stats eval on client side.");
-      return new AggrStats(new ArrayList<>(), 0); // Nothing to aggregate
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (colNames.isEmpty() || partNames.isEmpty()) {
+        LOG.debug("Columns is empty or partNames is empty : Short-circuiting stats eval on client side.");
+        return new AggrStats(new ArrayList<>(), 0); // Nothing to aggregate
+      }
+      PartitionsStatsRequest req = new PartitionsStatsRequest(dbName, tblName, colNames, partNames, engine);
+      req.setCatName(catName);
+      req.setValidWriteIdList(writeIdList);
+
+      return client.get_aggr_stats_for(req);
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getAggrColStatsFor",
+            diff, "HMS client");
+      }
     }
-    PartitionsStatsRequest req = new PartitionsStatsRequest(dbName, tblName, colNames, partNames, engine);
-    req.setCatName(catName);
-    req.setValidWriteIdList(writeIdList);
-    return client.get_aggr_stats_for(req);
   }
 
   @Override
@@ -1090,7 +1104,7 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
    * @throws MetaException
    * @throws NoSuchObjectException
    * @throws TException
-   * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface#create_table(org.apache.hadoop.hive.metastore.api.CreateTableRequest)
+   * @see org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Iface #create_table(org.apache.hadoop.hive.metastore.api.CreateTableRequest)
    */
   @Override
   public void createTable(Table tbl) throws AlreadyExistsException,
@@ -1869,9 +1883,19 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
                                                     int maxParts, String userName,
                                                     List<String> groupNames) throws TException {
     // TODO should we add capabilities here as well as it returns Partition objects
-    List<Partition> parts = client.get_partitions_with_auth(prependCatalogToDbName(catName,
-        dbName, conf), tableName, shrinkMaxtoShort(maxParts), userName, groupNames);
-    return deepCopyPartitions(FilterUtils.filterPartitionsIfEnabled(isClientFilterEnabled, filterHook, parts));
+    long t1 = System.currentTimeMillis();
+    try {
+      List<Partition> parts = client.get_partitions_with_auth(prependCatalogToDbName(catName,
+              dbName, conf), tableName, shrinkMaxtoShort(maxParts), userName, groupNames);
+
+      return deepCopyPartitions(FilterUtils.filterPartitionsIfEnabled(isClientFilterEnabled, filterHook, parts));
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "listPartitionsWithAuthInfo",
+            diff, "HMS client");
+      }
+    }
   }
 
   @Override
@@ -1890,9 +1914,20 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
                                                     String userName, List<String> groupNames)
       throws TException {
     // TODO should we add capabilities here as well as it returns Partition objects
-    List<Partition> parts = client.get_partitions_ps_with_auth(prependCatalogToDbName(catName,
-        dbName, conf), tableName, partialPvals, shrinkMaxtoShort(maxParts), userName, groupNames);
-    return deepCopyPartitions(FilterUtils.filterPartitionsIfEnabled(isClientFilterEnabled, filterHook, parts));
+    long t1 = System.currentTimeMillis();
+    try {
+      List<Partition> parts = client.get_partitions_ps_with_auth(prependCatalogToDbName(catName,
+              dbName, conf), tableName, partialPvals, shrinkMaxtoShort(maxParts), userName, groupNames);
+
+      return deepCopyPartitions(FilterUtils.filterPartitionsIfEnabled(isClientFilterEnabled, filterHook,
+              parts));
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "listPartitionsWithAuthInfo",
+            diff, "HMS client");
+      }
+    }
   }
 
   @Override
@@ -1936,13 +1971,11 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
         default_partition_name, max_parts, result);
   }
 
-  @Override
-  public boolean listPartitionsByExpr(String catName, String db_name, String tbl_name, byte[] expr,
-      String default_partition_name, int max_parts, List<Partition> result)
-          throws TException {
-    assert result != null;
+  protected PartitionsByExprRequest buildPartitionsByExprRequest(String catName, String db_name, String tbl_name, byte[] expr,
+                                                                 String default_partition_name, int max_parts) {
     PartitionsByExprRequest req = new PartitionsByExprRequest(
-        db_name, tbl_name, ByteBuffer.wrap(expr));
+            db_name, tbl_name, ByteBuffer.wrap(expr));
+
     if( catName == null ) {
       req.setCatName(getDefaultCatalog(conf));
     }else {
@@ -1955,66 +1988,93 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
       req.setMaxParts(shrinkMaxtoShort(max_parts));
     }
     req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(db_name, tbl_name)));
-    PartitionsByExprResult r;
+    return req;
+  }
+
+  protected PartitionsByExprResult getPartitionsByExprResult(PartitionsByExprRequest req) throws TException {
+    return client.get_partitions_by_expr(req);
+  }
+
+  @Override
+  public boolean listPartitionsByExpr(String catName, String db_name, String tbl_name, byte[] expr,
+      String default_partition_name, int max_parts, List<Partition> result)
+          throws TException {
+    long t1 = System.currentTimeMillis();
+
     try {
-      r = client.get_partitions_by_expr(req);
-    } catch (TApplicationException te) {
-      // TODO: backward compat for Hive <= 0.12. Can be removed later.
-      if (te.getType() != TApplicationException.UNKNOWN_METHOD
-          && te.getType() != TApplicationException.WRONG_METHOD_NAME) {
-        throw te;
+      assert result != null;
+      PartitionsByExprRequest req = buildPartitionsByExprRequest(catName, db_name, tbl_name, expr, default_partition_name,
+              max_parts);
+
+      PartitionsByExprResult r = null;
+
+      try {
+        r = getPartitionsByExprResult(req);
+      } catch (TApplicationException te) {
+        rethrowException(te);
+      }
+
+      assert r != null;
+      r.setPartitions(FilterUtils.filterPartitionsIfEnabled(isClientFilterEnabled, filterHook, r.getPartitions()));
+      // TODO: in these methods, do we really need to deepcopy?
+      //deepCopyPartitions(r.getPartitions(), result);
+      result.addAll(r.getPartitions());
+
+      return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "listPartitionsByExpr",
+            diff, "HMS client");
       }
-      throw new IncompatibleMetastoreException(
-          "Metastore does not support listPartitionsByExpr: " + te.getMessage());
     }
+  }
+
 
-    r.setPartitions(FilterUtils.filterPartitionsIfEnabled(isClientFilterEnabled, filterHook, r.getPartitions()));
-    // TODO: in these methods, do we really need to deepcopy?
-    //deepCopyPartitions(r.getPartitions(), result);
-    result.addAll(r.getPartitions());
-    return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions(); // Assume the worst.
+  private void rethrowException(TApplicationException te) throws TException{
+    // TODO: backward compat for Hive <= 0.12. Can be removed later.
+    if (te.getType() != TApplicationException.UNKNOWN_METHOD
+            && te.getType() != TApplicationException.WRONG_METHOD_NAME) {
+      throw te;
+    }
+    throw new IncompatibleMetastoreException(
+            "Metastore doesn't support listPartitionsByExpr: " + te.getMessage());
   }
 
-  @Override
-  public boolean listPartitionsSpecByExpr(String dbName, String tblName,
-      byte[] expr, String defaultPartName, short maxParts, List<PartitionSpec> result, String validWriteIdList)
-      throws TException {
-    return listPartitionsSpecByExpr(getDefaultCatalog(conf), dbName, tblName, expr, defaultPartName,
-        maxParts, result, validWriteIdList);
+  protected PartitionsSpecByExprResult getPartitionsSpecByExprResult(PartitionsByExprRequest req) throws TException {
+    return client.get_partitions_spec_by_expr(req);
   }
 
+
   @Override
-  public boolean listPartitionsSpecByExpr(String catName, String dbName, String tblName, byte[] expr,
-      String defaultPartitionName, short maxParts, List<PartitionSpec> result, String validWriteIdList)
+  public boolean listPartitionsSpecByExpr(PartitionsByExprRequest req, List<PartitionSpec> result)
       throws TException {
-    assert result != null;
-    PartitionsByExprRequest req = new PartitionsByExprRequest(
-        dbName, tblName, ByteBuffer.wrap(expr));
-    if (defaultPartitionName != null) {
-      req.setDefaultPartitionName(defaultPartitionName);
-    }
-    if (maxParts >= 0) {
-      req.setMaxParts(maxParts);
-    }
-    req.setValidWriteIdList(validWriteIdList);
-    PartitionsSpecByExprResult r;
+    long t1 = System.currentTimeMillis();
+
     try {
-      r = client.get_partitions_spec_by_expr(req);
-    } catch (TApplicationException te) {
-      if (te.getType() != TApplicationException.UNKNOWN_METHOD
-          && te.getType() != TApplicationException.WRONG_METHOD_NAME) {
-        throw te;
+      assert result != null;
+      PartitionsSpecByExprResult r = null;
+      try {
+        r = getPartitionsSpecByExprResult(req);
+      } catch (TApplicationException te) {
+        rethrowException(te);
       }
-      throw new IncompatibleMetastoreException(
-          "Metastore doesn't support listPartitionsByExpr: " + te.getMessage());
-    }
 
-    // do client side filtering
-    r.setPartitionsSpec(FilterUtils.filterPartitionSpecsIfEnabled(
-        isClientFilterEnabled, filterHook, r.getPartitionsSpec()));
+      assert r != null;
+      // do client side filtering
+      r.setPartitionsSpec(FilterUtils.filterPartitionSpecsIfEnabled(
+              isClientFilterEnabled, filterHook, r.getPartitionsSpec()));
+
+      result.addAll(r.getPartitionsSpec());
 
-    result.addAll(r.getPartitionsSpec());
-    return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions();
+      return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "listPartitionsSpecByExpr",
+            diff, "HMS client");
+      }
+    }
   }
 
   @Override
@@ -2024,19 +2084,30 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
 
   @Override
   public Database getDatabase(String catalogName, String databaseName) throws TException {
-    GetDatabaseRequest request = new GetDatabaseRequest();
-    if (databaseName != null)
-      request.setName(databaseName);
-    if (catalogName != null)
-      request.setCatalogName(catalogName);
-    if (processorCapabilities != null) {
-      request.setProcessorCapabilities(new ArrayList<>(Arrays.asList(processorCapabilities)));
-    }
-    if (processorIdentifier != null) {
-      request.setProcessorIdentifier(processorIdentifier);
+    long t1 = System.currentTimeMillis();
+
+    try {
+      GetDatabaseRequest request = new GetDatabaseRequest();
+      if (databaseName != null)
+        request.setName(databaseName);
+      if (catalogName != null)
+        request.setCatalogName(catalogName);
+      if (processorCapabilities != null) {
+        request.setProcessorCapabilities(new ArrayList<>(Arrays.asList(processorCapabilities)));
+      }
+      if (processorIdentifier != null) {
+        request.setProcessorIdentifier(processorIdentifier);
+      }
+      Database d = client.get_database_req(request);
+
+      return deepCopy(FilterUtils.filterDbIfEnabled(isClientFilterEnabled, filterHook, d));
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getDatabase",
+            diff, "HMS client");
+      }
     }
-    Database d = client.get_database_req(request);
-    return deepCopy(FilterUtils.filterDbIfEnabled(isClientFilterEnabled, filterHook, d));
   }
 
   @Override
@@ -2167,22 +2238,33 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
 
   public Table getTable(String catName, String dbName, String tableName,
       boolean getColumnStats, String engine) throws TException {
-    GetTableRequest req = new GetTableRequest(dbName, tableName);
-    req.setCatName(catName);
-    req.setCapabilities(version);
-    req.setGetColumnStats(getColumnStats);
-    req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tableName)));
+    long t1 = System.currentTimeMillis();
 
-    if (getColumnStats) {
-      req.setEngine(engine);
-    }
-    if (processorCapabilities != null)
-      req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
-    if (processorIdentifier != null)
-      req.setProcessorIdentifier(processorIdentifier);
+    try {
+      GetTableRequest req = new GetTableRequest(dbName, tableName);
+      req.setCatName(catName);
+      req.setCapabilities(version);
+      req.setGetColumnStats(getColumnStats);
+      req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tableName)));
+
+      if (getColumnStats) {
+        req.setEngine(engine);
+      }
+      if (processorCapabilities != null)
+        req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
+      if (processorIdentifier != null)
+        req.setProcessorIdentifier(processorIdentifier);
 
-    Table t = client.get_table_req(req).getTable();
-    return deepCopy(FilterUtils.filterTableIfEnabled(isClientFilterEnabled, filterHook, t));
+      Table t = client.get_table_req(req).getTable();
+
+      return deepCopy(FilterUtils.filterTableIfEnabled(isClientFilterEnabled, filterHook, t));
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getTable",
+            diff, "HMS client");
+      }
+    }
   }
 
   @Override
@@ -2194,25 +2276,36 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
   @Override
   public Table getTable(String catName, String dbName, String tableName, String validWriteIdList,
       boolean getColumnStats, String engine) throws TException {
-    GetTableRequest req = new GetTableRequest(dbName, tableName);
-    req.setCatName(catName);
-    req.setCapabilities(version);
-    if (validWriteIdList != null) {
-      req.setValidWriteIdList(validWriteIdList);
-    }else{
-      req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tableName)));
-    }
-    req.setGetColumnStats(getColumnStats);
-    if (getColumnStats) {
-      req.setEngine(engine);
-    }
-    if (processorCapabilities != null)
-      req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
-    if (processorIdentifier != null)
-      req.setProcessorIdentifier(processorIdentifier);
+    long t1 = System.currentTimeMillis();
+
+    try {
+      GetTableRequest req = new GetTableRequest(dbName, tableName);
+      req.setCatName(catName);
+      req.setCapabilities(version);
+      if (validWriteIdList != null) {
+        req.setValidWriteIdList(validWriteIdList);
+      } else {
+        req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tableName)));
+      }
+      req.setGetColumnStats(getColumnStats);
+      if (getColumnStats) {
+        req.setEngine(engine);
+      }
+      if (processorCapabilities != null)
+        req.setProcessorCapabilities(new ArrayList<String>(Arrays.asList(processorCapabilities)));
+      if (processorIdentifier != null)
+        req.setProcessorIdentifier(processorIdentifier);
+
+      Table t = client.get_table_req(req).getTable();
 
-    Table t = client.get_table_req(req).getTable();
-    return deepCopy(FilterUtils.filterTableIfEnabled(isClientFilterEnabled, filterHook, t));
+      return deepCopy(FilterUtils.filterTableIfEnabled(isClientFilterEnabled, filterHook, t));
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getTable",
+            diff, "HMS client");
+      }
+    }
   }
 
   @Override
@@ -2618,37 +2711,81 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
 
   @Override
   public List<SQLPrimaryKey> getPrimaryKeys(PrimaryKeysRequest req) throws TException {
-    if (!req.isSetCatName()) {
-      req.setCatName(getDefaultCatalog(conf));
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (!req.isSetCatName()) {
+        req.setCatName(getDefaultCatalog(conf));
+      }
+
+      return client.get_primary_keys(req).getPrimaryKeys();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getPrimaryKeys",
+            diff, "HMS client");
+      }
     }
-    return client.get_primary_keys(req).getPrimaryKeys();
   }
 
   @Override
   public List<SQLForeignKey> getForeignKeys(ForeignKeysRequest req) throws MetaException,
       NoSuchObjectException, TException {
-    if (!req.isSetCatName()) {
-      req.setCatName(getDefaultCatalog(conf));
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (!req.isSetCatName()) {
+        req.setCatName(getDefaultCatalog(conf));
+      }
+
+      return client.get_foreign_keys(req).getForeignKeys();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getForeignKeys",
+            diff, "HMS client");
+      }
     }
-    return client.get_foreign_keys(req).getForeignKeys();
   }
 
   @Override
   public List<SQLUniqueConstraint> getUniqueConstraints(UniqueConstraintsRequest req)
       throws MetaException, NoSuchObjectException, TException {
-    if (!req.isSetCatName()) {
-      req.setCatName(getDefaultCatalog(conf));
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (!req.isSetCatName()) {
+        req.setCatName(getDefaultCatalog(conf));
+      }
+
+      return client.get_unique_constraints(req).getUniqueConstraints();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getUniqueConstraints",
+            diff, "HMS client");
+      }
     }
-    return client.get_unique_constraints(req).getUniqueConstraints();
   }
 
   @Override
   public List<SQLNotNullConstraint> getNotNullConstraints(NotNullConstraintsRequest req)
       throws MetaException, NoSuchObjectException, TException {
-    if (!req.isSetCatName()) {
-      req.setCatName(getDefaultCatalog(conf));
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (!req.isSetCatName()) {
+        req.setCatName(getDefaultCatalog(conf));
+      }
+
+      return client.get_not_null_constraints(req).getNotNullConstraints();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getNotNullConstraints",
+            diff, "HMS client");
+      }
     }
-    return client.get_not_null_constraints(req).getNotNullConstraints();
   }
 
   @Override
@@ -2728,14 +2865,25 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
   @Override
   public List<ColumnStatisticsObj> getTableColumnStatistics(String catName, String dbName,
       String tableName, List<String> colNames, String engine) throws TException {
-    if(colNames.isEmpty()) {
-      return Collections.emptyList();
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (colNames.isEmpty()) {
+        return Collections.emptyList();
+      }
+      TableStatsRequest rqst = new TableStatsRequest(dbName, tableName, colNames, engine);
+      rqst.setCatName(catName);
+      rqst.setEngine(engine);
+      rqst.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tableName)));
+
+      return client.get_table_statistics_req(rqst).getTableStats();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getTableColumnStatistics",
+            diff, "HMS client");
+      }
     }
-    TableStatsRequest rqst = new TableStatsRequest(dbName, tableName, colNames, engine);
-    rqst.setCatName(catName);
-    rqst.setEngine(engine);
-    rqst.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tableName)));
-    return client.get_table_statistics_req(rqst).getTableStats();
   }
 
   @Override
@@ -2748,14 +2896,25 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
   @Override
   public List<ColumnStatisticsObj> getTableColumnStatistics(String catName, String dbName,
       String tableName, List<String> colNames, String engine, String validWriteIdList) throws TException {
-    if(colNames.isEmpty()) {
-      return Collections.emptyList();
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (colNames.isEmpty()) {
+        return Collections.emptyList();
+      }
+      TableStatsRequest rqst = new TableStatsRequest(dbName, tableName, colNames, engine);
+      rqst.setEngine(engine);
+      rqst.setCatName(catName);
+      rqst.setValidWriteIdList(validWriteIdList);
+
+      return client.get_table_statistics_req(rqst).getTableStats();
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getTableColumnStatistics",
+            diff, "HMS client");
+      }
     }
-    TableStatsRequest rqst = new TableStatsRequest(dbName, tableName, colNames, engine);
-    rqst.setCatName(catName);
-    rqst.setEngine(engine);
-    rqst.setValidWriteIdList(validWriteIdList);
-    return client.get_table_statistics_req(rqst).getTableStats();
   }
 
   @Override
@@ -2840,7 +2999,17 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
   @Override
   public String getConfigValue(String name, String defaultValue)
       throws TException, ConfigValSecurityException {
-    return client.get_config_value(name, defaultValue);
+    long t1 = System.currentTimeMillis();
+
+    try {
+      return client.get_config_value(name, defaultValue);
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getConfigValue",
+            diff, "HMS client");
+      }
+    }
   }
 
   @Override
@@ -3820,14 +3989,25 @@ public class HiveMetaStoreClient implements IMetaStoreClient, AutoCloseable {
   @Override
   public AggrStats getAggrColStatsFor(String catName, String dbName, String tblName,
       List<String> colNames, List<String> partNames, String engine) throws TException {
-    if (colNames.isEmpty() || partNames.isEmpty()) {
-      LOG.debug("Columns is empty or partNames is empty : Short-circuiting stats eval on client side.");
-      return new AggrStats(new ArrayList<>(),0); // Nothing to aggregate
+    long t1 = System.currentTimeMillis();
+
+    try {
+      if (colNames.isEmpty() || partNames.isEmpty()) {
+        LOG.debug("Columns is empty or partNames is empty : Short-circuiting stats eval on client side.");
+        return new AggrStats(new ArrayList<>(), 0); // Nothing to aggregate
+      }
+      PartitionsStatsRequest req = new PartitionsStatsRequest(dbName, tblName, colNames, partNames, engine);
+      req.setCatName(catName);
+      req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tblName)));
+
+      return client.get_aggr_stats_for(req);
+    } finally {
+      long diff = System.currentTimeMillis() - t1;
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("class={}, method={}, duration={}, comments={}", CLASS_NAME, "getAggrColStatsFor",
+            diff, "HMS client");
+      }
     }
-    PartitionsStatsRequest req = new PartitionsStatsRequest(dbName, tblName, colNames, partNames, engine);
-    req.setCatName(catName);
-    req.setValidWriteIdList(getValidWriteIdList(TableName.getDbTable(dbName, tblName)));
-    return client.get_aggr_stats_for(req);
   }
 
   @Override
diff --git a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientWithLocalCache.java b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientWithLocalCache.java
new file mode 100644
index 0000000..4146d52
--- /dev/null
+++ b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientWithLocalCache.java
@@ -0,0 +1,274 @@
+package org.apache.hadoop.hive.metastore;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.PartitionsByExprRequest;
+import org.apache.hadoop.hive.metastore.api.PartitionsByExprResult;
+import org.apache.hadoop.hive.metastore.api.PartitionsSpecByExprResult;
+import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.ql.util.IncrementalObjectSizeEstimator;
+import org.apache.hadoop.hive.ql.util.IncrementalObjectSizeEstimator.ObjectEstimator;
+import org.apache.thrift.TException;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Objects;
+
+/**
+ * This class introduces a caching layer in HS2 for metadata for some selected query APIs. It extends
+ * HiveMetaStoreClient, and overrides some of its methods to add this feature.
+ * Its design is simple, relying on snapshot information being queried to cache and invalidate the metadata.
+ * It helps to reduce the time spent in compilation by using HS2 memory more effectively, and it allows to
+ * improve HMS throughput for multi-tenant workloads by reducing the number of calls it needs to serve.
+ */
+public class HiveMetaStoreClientWithLocalCache extends HiveMetaStoreClient {
+
+  private static Cache<CacheKey, Object> mscLocalCache = null;
+  private static boolean IS_CACHE_ENABLED;
+  private static long MAX_SIZE;
+  private static boolean RECORD_STATS;
+  private static HashMap<Class<?>, ObjectEstimator> sizeEstimator = null;
+  private static String cacheObjName = null;
+
+  public static synchronized void init() {
+    if (mscLocalCache != null) return; // init cache only once
+    Configuration metaConf = MetastoreConf.newMetastoreConf();
+    LOG.debug("Initializing local cache in HiveMetaStoreClient...");
+    MAX_SIZE = MetastoreConf.getSizeVar(metaConf, MetastoreConf.ConfVars.MSC_CACHE_MAX_SIZE);
+    IS_CACHE_ENABLED = MetastoreConf.getBoolVar(metaConf, MetastoreConf.ConfVars.MSC_CACHE_ENABLED);
+    RECORD_STATS = MetastoreConf.getBoolVar(metaConf, MetastoreConf.ConfVars.MSC_CACHE_RECORD_STATS);
+    initSizeEstimator();
+    initCache();
+    LOG.debug("Local cache initialized in HiveMetaStoreClient: " + mscLocalCache);
+  }
+
+  public HiveMetaStoreClientWithLocalCache(Configuration conf) throws MetaException {
+    this(conf, null, true);
+  }
+
+  public HiveMetaStoreClientWithLocalCache(Configuration conf, HiveMetaHookLoader hookLoader) throws MetaException {
+    this(conf, hookLoader, true);
+  }
+
+  public HiveMetaStoreClientWithLocalCache(Configuration conf, HiveMetaHookLoader hookLoader, Boolean allowEmbedded) throws MetaException {
+    super(conf, hookLoader, allowEmbedded);
+  }
+
+  private static void initSizeEstimator() {
+    sizeEstimator = new HashMap<>();
+    IncrementalObjectSizeEstimator.createEstimators(CacheKey.class, sizeEstimator);
+    Arrays.stream(KeyType.values()).forEach(e -> {
+      IncrementalObjectSizeEstimator.createEstimators(e.keyClass, sizeEstimator);
+      IncrementalObjectSizeEstimator.createEstimators(e.valueClass, sizeEstimator);}
+    );
+  }
+
+  /**
+   * KeyType is used to differentiate the request types. More types can be added in future.
+   */
+  public enum KeyType {
+    PARTITIONS_BY_EXPR(PartitionsByExprRequest.class, PartitionsByExprResult.class),
+    PARTITIONS_SPEC_BY_EXPR(PartitionsByExprRequest.class, PartitionsSpecByExprResult.class);
+
+    private final Class<?> keyClass;
+    private final Class<?> valueClass;
+
+    KeyType(Class<?> keyClass, Class<?> valueClass) {
+      this.keyClass = keyClass;
+      this.valueClass = valueClass;
+    }
+  }
+
+  /**
+   * CacheKey objects are used as key for the cache.
+   */
+  public static class CacheKey{
+    KeyType IDENTIFIER;
+    Object obj;
+
+    public CacheKey(KeyType IDENTIFIER, Object obj) {
+      this.IDENTIFIER = IDENTIFIER;
+      this.obj = obj;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+      if (this == o) {
+        return true;
+      }
+      if (o == null || getClass() != o.getClass()) {
+        return false;
+      }
+      CacheKey cacheKey = (CacheKey) o;
+      return IDENTIFIER == cacheKey.IDENTIFIER &&
+              Objects.equals(obj, cacheKey.obj);
+    }
+
+    @Override
+    public int hashCode() {
+      return Objects.hash(IDENTIFIER, obj);
+    }
+  }
+
+  private static int getWeight(CacheKey key, Object val) {
+    ObjectEstimator keySizeEstimator = sizeEstimator.get(key.getClass());
+    ObjectEstimator valSizeEstimator = sizeEstimator.get(key.IDENTIFIER.valueClass);
+    int keySize = keySizeEstimator.estimate(key, sizeEstimator);
+    int valSize = valSizeEstimator.estimate(val, sizeEstimator);
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("Cache entry weight - key: {}, value: {}, total: {}", keySize, valSize, keySize + valSize);
+    }
+    return keySize + valSize;
+  }
+
+  private Object load(CacheKey key) {
+    try {
+      return getResultObject(key);
+    } catch (TException e) {
+      throw new UncheckedCacheException(e);
+    }
+  }
+
+/**
+ * Initializes the cache
+ */
+  private static void initCache() {
+    int initSize = 100;
+    Caffeine<CacheKey, Object> cacheBuilder = Caffeine.newBuilder()
+            .initialCapacity(initSize)
+            .maximumWeight(MAX_SIZE)
+            .weigher(HiveMetaStoreClientWithLocalCache::getWeight)
+            .removalListener((key, val, cause) -> {
+              if (LOG.isDebugEnabled()) {
+                LOG.debug("Caffeine - ({}, {}) was removed ({})", key, val, cause);
+              }});
+    if (RECORD_STATS) {
+      cacheBuilder.recordStats();
+    }
+    mscLocalCache = cacheBuilder.build();
+    cacheObjName = mscLocalCache.toString().substring(mscLocalCache.toString().indexOf("Cache@"));
+  }
+
+  /**
+   * This method is used to load the cache by calling relevant APIs, depending on the type of the request.
+   *
+   * @param cacheKey key of the cache, containing an identifier and a request object
+   * @return Result object / null
+   * @throws TException
+   */
+  private Object getResultObject(CacheKey cacheKey) throws TException {
+    Object result = null;
+
+    switch (cacheKey.IDENTIFIER) {
+      case PARTITIONS_BY_EXPR:
+        result = super.getPartitionsByExprResult((PartitionsByExprRequest)cacheKey.obj);
+        break;
+      case PARTITIONS_SPEC_BY_EXPR:
+        result = super.getPartitionsSpecByExprResult((PartitionsByExprRequest)cacheKey.obj);
+        break;
+      default:
+        break;
+    }
+
+    return result;
+  }
+
+  @Override
+  protected PartitionsByExprResult getPartitionsByExprResult(PartitionsByExprRequest req) throws TException {
+    PartitionsByExprResult r;
+
+    // table should be transactional to get responses from the cache
+    if (isCacheEnabledAndInitialized() && isRequestCachable(req, KeyType.PARTITIONS_BY_EXPR)) {
+      CacheKey cacheKey = new CacheKey(KeyType.PARTITIONS_BY_EXPR, req);
+      try {
+        r = (PartitionsByExprResult) mscLocalCache.get(cacheKey, this::load); // get either the result or an Exception
+
+        if (LOG.isDebugEnabled() && RECORD_STATS) {
+          LOG.debug(cacheObjName + ": " + mscLocalCache.stats().toString());
+        }
+
+      } catch (UncheckedCacheException e) {
+        if (e.getCause() instanceof MetaException) {
+          throw (MetaException) e.getCause();
+        } else if (e.getCause() instanceof TException) {
+          throw (TException) e.getCause();
+        } else {
+          throw new TException(e.getCause());
+        }
+      }
+    } else {
+      r = client.get_partitions_by_expr(req);
+    }
+
+    return r;
+  }
+
+  @Override
+  protected PartitionsSpecByExprResult getPartitionsSpecByExprResult(PartitionsByExprRequest req) throws TException {
+    PartitionsSpecByExprResult r;
+
+    // table should be transactional to get responses from the cache
+    if (isCacheEnabledAndInitialized() && isRequestCachable(req, KeyType.PARTITIONS_SPEC_BY_EXPR)) {
+      CacheKey cacheKey = new CacheKey(KeyType.PARTITIONS_SPEC_BY_EXPR, req);
+      try {
+        r = (PartitionsSpecByExprResult) mscLocalCache.get(cacheKey, this::load); // get either the result or an Exception
+
+        if (LOG.isDebugEnabled() && RECORD_STATS) {
+          LOG.debug(cacheObjName + ": " + mscLocalCache.stats().toString());
+        }
+
+      } catch (UncheckedCacheException e) {
+        if (e.getCause() instanceof MetaException) {
+          throw (MetaException) e.getCause();
+        } else if (e.getCause() instanceof TException) {
+          throw (TException) e.getCause();
+        } else {
+          throw new TException(e.getCause());
+        }
+      }
+    } else {
+      r = client.get_partitions_spec_by_expr(req);
+    }
+
+    return r;
+  }
+
+  /**
+   * This method determines if the request should be cached.
+   * @param request Request object
+   * @return boolean
+   */
+  private boolean isRequestCachable(Object request, KeyType keyType) {
+    switch (keyType) {
+      //cache only requests for transactional tables, with a valid table id
+      case PARTITIONS_BY_EXPR:
+      case PARTITIONS_SPEC_BY_EXPR:
+        PartitionsByExprRequest req = (PartitionsByExprRequest) request;
+        return req.getValidWriteIdList() != null && req.getId() != -1;
+        // Requests of other types can have different conditions and should be added here.
+      default:
+        return false;
+    }
+  }
+
+  /**
+   * Checks if cache is enabled and initialized
+   *
+   * @return boolean
+   */
+  private boolean isCacheEnabledAndInitialized() {
+    return IS_CACHE_ENABLED && mscLocalCache != null;
+  }
+}
+
+/**
+ * This unchecked exception is thrown from the load method because checked exception is
+ * not thrown from the functional interface
+ */
+class UncheckedCacheException extends RuntimeException {
+  public UncheckedCacheException(Throwable t) {
+    super(t);
+  }
+}
diff --git a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
index 8ae0903..8e0e664 100644
--- a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
+++ b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/IMetaStoreClient.java
@@ -1378,40 +1378,14 @@ public interface IMetaStoreClient {
 
   /**
    * Get list of {@link PartitionSpec} matching specified serialized expression.
-   * @param dbName the database name
-   * @param tblName the table name
-   * @param expr expression, serialized from ExprNodeDesc
-   * @param maxParts the maximum number of partitions to return,
-   *    all partitions are returned if -1 is passed
-   * @param defaultPartName Default partition name from configuration. If blank, the
-   *    metastore server-side configuration is used.
-   * @param result the resulting list of partitions
+   * @param req PartitionsByExprRequest object
    * @return whether the resulting list contains partitions which may or may not match the expr
    * @throws TException thrift transport error or error executing the filter.
    */
-  boolean listPartitionsSpecByExpr(String dbName, String tblName,
-      byte[] expr, String defaultPartName, short maxParts, List<PartitionSpec> result, String validWriteIdList)
+  boolean listPartitionsSpecByExpr(PartitionsByExprRequest req, List<PartitionSpec> result)
           throws TException;
 
   /**
-   * Get list of {@link PartitionSpec} matching specified serialized expression.
-   * @param catName the catalog name
-   * @param dbName the database name
-   * @param tblName the table name
-   * @param expr expression, serialized from ExprNodeDesc
-   * @param maxParts the maximum number of partitions to return,
-   *    all partitions are returned if -1 is passed
-   * @param defaultPartitionName Default partition name from configuration. If blank, the
-   *    metastore server-side configuration is used.
-   * @param result the resulting list of partitions
-   * @return whether the resulting list contains partitions which may or may not match the expr
-   * @throws TException thrift transport error or error executing the filter.
-   */
-  boolean listPartitionsSpecByExpr(String catName, String dbName, String tblName,
-      byte[] expr, String defaultPartitionName, short maxParts, List<PartitionSpec> result, String validWriteIdList)
-      throws TException;
-
-  /**
    * Get list of partitions matching specified serialized expression
    * @param db_name the database name
    * @param tbl_name the table name
diff --git a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
index 454a4d5..0c43545 100644
--- a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
+++ b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/conf/MetastoreConf.java
@@ -771,6 +771,16 @@ public class MetastoreConf {
                 "get_partitions_spec_by_filter, \n" +
                 "get_partitions_by_expr.\n" +
             "The default value \"-1\" means no limit."),
+    MSC_CACHE_ENABLED("metastore.client.cache.enabled",
+            "hive.metastore.client.cache.enabled", true,
+            "This property enables a Caffeiene Cache for Metastore client"),
+    MSC_CACHE_MAX_SIZE("metastore.client.cache.maxSize",
+            "hive.metastore.client.cache.maxSize", "1Gb", new SizeValidator(),
+            "Set the maximum size (number of bytes) of the metastore client cache (DEFAULT: 1GB). " +
+                    "Only in effect when the cache is enabled"),
+    MSC_CACHE_RECORD_STATS("metastore.client.cache.recordStats",
+            "hive.metastore.client.cache.recordStats", false,
+            "This property enables recording metastore client cache stats in DEBUG logs"),
     LOG4J_FILE("metastore.log4j.file", "hive.log4j.file", "",
         "Hive log4j configuration file.\n" +
             "If the property is not set, then logging will be initialized using metastore-log4j2.properties found on the classpath.\n" +
diff --git a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
index f9a771c..3416e5b 100644
--- a/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
+++ b/standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/MetaStoreUtils.java
@@ -53,6 +53,8 @@ import org.apache.hadoop.hive.metastore.Warehouse;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.PartitionSpec;
+import org.apache.hadoop.hive.metastore.api.PartitionsSpecByExprResult;
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.Table;
 import org.apache.hadoop.hive.metastore.api.WMPoolSchedulingPolicy;
@@ -1012,4 +1014,12 @@ public class MetaStoreUtils {
     }
     return orderSpecs;
   }
+
+  public static void addPartitonSpecsToList(PartitionsSpecByExprResult r, List<PartitionSpec> result) {
+    result.addAll(r.getPartitionsSpec());
+  }
+
+  public static boolean hasUnknownPartitions(PartitionsSpecByExprResult r) {
+    return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions();
+  }
 }
diff --git a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metrics/PerfLogger.java b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metrics/PerfLogger.java
index 536e0c5..5465187 100644
--- a/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metrics/PerfLogger.java
+++ b/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/metrics/PerfLogger.java
@@ -38,6 +38,23 @@ public class PerfLogger {
   static final private Logger LOG = LoggerFactory.getLogger(PerfLogger.class.getName());
   protected static final ThreadLocal<PerfLogger> perfLogger = new ThreadLocal<>();
 
+  public static final String GET_AGGR_COL_STATS = "getAggrColStatsFor";
+  public static final String GET_AGGR_COL_STATS_2 = "getAggrColStatsFor_2";
+  public static final String LIST_PARTS_WITH_AUTH_INFO = "listPartitionsWithAuthInfo";
+  public static final String LIST_PARTS_WITH_AUTH_INFO_2 = "listPartitionsWithAuthInfo_2";
+  public static final String LIST_PARTS_BY_EXPR = "listPartitionsByExpr";
+  public static final String LIST_PARTS_SPECS_BY_EXPR = "listPartitionsSpecByExpr";
+  public static final String GET_DATABASE = "getDatabase";
+  public static final String GET_TABLE = "getTable";
+  public static final String GET_TABLE_2 = "getTable_2";
+  public static final String GET_PK = "getPrimaryKeys";
+  public static final String GET_FK = "getForeignKeys";
+  public static final String GET_UNIQ_CONSTRAINTS = "getUniqueConstraints";
+  public static final String GET_NOT_NULL_CONSTRAINTS = "getNotNullConstraints";
+  public static final String GET_TABLE_COL_STATS = "getTableColumnStatistics";
+  public static final String GET_TABLE_COL_STATS_2 = "getTableColumnStatistics_2";
+  public static final String GET_CONFIG_VAL = "getConfigValue";
+
 
   private PerfLogger() {
     // Use getPerfLogger to get an instance of PerfLogger
diff --git a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientPreCatalog.java b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientPreCatalog.java
index 24c73ea..de41fd2 100644
--- a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientPreCatalog.java
+++ b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/HiveMetaStoreClientPreCatalog.java
@@ -1375,27 +1375,11 @@ public class HiveMetaStoreClientPreCatalog implements IMetaStoreClient, AutoClos
     return !r.isSetHasUnknownPartitions() || r.isHasUnknownPartitions(); // Assume the worst.
   }
 
-  @Override
-  public boolean listPartitionsSpecByExpr(String dbName, String tblName,
-      byte[] expr, String defaultPartName, short maxParts, List<PartitionSpec> result, String validWriteIdList)
-      throws TException {
-    return listPartitionsSpecByExpr(getDefaultCatalog(conf), dbName, tblName, expr, defaultPartName,
-        maxParts, result, validWriteIdList);
-  }
 
   @Override
-  public boolean listPartitionsSpecByExpr(String catName, String dbName, String tblName, byte[] expr,
-      String defaultPartitionName, short maxParts, List<PartitionSpec> result, String validWriteIdList)
+  public boolean listPartitionsSpecByExpr(PartitionsByExprRequest req, List<PartitionSpec> result)
       throws TException {
     assert result != null;
-    PartitionsByExprRequest req = new PartitionsByExprRequest(dbName, tblName, ByteBuffer.wrap(expr));
-    if (defaultPartitionName != null) {
-      req.setDefaultPartitionName(defaultPartitionName);
-    }
-    if (maxParts >= 0) {
-      req.setMaxParts(maxParts);
-    }
-    req.setValidWriteIdList(validWriteIdList);
     PartitionsSpecByExprResult r;
     try {
       r = client.get_partitions_spec_by_expr(req);
diff --git a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/client/TestListPartitions.java b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/client/TestListPartitions.java
index b300314..dfe4066 100644
--- a/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/client/TestListPartitions.java
+++ b/standalone-metastore/metastore-server/src/test/java/org/apache/hadoop/hive/metastore/client/TestListPartitions.java
@@ -70,6 +70,16 @@ public class TestListPartitions extends MetaStoreClientTest {
   protected static final String USER_NAME = "user0";
   protected static final String GROUP = "group0";
 
+  public static class ReturnTable {
+    public Table table;
+    public List<List<String>> testValues;
+
+    public ReturnTable(Table table, List<List<String>> testValues) {
+      this.table = table;
+      this.testValues = testValues;
+    }
+  }
+
   public TestListPartitions(String name, AbstractMetaStoreService metaStore) {
     this.metaStore = metaStore;
   }
@@ -156,18 +166,20 @@ public class TestListPartitions extends MetaStoreClientTest {
     client.add_partition(partitionBuilder.build(metaStore.getConf()));
   }
 
-  private void createTable3PartCols1PartGeneric(IMetaStoreClient client, boolean authOn)
+  private Table createTable3PartCols1PartGeneric(IMetaStoreClient client, boolean authOn)
           throws TException {
     Table t = createTestTable(client, DB_NAME, TABLE_NAME, Lists.newArrayList("yyyy", "mm",
             "dd"), authOn);
     addPartition(client, t, Lists.newArrayList("1997", "05", "16"));
+
+    return t;
   }
 
-  protected void createTable3PartCols1Part(IMetaStoreClient client) throws TException {
-    createTable3PartCols1PartGeneric(client, false);
+  protected Table createTable3PartCols1Part(IMetaStoreClient client) throws TException {
+    return createTable3PartCols1PartGeneric(client, false);
   }
 
-  private List<List<String>> createTable4PartColsPartsGeneric(IMetaStoreClient client,
+  private ReturnTable createTable4PartColsPartsGeneric(IMetaStoreClient client,
                                                                      boolean authOn) throws
           Exception {
     Table t = createTestTable(client, DB_NAME, TABLE_NAME, Lists.newArrayList("yyyy", "mm", "dd"),
@@ -182,15 +194,15 @@ public class TestListPartitions extends MetaStoreClientTest {
       addPartition(client, t, vals);
     }
 
-    return testValues;
+    return new ReturnTable(t, testValues);
   }
 
-  protected List<List<String>> createTable4PartColsParts(IMetaStoreClient client) throws
+  protected ReturnTable createTable4PartColsParts(IMetaStoreClient client) throws
           Exception {
     return createTable4PartColsPartsGeneric(client, false);
   }
 
-  protected List<List<String>> createTable4PartColsPartsAuthOn(IMetaStoreClient client) throws
+  protected ReturnTable createTable4PartColsPartsAuthOn(IMetaStoreClient client) throws
           Exception {
     return createTable4PartColsPartsGeneric(client, true);
   }
@@ -261,7 +273,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionsAll() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     List<Partition> partitions = client.listPartitions(DB_NAME, TABLE_NAME, (short)-1);
     assertPartitionsHaveCorrectValues(partitions, testValues);
 
@@ -279,7 +291,7 @@ public class TestListPartitions extends MetaStoreClientTest {
   @Test
   @ConditionalIgnoreOnSessionHiveMetastoreClient
   public void testGetPartitionsRequest() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     PartitionsRequest req = new PartitionsRequest();
     req.setCatName(MetaStoreUtils.getDefaultCatalog(metaStore.getConf()));
     req.setDbName(DB_NAME);
@@ -365,7 +377,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionsByValues() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
 
     List<Partition> partitions = client.listPartitions(DB_NAME, TABLE_NAME,
             Lists.newArrayList("2017"), (short)-1);
@@ -444,7 +456,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionSpecs() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
 
     PartitionSpecProxy partSpecProxy = client.listPartitionSpecs(DB_NAME, TABLE_NAME, -1);
     assertPartitionsSpecProxy(partSpecProxy, testValues);
@@ -516,7 +528,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionsWithAuth() throws Exception {
-    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client);
+    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client).testValues;
     List<String> groups = Lists.newArrayList(GROUP);
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, (short)-1,
             USER_NAME, groups);
@@ -553,7 +565,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionsWithAuthNoPrivilegesSet() throws Exception {
-    List<List<String>> partValues = createTable4PartColsParts(client);
+    List<List<String>> partValues = createTable4PartColsParts(client).testValues;
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, (short)-1,
             "", Lists.newArrayList());
 
@@ -624,7 +636,7 @@ public class TestListPartitions extends MetaStoreClientTest {
   @Test
   @ConditionalIgnoreOnSessionHiveMetastoreClient
   public void testListPartitionsWithAuthRequestByValues() throws Exception {
-    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client);
+    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client).testValues;
     List<String> groups = Lists.newArrayList(GROUP);
 
     GetPartitionsPsWithAuthRequest req = new GetPartitionsPsWithAuthRequest();
@@ -671,7 +683,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionsWithAuthByValues() throws Exception {
-    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client);
+    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client).testValues;
     List<String> groups = Lists.newArrayList(GROUP);
 
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, Lists
@@ -714,7 +726,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionsWithAuthByValuesHighMaxParts() throws Exception {
-    List<List<String>> partValues = createTable4PartColsParts(client);
+    List<List<String>> partValues = createTable4PartColsParts(client).testValues;
     //This doesn't throw MetaException when setting to high max part count
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, Lists
             .newArrayList("2017"), (short)101, "", Lists.newArrayList());
@@ -730,7 +742,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionsWithAuthByValuesNoPrivilegesSet() throws Exception {
-    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client);
+    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client).testValues;
     String user = "user0";
     List<String> groups = Lists.newArrayList("group0");
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, Lists
@@ -801,7 +813,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionsWithAuthByValuesNullUser() throws Exception {
-    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client);
+    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client).testValues;
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, Lists
             .newArrayList("2017", "11", "27"), (short)-1, null, Lists.newArrayList());
     assertPartitionsHaveCorrectValues(partitions, partValues.subList(3, 4));
@@ -809,7 +821,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionsWithAuthByValuesNullGroup() throws Exception {
-    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client);
+    List<List<String>> partValues = createTable4PartColsPartsAuthOn(client).testValues;
     List<Partition> partitions = client.listPartitionsWithAuthInfo(DB_NAME, TABLE_NAME, Lists
             .newArrayList("2017", "11", "27"), (short)-1, "", null);
     assertPartitionsHaveCorrectValues(partitions, partValues.subList(3, 4));
@@ -824,7 +836,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionsByFilter() throws Exception {
-    List<List<String>> partValues = createTable4PartColsParts(client);
+    List<List<String>> partValues = createTable4PartColsParts(client).testValues;
     List<Partition> partitions = client.listPartitionsByFilter(DB_NAME, TABLE_NAME,
             "yyyy=\"2017\" OR " + "mm=\"02\"", (short)-1);
     assertEquals(3, partitions.size());
@@ -1002,7 +1014,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionsSpecsByFilter() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     PartitionSpecProxy partSpecProxy = client.listPartitionSpecsByFilter(DB_NAME, TABLE_NAME,
             "yyyy=\"2017\" OR " + "mm=\"02\"", -1);
 
@@ -1082,14 +1094,14 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionSpecsByFilterNullFilter() throws Exception {
-    List<List<String>> values = createTable4PartColsParts(client);
+    List<List<String>> values = createTable4PartColsParts(client).testValues;
     PartitionSpecProxy pproxy = client.listPartitionSpecsByFilter(DB_NAME, TABLE_NAME, null, -1);
     assertPartitionsSpecProxy(pproxy, values);
   }
 
   @Test
   public void testListPartitionSpecsByFilterEmptyFilter() throws Exception {
-    List<List<String>> values = createTable4PartColsParts(client);
+    List<List<String>> values = createTable4PartColsParts(client).testValues;
     PartitionSpecProxy pproxy = client.listPartitionSpecsByFilter(DB_NAME, TABLE_NAME, "", -1);
     assertPartitionsSpecProxy(pproxy, values);
   }
@@ -1180,7 +1192,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionNames() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     List<String> partitionNames = client.listPartitionNames(DB_NAME, TABLE_NAME, (short)-1);
     assertCorrectPartitionNames(partitionNames, testValues, Lists.newArrayList("yyyy", "mm",
             "dd"));
@@ -1253,7 +1265,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionNamesByValues() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     List<String> partitionNames = client.listPartitionNames(DB_NAME, TABLE_NAME,
             Lists.newArrayList("2017"), (short)-1);
     assertCorrectPartitionNames(partitionNames, testValues.subList(2, 4),
@@ -1287,7 +1299,7 @@ public class TestListPartitions extends MetaStoreClientTest {
   @Test
   @ConditionalIgnoreOnSessionHiveMetastoreClient
   public void testListPartitionNamesRequestByValues() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     GetPartitionNamesPsRequest req = new GetPartitionNamesPsRequest();
     req.setCatName(MetaStoreUtils.getDefaultCatalog(metaStore.getConf()));
     req.setDbName(DB_NAME);
@@ -1327,7 +1339,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionNamesByValuesMaxPartCountUnlimited() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     //TODO: due to value 101 this probably should throw an exception
     List<String> partitionNames = client.listPartitionNames(DB_NAME, TABLE_NAME,
             Lists.newArrayList("2017"), (short) 101);
@@ -1337,7 +1349,7 @@ public class TestListPartitions extends MetaStoreClientTest {
 
   @Test
   public void testListPartitionNamesByValuesLowPartCount() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     List<String> partitionNames = client.listPartitionNames(DB_NAME, TABLE_NAME,
         Lists.newArrayList("2017"), (short) 1);
     assertTrue(partitionNames.size() == 1);
@@ -1422,7 +1434,7 @@ public class TestListPartitions extends MetaStoreClientTest {
    */
   @Test
   public void testListPartitionValues() throws Exception {
-    List<List<String>> testValues = createTable4PartColsParts(client);
+    List<List<String>> testValues = createTable4PartColsParts(client).testValues;
     List<FieldSchema> partitionSchema = Lists.newArrayList(
             new FieldSchema("yyyy", "string", ""),
             new FieldSchema("mm", "string", ""));
@@ -1437,7 +1449,7 @@ public class TestListPartitions extends MetaStoreClientTest {
   @Test
   public void testListPartitionValuesEmptySchema() throws Exception {
     try {
-      List<List<String>> testValues = createTable4PartColsParts(client);
+      List<List<String>> testValues = createTable4PartColsParts(client).testValues;
       List<FieldSchema> partitionSchema = Lists.newArrayList();
 
       PartitionValuesRequest request = new PartitionValuesRequest(DB_NAME, TABLE_NAME,
diff --git a/standalone-metastore/pom.xml b/standalone-metastore/pom.xml
index edcb8d2..819a0b2 100644
--- a/standalone-metastore/pom.xml
+++ b/standalone-metastore/pom.xml
@@ -105,6 +105,7 @@
     <zookeeper.version>3.5.5</zookeeper.version>
     <cron-utils.version>8.1.1</cron-utils.version>
     <spotbugs.version>4.0.3</spotbugs.version>
+    <caffeine.version>2.8.4</caffeine.version>
 
     <!-- Thrift properties -->
     <thrift.home>you-must-set-this-to-run-thrift</thrift.home>
@@ -311,6 +312,11 @@
         <artifactId>cron-utils</artifactId>
         <version>${cron-utils.version}</version>
       </dependency>
+      <dependency>
+        <groupId>com.github.ben-manes.caffeine</groupId>
+        <artifactId>caffeine</artifactId>
+        <version>${caffeine.version}</version>
+      </dependency>
 
       <!-- test scope dependencies -->
 
diff --git a/standalone-metastore/spotbugs/spotbugs-exclude.xml b/standalone-metastore/spotbugs/spotbugs-exclude.xml
index da4b99b..b716039 100644
--- a/standalone-metastore/spotbugs/spotbugs-exclude.xml
+++ b/standalone-metastore/spotbugs/spotbugs-exclude.xml
@@ -27,4 +27,7 @@
             <Class name="~org.apache.hadoop.hive.metastore.Metastore.*" />
         </Or>
     </Match>
+    <Match>
+        <Class name="~org.apache.hadoop.hive.metastore.metrics.*" />
+    </Match>
 </FindBugsFilter>