You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by yi...@apache.org on 2022/08/03 03:16:09 UTC

[doris] branch dev-1.1.2 updated: [improvement](memtracker)add new mem tracker (#11449)

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

yiguolei pushed a commit to branch dev-1.1.2
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/dev-1.1.2 by this push:
     new f74624df31 [improvement](memtracker)add new mem tracker (#11449)
f74624df31 is described below

commit f74624df3114054d425d6e78d719cc3be09cd5df
Author: Xinyi Zou <zo...@gmail.com>
AuthorDate: Wed Aug 3 11:16:04 2022 +0800

    [improvement](memtracker)add new mem tracker (#11449)
---
 be/CMakeLists.txt                                  |   8 +
 be/src/common/config.h                             |  32 ++-
 be/src/common/daemon.cpp                           |   2 -
 be/src/common/status.h                             |   2 +-
 be/src/common/utils.h                              |   4 +-
 be/src/exec/blocking_join_node.cpp                 |   1 +
 be/src/exec/broker_scan_node.cpp                   |   2 +
 be/src/exec/cross_join_node.cpp                    |   4 +-
 be/src/exec/es_http_scan_node.cpp                  |   1 +
 be/src/exec/except_node.cpp                        |   2 +-
 be/src/exec/hash_join_node.cpp                     |   6 +-
 be/src/exec/intersect_node.cpp                     |   2 +-
 be/src/exec/olap_scan_node.cpp                     |   2 +
 be/src/exec/set_operation_node.cpp                 |   2 +-
 be/src/exec/tablet_sink.cpp                        |  16 +-
 be/src/exec/tablet_sink.h                          |   6 +-
 be/src/gutil/strings/numbers.cc                    |  43 +++
 be/src/gutil/strings/numbers.h                     |   4 +
 be/src/http/default_path_handlers.cpp              |  54 +++-
 be/src/olap/base_compaction.cpp                    |   3 +
 be/src/olap/byte_buffer.cpp                        |   9 +
 be/src/olap/cumulative_compaction.cpp              |   3 +
 be/src/olap/generic_iterators.cpp                  |   3 +-
 be/src/olap/lru_cache.cpp                          |   9 +-
 be/src/olap/lru_cache.h                            |   5 +
 be/src/olap/out_stream.cpp                         |   2 +-
 be/src/olap/out_stream.h                           |   1 -
 be/src/olap/rowset/column_writer.cpp               |   3 +-
 be/src/olap/rowset/column_writer.h                 |   1 -
 be/src/olap/rowset/segment_v2/bitshuffle_page.h    |   2 +-
 be/src/olap/storage_engine.cpp                     |   4 +-
 be/src/olap/storage_engine.h                       |   3 +
 be/src/runtime/CMakeLists.txt                      |   4 +
 be/src/runtime/bufferpool/system_allocator.cc      |   6 +
 be/src/runtime/data_stream_recvr.cc                |   6 +
 be/src/runtime/exec_env.h                          |  17 ++
 be/src/runtime/exec_env_init.cpp                   |  53 +++-
 be/src/runtime/fragment_mgr.cpp                    |   7 +
 be/src/runtime/load_channel_mgr.cpp                |   2 +-
 be/src/runtime/memory/chunk_allocator.cpp          |   8 +
 be/src/runtime/memory/chunk_allocator.h            |   3 +
 be/src/runtime/memory/mem_tracker.cpp              | 122 +++++++++
 be/src/runtime/memory/mem_tracker.h                | 116 +++++++++
 be/src/runtime/memory/mem_tracker_limiter.cpp      | 264 +++++++++++++++++++
 be/src/runtime/memory/mem_tracker_limiter.h        | 287 +++++++++++++++++++++
 be/src/runtime/memory/mem_tracker_task_pool.cpp    | 145 +++++++++++
 be/src/runtime/memory/mem_tracker_task_pool.h      |  61 +++++
 be/src/runtime/memory/system_allocator.cpp         |   5 +
 be/src/runtime/memory/tcmalloc_hook.h              |  72 ++++++
 be/src/runtime/memory/thread_mem_tracker_mgr.cpp   |  69 +++++
 be/src/runtime/memory/thread_mem_tracker_mgr.h     | 234 +++++++++++++++++
 be/src/runtime/plan_fragment_executor.cpp          |   7 +
 be/src/runtime/result_sink.cpp                     |   3 +
 be/src/runtime/runtime_state.cpp                   |  68 +++--
 be/src/runtime/runtime_state.h                     |  25 +-
 be/src/runtime/sorted_run_merger.cc                |   6 +-
 be/src/runtime/tablets_channel.cpp                 |   3 +-
 be/src/runtime/thread_context.cpp                  |  97 ++++++-
 be/src/runtime/thread_context.h                    | 263 ++++++++++++++-----
 be/src/runtime/threadlocal.cc                      |   1 -
 be/src/runtime/threadlocal.h                       |   2 +-
 .../thread_context.cpp => service/brpc_conflict.h} |  36 ++-
 be/src/service/doris_main.cpp                      |  12 +-
 be/src/service/internal_service.cpp                |  57 +++-
 be/src/util/file_utils.cpp                         |   3 +
 be/src/vec/common/allocator.h                      |  17 +-
 be/src/vec/exec/join/vhash_join_node.cpp           |   4 +-
 be/src/vec/exec/vaggregation_node.cpp              |   4 +-
 be/src/vec/exec/vblocking_join_node.cpp            |   1 +
 be/src/vec/exec/vcross_join_node.cpp               |   3 +-
 be/src/vec/exec/volap_scan_node.cpp                |   2 +
 be/src/vec/exec/vset_operation_node.cpp            |   4 +-
 be/src/vec/runtime/vdata_stream_recvr.cpp          |   6 +
 be/src/vec/sink/result_sink.cpp                    |   3 +
 build.sh                                           |   6 +-
 gensrc/proto/types.proto                           |   1 +
 run-be-ut.sh                                       |   1 +
 77 files changed, 2151 insertions(+), 206 deletions(-)

diff --git a/be/CMakeLists.txt b/be/CMakeLists.txt
index 6118cae793..782effadc2 100644
--- a/be/CMakeLists.txt
+++ b/be/CMakeLists.txt
@@ -415,6 +415,14 @@ if (WITH_LZO)
     set(CXX_COMMON_FLAGS "${CXX_COMMON_FLAGS} -DDORIS_WITH_LZO")
 endif()
 
+# Enable memory tracker, which allows BE to limit the memory of tasks such as query, load,
+# and compaction,and observe the memory of BE through be_ip:http_port/MemTracker.
+# Adding the option `USE_MEM_TRACKER=OFF sh build.sh` when compiling can turn off the memory tracker,
+# which will bring about a 2% performance improvement, which may be useful in performance POC.
+if (USE_MEM_TRACKER)
+    set(CXX_COMMON_FLAGS "${CXX_COMMON_FLAGS} -DUSE_MEM_TRACKER")
+endif()
+
 # STRICT_MEMORY_USE=ON` expects BE to use less memory, and gives priority to ensuring stability
 # when the cluster memory is limited.
 # TODO In the future, expect a dynamic soft memory limit, combined with real-time memory usage of the cluster,
diff --git a/be/src/common/config.h b/be/src/common/config.h
index 2f956e3b8d..9533beff65 100644
--- a/be/src/common/config.h
+++ b/be/src/common/config.h
@@ -412,10 +412,14 @@ CONF_Bool(disable_mem_pools, "false");
 // to a relative large number or the performance is very very bad.
 CONF_Bool(use_mmap_allocate_chunk, "false");
 
-// Chunk Allocator's reserved bytes limit,
-// Default value is 2GB, increase this variable can improve performance, but will
-// acquire more free memory which can not be used by other modules
-CONF_Int64(chunk_reserved_bytes_limit, "2147483648");
+// The reserved bytes limit of Chunk Allocator, usually set as a percentage of mem_limit.
+// defaults to bytes if no unit is given, the number of bytes must be a multiple of 2.
+// must larger than 0. and if larger than physical memory size, it will be set to physical memory size.
+// increase this variable can improve performance,
+// but will acquire more free memory which can not be used by other modules.
+CONF_mString(chunk_reserved_bytes_limit, "20%");
+// 1024, The minimum chunk allocator size (in bytes)
+CONF_Int32(min_chunk_reserved_bytes, "1024");
 
 // The probing algorithm of partitioned hash table.
 // Enable quadratic probing hash table
@@ -621,6 +625,26 @@ CONF_mInt32(remote_storage_read_buffer_mb, "16");
 // the level equal or lower than mem_tracker_level will show in web page
 CONF_Int16(mem_tracker_level, "0");
 
+// Whether Hook TCmalloc new/delete, currently consume/release tls mem tracker in Hook.
+CONF_Bool(enable_tcmalloc_hook, "true");
+
+// If true, switch TLS MemTracker to count more detailed memory,
+// including caches such as ExecNode operators and TabletManager.
+//
+// At present, there is a performance problem in the frequent switch thread mem tracker.
+// This is because the mem tracker exists as a shared_ptr in the thread local. Each time it is switched,
+// the atomic variable use_count in the shared_ptr of the current tracker will be -1, and the tracker to be
+// replaced use_count +1, multi-threading Frequent changes to the same tracker shared_ptr are slow.
+// TODO: 1. Reduce unnecessary thread mem tracker switches,
+//       2. Consider using raw pointers for mem tracker in thread local
+CONF_Bool(memory_verbose_track, "false");
+
+// The minimum length when TCMalloc Hook consumes/releases MemTracker, consume size
+// smaller than this value will continue to accumulate. specified as number of bytes.
+// Decreasing this value will increase the frequency of consume/release.
+// Increasing this value will cause MemTracker statistics to be inaccurate.
+CONF_mInt32(mem_tracker_consume_min_size_bytes, "1048576");
+
 // The version information of the tablet will be stored in the memory
 // in an adjacency graph data structure.
 // And as the new version is written and the old version is deleted,
diff --git a/be/src/common/daemon.cpp b/be/src/common/daemon.cpp
index 07b5439e4c..ea628bb100 100644
--- a/be/src/common/daemon.cpp
+++ b/be/src/common/daemon.cpp
@@ -275,8 +275,6 @@ void Daemon::init(int argc, char** argv, const std::vector<StorePath>& paths) {
 
     init_doris_metrics(paths);
     init_signals();
-
-    ChunkAllocator::init_instance(config::chunk_reserved_bytes_limit);
 }
 
 void Daemon::start() {
diff --git a/be/src/common/status.h b/be/src/common/status.h
index c94c660ff1..e14685dead 100644
--- a/be/src/common/status.h
+++ b/be/src/common/status.h
@@ -17,7 +17,7 @@ namespace doris {
 
 class Status {
     enum { 
-        STATE_CAPACITY = 256,
+        STATE_CAPACITY = 2048,
         HEADER_LEN = 7,
         MESSAGE_LEN = STATE_CAPACITY - HEADER_LEN
     };
diff --git a/be/src/common/utils.h b/be/src/common/utils.h
index c0ca459423..18d5f0a547 100644
--- a/be/src/common/utils.h
+++ b/be/src/common/utils.h
@@ -21,7 +21,9 @@
 
 namespace doris {
 
-#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
+#ifndef ARRAY_SIZE
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+#endif
 
 struct AuthInfo {
     std::string user;
diff --git a/be/src/exec/blocking_join_node.cpp b/be/src/exec/blocking_join_node.cpp
index ba137860ac..382d626fb2 100644
--- a/be/src/exec/blocking_join_node.cpp
+++ b/be/src/exec/blocking_join_node.cpp
@@ -82,6 +82,7 @@ Status BlockingJoinNode::close(RuntimeState* state) {
 }
 
 void BlockingJoinNode::build_side_thread(RuntimeState* state, std::promise<Status>* status) {
+    SCOPED_ATTACH_TASK(state);
     status->set_value(construct_build_side(state));
 }
 
diff --git a/be/src/exec/broker_scan_node.cpp b/be/src/exec/broker_scan_node.cpp
index 0ecd7ba875..cb91e15d02 100644
--- a/be/src/exec/broker_scan_node.cpp
+++ b/be/src/exec/broker_scan_node.cpp
@@ -27,6 +27,7 @@
 #include "exec/parquet_scanner.h"
 #include "exprs/expr.h"
 #include "exprs/expr_context.h"
+#include "runtime/thread_context.h"
 #include "runtime/dpp_sink_internal.h"
 #include "runtime/row_batch.h"
 #include "runtime/runtime_state.h"
@@ -347,6 +348,7 @@ Status BrokerScanNode::scanner_scan(const TBrokerScanRange& scan_range,
 }
 
 void BrokerScanNode::scanner_worker(int start_idx, int length) {
+    SCOPED_ATTACH_TASK(_runtime_state);
     // Clone expr context
     std::vector<ExprContext*> scanner_expr_ctxs;
     auto status = Expr::clone_if_not_exists(_conjunct_ctxs, _runtime_state, &scanner_expr_ctxs);
diff --git a/be/src/exec/cross_join_node.cpp b/be/src/exec/cross_join_node.cpp
index 8ef9b662f8..b26f4f2cd4 100644
--- a/be/src/exec/cross_join_node.cpp
+++ b/be/src/exec/cross_join_node.cpp
@@ -52,6 +52,7 @@ Status CrossJoinNode::close(RuntimeState* state) {
 Status CrossJoinNode::construct_build_side(RuntimeState* state) {
     // Do a full scan of child(1) and store all build row batches.
     RETURN_IF_ERROR(child(1)->open(state));
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Cross join, while getting next from child 1");
 
     while (true) {
         RowBatch* batch = _build_batch_pool->add(
@@ -63,9 +64,6 @@ Status CrossJoinNode::construct_build_side(RuntimeState* state) {
         bool eos = false;
         RETURN_IF_ERROR(child(1)->get_next(state, batch, &eos));
 
-        // to prevent use too many memory
-        RETURN_IF_LIMIT_EXCEEDED(state, "Cross join, while getting next from the child 1.");
-
         SCOPED_TIMER(_build_timer);
         _build_batches.add_row_batch(batch);
         VLOG_ROW << build_list_debug_string();
diff --git a/be/src/exec/es_http_scan_node.cpp b/be/src/exec/es_http_scan_node.cpp
index 7e88dba043..a5d7ab9eee 100644
--- a/be/src/exec/es_http_scan_node.cpp
+++ b/be/src/exec/es_http_scan_node.cpp
@@ -422,6 +422,7 @@ static std::string get_host_port(const std::vector<TNetworkAddress>& es_hosts) {
 }
 
 void EsHttpScanNode::scanner_worker(int start_idx, int length, std::promise<Status>& p_status) {
+    SCOPED_ATTACH_TASK(_runtime_state);
     // Clone expr context
     std::vector<ExprContext*> scanner_expr_ctxs;
     DCHECK(start_idx < length);
diff --git a/be/src/exec/except_node.cpp b/be/src/exec/except_node.cpp
index d79aceb9c8..58a9b67f2f 100644
--- a/be/src/exec/except_node.cpp
+++ b/be/src/exec/except_node.cpp
@@ -40,6 +40,7 @@ Status ExceptNode::init(const TPlanNode& tnode, RuntimeState* state) {
 
 Status ExceptNode::open(RuntimeState* state) {
     RETURN_IF_ERROR(SetOperationNode::open(state));
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Except Node, while probing the hash table.");
     // if a table is empty, the result must be empty
     if (_hash_tbl->size() == 0) {
         _hash_tbl_iterator = _hash_tbl->begin();
@@ -63,7 +64,6 @@ Status ExceptNode::open(RuntimeState* state) {
         while (!eos) {
             RETURN_IF_CANCELLED(state);
             RETURN_IF_ERROR(child(i)->get_next(state, _probe_batch.get(), &eos));
-            RETURN_IF_LIMIT_EXCEEDED(state, " Except , while probing the hash table.");
             for (int j = 0; j < _probe_batch->num_rows(); ++j) {
                 _hash_tbl_iterator = _hash_tbl->find(_probe_batch->get_row(j));
                 if (_hash_tbl_iterator != _hash_tbl->end()) {
diff --git a/be/src/exec/hash_join_node.cpp b/be/src/exec/hash_join_node.cpp
index 291edbc4c3..7c572ff95d 100644
--- a/be/src/exec/hash_join_node.cpp
+++ b/be/src/exec/hash_join_node.cpp
@@ -177,6 +177,7 @@ Status HashJoinNode::close(RuntimeState* state) {
 }
 
 void HashJoinNode::build_side_thread(RuntimeState* state, std::promise<Status>* status) {
+    SCOPED_ATTACH_TASK(state);
     status->set_value(construct_hash_table(state));
 }
 
@@ -185,6 +186,7 @@ Status HashJoinNode::construct_hash_table(RuntimeState* state) {
     // The hash join node needs to keep in memory all build tuples, including the tuple
     // row ptrs.  The row ptrs are copied into the hash table's internal structure so they
     // don't need to be stored in the _build_pool.
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Hash join, while constructing the hash table.");
     RowBatch build_batch(child(1)->row_desc(), state->batch_size(), mem_tracker().get());
     RETURN_IF_ERROR(child(1)->open(state));
 
@@ -302,7 +304,7 @@ Status HashJoinNode::get_next(RuntimeState* state, RowBatch* out_batch, bool* eo
     // In most cases, no additional memory overhead will be applied for at this stage,
     // but if the expression calculation in this node needs to apply for additional memory,
     // it may cause the memory to exceed the limit.
-    RETURN_IF_LIMIT_EXCEEDED(state, "Hash join, while execute get_next.");
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Hash join, while execute get_next.");
     SCOPED_TIMER(_runtime_profile->total_time_counter());
 
     if (reached_limit()) {
@@ -770,11 +772,9 @@ Status HashJoinNode::process_build_batch(RuntimeState* state, RowBatch* build_ba
                                                    _build_pool.get(), false);
             }
         }
-        RETURN_IF_LIMIT_EXCEEDED(state, "Hash join, while constructing the hash table.");
     } else {
         // take ownership of tuple data of build_batch
         _build_pool->acquire_data(build_batch->tuple_data_pool(), false);
-        RETURN_IF_LIMIT_EXCEEDED(state, "Hash join, while constructing the hash table.");
         RETURN_IF_ERROR(_hash_tbl->resize_buckets_ahead(build_batch->num_rows()));
         for (int i = 0; i < build_batch->num_rows(); ++i) {
             _hash_tbl->insert_without_check(build_batch->get_row(i));
diff --git a/be/src/exec/intersect_node.cpp b/be/src/exec/intersect_node.cpp
index 2cbf4db135..9f5eb3ece1 100644
--- a/be/src/exec/intersect_node.cpp
+++ b/be/src/exec/intersect_node.cpp
@@ -43,6 +43,7 @@ Status IntersectNode::init(const TPlanNode& tnode, RuntimeState* state) {
 // 2 probe with child(1), then filter the hash table and find the matched item, use them to rebuild a hash table
 // repeat [2] this for all the rest child
 Status IntersectNode::open(RuntimeState* state) {
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Intersect Node, while probing the hash table.");
     RETURN_IF_ERROR(SetOperationNode::open(state));
     // if a table is empty, the result must be empty
     if (_hash_tbl->size() == 0) {
@@ -66,7 +67,6 @@ Status IntersectNode::open(RuntimeState* state) {
         while (!eos) {
             RETURN_IF_CANCELLED(state);
             RETURN_IF_ERROR(child(i)->get_next(state, _probe_batch.get(), &eos));
-            RETURN_IF_LIMIT_EXCEEDED(state, " Intersect , while probing the hash table.");
             for (int j = 0; j < _probe_batch->num_rows(); ++j) {
                 _hash_tbl_iterator = _hash_tbl->find(_probe_batch->get_row(j));
                 if (_hash_tbl_iterator != _hash_tbl->end()) {
diff --git a/be/src/exec/olap_scan_node.cpp b/be/src/exec/olap_scan_node.cpp
index de8fa57726..b3e63ee8cd 100644
--- a/be/src/exec/olap_scan_node.cpp
+++ b/be/src/exec/olap_scan_node.cpp
@@ -1348,6 +1348,7 @@ Status OlapScanNode::normalize_bloom_filter_predicate(SlotDescriptor* slot) {
 
 void OlapScanNode::transfer_thread(RuntimeState* state) {
     // scanner open pushdown to scanThread
+    SCOPED_ATTACH_TASK(state);
     Status status = Status::OK();
     for (auto scanner : _olap_scanners) {
         status = Expr::clone_if_not_exists(_conjunct_ctxs, state, scanner->conjunct_ctxs());
@@ -1522,6 +1523,7 @@ void OlapScanNode::transfer_thread(RuntimeState* state) {
 }
 
 void OlapScanNode::scanner_thread(OlapScanner* scanner) {
+    SCOPED_ATTACH_TASK(_runtime_state);
     if (UNLIKELY(_transfer_done)) {
         _scanner_done = true;
         std::unique_lock<std::mutex> l(_scan_batches_lock);
diff --git a/be/src/exec/set_operation_node.cpp b/be/src/exec/set_operation_node.cpp
index 5958c2569d..e0bfbb199c 100644
--- a/be/src/exec/set_operation_node.cpp
+++ b/be/src/exec/set_operation_node.cpp
@@ -138,6 +138,7 @@ Status SetOperationNode::open(RuntimeState* state) {
     RETURN_IF_ERROR(ExecNode::open(state));
     RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::OPEN));
     SCOPED_TIMER(_runtime_profile->total_time_counter());
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("SetOperation, while constructing the hash table.");
     RETURN_IF_CANCELLED(state);
     // open result expr lists.
     for (const std::vector<ExprContext*>& exprs : _child_expr_lists) {
@@ -156,7 +157,6 @@ Status SetOperationNode::open(RuntimeState* state) {
         RETURN_IF_ERROR(child(0)->get_next(state, &build_batch, &eos));
         // take ownership of tuple data of build_batch
         _build_pool->acquire_data(build_batch.tuple_data_pool(), false);
-        RETURN_IF_LIMIT_EXCEEDED(state, " SetOperation, while constructing the hash table.");
         // build hash table and remove duplicate items
         RETURN_IF_ERROR(_hash_tbl->resize_buckets_ahead(build_batch.num_rows()));
         for (int i = 0; i < build_batch.num_rows(); ++i) {
diff --git a/be/src/exec/tablet_sink.cpp b/be/src/exec/tablet_sink.cpp
index 2d9733e9bf..1aa0cdf692 100644
--- a/be/src/exec/tablet_sink.cpp
+++ b/be/src/exec/tablet_sink.cpp
@@ -443,7 +443,7 @@ void NodeChannel::cancel(const std::string& cancel_msg) {
     request.release_id();
 }
 
-int NodeChannel::try_send_and_fetch_status(std::unique_ptr<ThreadPoolToken>& thread_pool_token) {
+int NodeChannel::try_send_and_fetch_status(RuntimeState* state, std::unique_ptr<ThreadPoolToken>& thread_pool_token) {
     auto st = none_of({_cancelled, _send_finished});
     if (!st.ok()) {
         return 0;
@@ -456,7 +456,7 @@ int NodeChannel::try_send_and_fetch_status(std::unique_ptr<ThreadPoolToken>& thr
     // We are sure that try_send_batch is not running
     if (_pending_batches_num > 0) {
         auto s = thread_pool_token->submit_func(
-                std::bind(&NodeChannel::try_send_batch, this));
+                std::bind(&NodeChannel::try_send_batch, this, state));
         if (!s.ok()) {
             _cancel_with_msg("submit send_batch task to send_batch_thread_pool failed");
             // clear in flight
@@ -470,8 +470,9 @@ int NodeChannel::try_send_and_fetch_status(std::unique_ptr<ThreadPoolToken>& thr
     return _send_finished ? 0 : 1;
 }
 
-void NodeChannel::try_send_batch() {
+void NodeChannel::try_send_batch(RuntimeState* state) {
     SCOPED_ATOMIC_TIMER(&_actual_consume_ns);
+    SCOPED_ATTACH_TASK(state);
     AddBatchReq send_batch;
     {
         debug::ScopedTSANIgnoreReadsAndWrites ignore_tsan;
@@ -901,7 +902,7 @@ Status OlapTableSink::open(RuntimeState* state) {
     _send_batch_thread_pool_token = state->exec_env()->send_batch_thread_pool()->new_token(
             ThreadPool::ExecutionMode::CONCURRENT, send_batch_parallelism);
     RETURN_IF_ERROR(Thread::create(
-            "OlapTableSink", "send_batch_process", [this]() { this->_send_batch_process(); },
+            "OlapTableSink", "send_batch_process", [this, state]() { this->_send_batch_process(state); },
             &_sender_thread));
 
     return Status::OK();
@@ -1293,14 +1294,15 @@ Status OlapTableSink::_validate_data(RuntimeState* state, RowBatch* batch, Bitma
     return Status::OK();
 }
 
-void OlapTableSink::_send_batch_process() {
+void OlapTableSink::_send_batch_process(RuntimeState* state) {
     SCOPED_TIMER(_non_blocking_send_timer);
+    SCOPED_ATTACH_TASK(state);
     do {
         int running_channels_num = 0;
         for (auto index_channel : _channels) {
-            index_channel->for_each_node_channel([&running_channels_num, this](const std::shared_ptr<NodeChannel>& ch) {
+            index_channel->for_each_node_channel([&running_channels_num, this, state](const std::shared_ptr<NodeChannel>& ch) {
                 running_channels_num +=
-                        ch->try_send_and_fetch_status(this->_send_batch_thread_pool_token);
+                        ch->try_send_and_fetch_status(state, this->_send_batch_thread_pool_token);
             });
         }
 
diff --git a/be/src/exec/tablet_sink.h b/be/src/exec/tablet_sink.h
index f1f6e26574..d3e083363d 100644
--- a/be/src/exec/tablet_sink.h
+++ b/be/src/exec/tablet_sink.h
@@ -193,9 +193,9 @@ public:
     // 1: running, haven't reach eos.
     // only allow 1 rpc in flight
     // plz make sure, this func should be called after open_wait().
-    int try_send_and_fetch_status(std::unique_ptr<ThreadPoolToken>& thread_pool_token);
+    int try_send_and_fetch_status(RuntimeState* state, std::unique_ptr<ThreadPoolToken>& thread_pool_token);
 
-    void try_send_batch();
+    void try_send_batch(RuntimeState* state);
 
     void time_report(std::unordered_map<int64_t, AddBatchCounter>* add_batch_counter_map,
                      int64_t* serialize_batch_ns, int64_t* mem_exceeded_block_ns,
@@ -403,7 +403,7 @@ private:
     // the consumer func of sending pending batches in every NodeChannel.
     // use polling & NodeChannel::try_send_and_fetch_status() to achieve nonblocking sending.
     // only focus on pending batches and channel status, the internal errors of NodeChannels will be handled by the producer
-    void _send_batch_process();
+    void _send_batch_process(RuntimeState* state);
 
 protected:
     friend class NodeChannel;
diff --git a/be/src/gutil/strings/numbers.cc b/be/src/gutil/strings/numbers.cc
index 5027dea46b..506075c7ab 100644
--- a/be/src/gutil/strings/numbers.cc
+++ b/be/src/gutil/strings/numbers.cc
@@ -1479,6 +1479,49 @@ string ItoaKMGT(int64 i) {
     return StringPrintf("%s%" PRId64 "%s", sign, val, suffix);
 }
 
+string AccurateItoaKMGT(int64 i) {
+    const char* sign = "";
+    if (i < 0) {
+        // We lose some accuracy if the caller passes LONG_LONG_MIN, but
+        // that's OK as this function is only for human readability
+        if (i == numeric_limits<int64>::min()) i++;
+        sign = "-";
+        i = -i;
+    }
+
+    string ret = StringPrintf("%s", sign);
+    int64 val;
+    if ((val = (i >> 40)) > 1) {
+        ret += StringPrintf("%" PRId64
+                            "%s"
+                            ",",
+                            val, "T");
+        i = i - (val << 40);
+    }
+    if ((val = (i >> 30)) > 1) {
+        ret += StringPrintf("%" PRId64
+                            "%s"
+                            ",",
+                            val, "G");
+        i = i - (val << 30);
+    }
+    if ((val = (i >> 20)) > 1) {
+        ret += StringPrintf("%" PRId64
+                            "%s"
+                            ",",
+                            val, "M");
+        i = i - (val << 20);
+    }
+    if ((val = (i >> 10)) > 1) {
+        ret += StringPrintf("%" PRId64 "%s", val, "K");
+        i = i - (val << 10);
+    } else {
+        ret += StringPrintf("%" PRId64 "%s", i, "K");
+    }
+
+    return ret;
+}
+
 // DEPRECATED(wadetregaskis).
 // These are non-inline because some BUILD files turn on -Wformat-non-literal.
 
diff --git a/be/src/gutil/strings/numbers.h b/be/src/gutil/strings/numbers.h
index 00a10d37a8..01540d2900 100644
--- a/be/src/gutil/strings/numbers.h
+++ b/be/src/gutil/strings/numbers.h
@@ -474,8 +474,12 @@ char* SimpleItoaWithCommas(__int128_t i, char* buffer, int32_t buffer_size);
 //    e.g. 3000 -> 2K   57185920 -> 45M
 //
 //    Return value: string
+//
+// AccurateItoaKMGT()
+//    Description: preserve accuracy
 // ----------------------------------------------------------------------
 string ItoaKMGT(int64 i);
+string AccurateItoaKMGT(int64 i);
 
 // ----------------------------------------------------------------------
 // ParseDoubleRange()
diff --git a/be/src/http/default_path_handlers.cpp b/be/src/http/default_path_handlers.cpp
index d8416970dc..c7cdcd2ad8 100644
--- a/be/src/http/default_path_handlers.cpp
+++ b/be/src/http/default_path_handlers.cpp
@@ -30,6 +30,7 @@
 #include "http/action/tablets_info_action.h"
 #include "http/web_page_handler.h"
 #include "runtime/mem_tracker.h"
+#include "runtime/memory/mem_tracker_limiter.h"
 #include "util/debug_util.h"
 #include "util/pretty_printer.h"
 #include "util/thread.h"
@@ -129,18 +130,19 @@ void mem_tracker_handler(const WebPageHandler::ArgumentMap& args, std::stringstr
                  "       data-search='true' "
                  "       class='table table-striped'>\n";
     (*output) << "<thead><tr>"
-                 "<th data-sortable='true' "
-                 ">Id</th>"
+                 "<th data-sortable='true'>Level</th>"
+                 "<th data-sortable='true'>Label</th>"
                  "<th>Parent</th>"
                  "<th>Limit</th>"
-                 "<th data-sorter='bytesSorter' "
-                 "    data-sortable='true' "
-                 ">Current Consumption</th>"
-                 "<th data-sorter='bytesSorter' "
-                 "    data-sortable='true' "
-                 ">Peak Consumption</th>"
                  "<th data-sortable='true' "
-                 ">Use Count</th></tr></thead>";
+                 ">Current Consumption(Bytes)</th>"
+                 "<th>Current Consumption(Normalize)</th>"
+                 "<th data-sortable='true' "
+                 ">Peak Consumption(Bytes)</th>"
+                 "<th>Peak Consumption(Normalize)</th>"
+                 "<th data-sortable='true' "
+                 ">Child Count</th>"
+                 "</tr></thead>";
     (*output) << "<tbody>\n";
 
     std::vector<shared_ptr<MemTracker>> trackers;
@@ -151,11 +153,39 @@ void mem_tracker_handler(const WebPageHandler::ArgumentMap& args, std::stringstr
         string current_consumption_str = ItoaKMGT(tracker->consumption());
         string peak_consumption_str = ItoaKMGT(tracker->peak_consumption());
         int64_t use_count = tracker.use_count();
+        string current_consumption_normalize = AccurateItoaKMGT(tracker->consumption());
+        string peak_consumption_normalize = AccurateItoaKMGT(tracker->peak_consumption());
         (*output) << strings::Substitute(
-                "<tr><td>$0</td><td>$1</td><td>$2</td>" // id, parent, limit
-                "<td>$3</td><td>$4</td><td>$5</td></tr>\n",        // current, peak
-                tracker->label(), parent, limit_str, current_consumption_str, peak_consumption_str, use_count);
+                "<tr><td>$0</td><td>$1</td><td>$2</td><td>$3</td><td>$4</td><td>$5</td><td>$6</"
+                "td><td>$7</td><td>$8</td></tr>\n",
+                -1, tracker->label(), parent, limit_str, current_consumption_str,
+                current_consumption_normalize, peak_consumption_str, peak_consumption_normalize,
+                use_count);
     }
+
+    size_t upper_level;
+    size_t cur_level = 1;
+    // the level equal or lower than upper_level will show in web page
+    auto iter = args.find("upper_level");
+    if (iter != args.end()) {
+        upper_level = std::stol(iter->second);
+    } else {
+        upper_level = 3;
+    }
+    std::vector<NewMemTracker::Snapshot> snapshots;
+    ExecEnv::GetInstance()->new_process_mem_tracker()->make_snapshot(&snapshots, cur_level, upper_level);
+    for (const auto& item : snapshots) {
+        string limit_str = item.limit == -1 ? "none" : AccurateItoaKMGT(item.limit);
+        string current_consumption_normalize = AccurateItoaKMGT(item.cur_consumption);
+        string peak_consumption_normalize = AccurateItoaKMGT(item.peak_consumption);
+        (*output) << strings::Substitute(
+                "<tr><td>$0</td><td>$1</td><td>$2</td><td>$3</td><td>$4</td><td>$5</td><td>$6</"
+                "td><td>$7</td><td>$8</td></tr>\n",
+                item.level, item.label, item.parent, limit_str, item.cur_consumption,
+                current_consumption_normalize, item.peak_consumption, peak_consumption_normalize,
+                item.child_count);
+    }
+
     (*output) << "</tbody></table>\n";
 }
 
diff --git a/be/src/olap/base_compaction.cpp b/be/src/olap/base_compaction.cpp
index f1722d328a..6277e2417b 100644
--- a/be/src/olap/base_compaction.cpp
+++ b/be/src/olap/base_compaction.cpp
@@ -19,6 +19,7 @@
 
 #include "util/doris_metrics.h"
 #include "util/trace.h"
+#include "runtime/thread_context.h"
 
 namespace doris {
 
@@ -64,6 +65,8 @@ OLAPStatus BaseCompaction::execute_compact_impl() {
         return OLAP_ERR_BE_CLONE_OCCURRED;
     }
 
+    SCOPED_ATTACH_TASK(StorageEngine::instance()->new_compaction_mem_tracker(), ThreadContext::TaskType::COMPACTION);
+
     // 2. do base compaction, merge rowsets
     int64_t permits = get_compaction_permits();
     RETURN_NOT_OK(do_compaction(permits));
diff --git a/be/src/olap/byte_buffer.cpp b/be/src/olap/byte_buffer.cpp
index 6b2747c12e..94fd6453f7 100644
--- a/be/src/olap/byte_buffer.cpp
+++ b/be/src/olap/byte_buffer.cpp
@@ -20,6 +20,7 @@
 #include <sys/mman.h>
 
 #include "olap/utils.h"
+#include "runtime/thread_context.h"
 
 namespace doris {
 
@@ -42,6 +43,8 @@ void StorageByteBuffer::BufDeleter::operator()(char* p) {
         if (0 != munmap(p, _mmap_length)) {
             LOG(FATAL) << "fail to munmap: mem=" << p << ", len=" << _mmap_length
                        << ", errno=" << Errno::no() << ", errno_str=" << Errno::str();
+        } else {
+            RELEASE_THREAD_MEM_TRACKER(_mmap_length);
         }
     } else {
         delete[] p;
@@ -93,10 +96,12 @@ StorageByteBuffer* StorageByteBuffer::reference_buffer(StorageByteBuffer* refere
 
 StorageByteBuffer* StorageByteBuffer::mmap(void* start, uint64_t length, int prot, int flags,
                                            int fd, uint64_t offset) {
+    CONSUME_THREAD_MEM_TRACKER(length);
     char* memory = (char*)::mmap(start, length, prot, flags, fd, offset);
 
     if (MAP_FAILED == memory) {
         OLAP_LOG_WARNING("fail to mmap. [errno='%d' errno_str='%s']", Errno::no(), Errno::str());
+        RELEASE_THREAD_MEM_TRACKER(length);
         return nullptr;
     }
 
@@ -108,6 +113,7 @@ StorageByteBuffer* StorageByteBuffer::mmap(void* start, uint64_t length, int pro
     if (nullptr == buf) {
         deleter(memory);
         OLAP_LOG_WARNING("fail to allocate StorageByteBuffer.");
+        RELEASE_THREAD_MEM_TRACKER(length);
         return nullptr;
     }
 
@@ -128,10 +134,12 @@ StorageByteBuffer* StorageByteBuffer::mmap(FileHandler* handler, uint64_t offset
 
     size_t length = handler->length();
     int fd = handler->fd();
+    CONSUME_THREAD_MEM_TRACKER(length);
     char* memory = (char*)::mmap(nullptr, length, prot, flags, fd, offset);
 
     if (MAP_FAILED == memory) {
         OLAP_LOG_WARNING("fail to mmap. [errno='%d' errno_str='%s']", Errno::no(), Errno::str());
+        RELEASE_THREAD_MEM_TRACKER(length);
         return nullptr;
     }
 
@@ -143,6 +151,7 @@ StorageByteBuffer* StorageByteBuffer::mmap(FileHandler* handler, uint64_t offset
     if (nullptr == buf) {
         deleter(memory);
         OLAP_LOG_WARNING("fail to allocate StorageByteBuffer.");
+        RELEASE_THREAD_MEM_TRACKER(length);
         return nullptr;
     }
 
diff --git a/be/src/olap/cumulative_compaction.cpp b/be/src/olap/cumulative_compaction.cpp
index 864a7ec0a6..15de430609 100644
--- a/be/src/olap/cumulative_compaction.cpp
+++ b/be/src/olap/cumulative_compaction.cpp
@@ -19,6 +19,7 @@
 
 #include "util/doris_metrics.h"
 #include "util/time.h"
+#include "runtime/thread_context.h"
 #include "util/trace.h"
 
 namespace doris {
@@ -71,6 +72,8 @@ OLAPStatus CumulativeCompaction::execute_compact_impl() {
         return OLAP_ERR_CUMULATIVE_CLONE_OCCURRED;
     }
 
+    SCOPED_ATTACH_TASK(StorageEngine::instance()->new_compaction_mem_tracker(), ThreadContext::TaskType::COMPACTION);
+
     // 3. do cumulative compaction, merge rowsets
     int64_t permits = get_compaction_permits();
     RETURN_NOT_OK(do_compaction(permits));
diff --git a/be/src/olap/generic_iterators.cpp b/be/src/olap/generic_iterators.cpp
index 2765096cb1..f0d2721433 100644
--- a/be/src/olap/generic_iterators.cpp
+++ b/be/src/olap/generic_iterators.cpp
@@ -214,7 +214,7 @@ class MergeIterator : public RowwiseIterator {
 public:
     // MergeIterator takes the ownership of input iterators
     MergeIterator(std::vector<RowwiseIterator*> iters, std::shared_ptr<MemTracker> parent, int sequence_id_idx, bool is_unique, uint64_t* merged_rows)
-        : _origin_iters(std::move(iters)), _sequence_id_idx(sequence_id_idx), _is_unique(is_unique), _merged_rows(merged_rows), _merge_heap(MergeContextComparator(_sequence_id_idx, is_unique)) {
+        : _origin_iters(std::move(iters)), _sequence_id_idx(sequence_id_idx), _merged_rows(merged_rows), _merge_heap(MergeContextComparator(_sequence_id_idx, is_unique)) {
         // use for count the mem use of Block use in Merge
         _mem_tracker = MemTracker::CreateTracker(-1, "MergeIterator", std::move(parent), false);
     }
@@ -238,7 +238,6 @@ private:
     std::vector<RowwiseIterator*> _origin_iters;
 
     int _sequence_id_idx;
-    bool _is_unique;
 
     std::unique_ptr<Schema> _schema;
     uint64_t* _merged_rows;
diff --git a/be/src/olap/lru_cache.cpp b/be/src/olap/lru_cache.cpp
index ca73ab1d8b..9a196d19cd 100644
--- a/be/src/olap/lru_cache.cpp
+++ b/be/src/olap/lru_cache.cpp
@@ -292,7 +292,7 @@ void LRUCache::_evict_one_entry(LRUHandle* e) {
 
 Cache::Handle* LRUCache::insert(const CacheKey& key, uint32_t hash, void* value, size_t charge,
                                 void (*deleter)(const CacheKey& key, void* value),
-                                CachePriority priority) {
+                                MemTrackerLimiter* tracker, CachePriority priority) {
     size_t handle_size = sizeof(LRUHandle) - 1 + key.size();
     LRUHandle* e = reinterpret_cast<LRUHandle*>(malloc(handle_size));
     e->value = value;
@@ -305,7 +305,11 @@ Cache::Handle* LRUCache::insert(const CacheKey& key, uint32_t hash, void* value,
     e->next = e->prev = nullptr;
     e->in_cache = true;
     e->priority = priority;
+    e->mem_tracker = tracker;
     memcpy(e->key_data, key.data(), key.size());
+    // The memory of the parameter value should be recorded in the tls mem tracker,
+    // transfer the memory ownership of the value to ShardedLRUCache::_mem_tracker.
+    THREAD_MEM_TRACKER_TRANSFER_TO(e->total_size, tracker);
     LRUHandle* to_remove_head = nullptr;
     {
         MutexLock l(&_mutex);
@@ -444,6 +448,7 @@ ShardedLRUCache::ShardedLRUCache(const std::string& name, size_t total_capacity,
           _last_id(1),
           _mem_tracker(MemTracker::CreateTracker(-1, name, parent, true, false,
                                                  MemTrackerLevel::OVERVIEW)) {
+    _new_mem_tracker = std::make_unique<MemTrackerLimiter>(-1, "New" + name);
     const size_t per_shard = (total_capacity + (kNumShards - 1)) / kNumShards;
     for (int s = 0; s < kNumShards; s++) {
         _shards[s] = new LRUCache(type);
@@ -474,7 +479,7 @@ Cache::Handle* ShardedLRUCache::insert(const CacheKey& key, void* value, size_t
                                        void (*deleter)(const CacheKey& key, void* value),
                                        CachePriority priority) {
     const uint32_t hash = _hash_slice(key);
-    return _shards[_shard(hash)]->insert(key, hash, value, charge, deleter, priority);
+    return _shards[_shard(hash)]->insert(key, hash, value, charge, deleter, _new_mem_tracker.get(), priority);
 }
 
 Cache::Handle* ShardedLRUCache::lookup(const CacheKey& key) {
diff --git a/be/src/olap/lru_cache.h b/be/src/olap/lru_cache.h
index 0ff3ce16a6..1896164aea 100644
--- a/be/src/olap/lru_cache.h
+++ b/be/src/olap/lru_cache.h
@@ -16,6 +16,7 @@
 
 #include "olap/olap_common.h"
 #include "runtime/mem_tracker.h"
+#include "runtime/thread_context.h"
 #include "util/metrics.h"
 #include "util/mutex.h"
 #include "util/slice.h"
@@ -241,6 +242,7 @@ typedef struct LRUHandle {
     uint32_t refs;
     uint32_t hash; // Hash of key(); used for fast sharding and comparisons
     CachePriority priority = CachePriority::NORMAL;
+    MemTrackerLimiter* mem_tracker;
     char key_data[1]; // Beginning of key
 
     CacheKey key() const {
@@ -255,6 +257,7 @@ typedef struct LRUHandle {
 
     void free() {
         (*deleter)(key(), value);
+        THREAD_MEM_TRACKER_TRANSFER_FROM(total_size, mem_tracker);
         ::free(this);
     }
 
@@ -315,6 +318,7 @@ public:
     // Like Cache methods, but with an extra "hash" parameter.
     Cache::Handle* insert(const CacheKey& key, uint32_t hash, void* value, size_t charge,
                           void (*deleter)(const CacheKey& key, void* value),
+                          MemTrackerLimiter* tracker,
                           CachePriority priority = CachePriority::NORMAL);
     Cache::Handle* lookup(const CacheKey& key, uint32_t hash);
     void release(Cache::Handle* handle);
@@ -390,6 +394,7 @@ private:
     std::atomic<uint64_t> _last_id;
 
     std::shared_ptr<MemTracker> _mem_tracker;
+    std::unique_ptr<MemTrackerLimiter> _new_mem_tracker;
     std::shared_ptr<MetricEntity> _entity = nullptr;
     IntGauge* capacity = nullptr;
     IntGauge* usage = nullptr;
diff --git a/be/src/olap/out_stream.cpp b/be/src/olap/out_stream.cpp
index 2b7000ec23..7e7497645e 100644
--- a/be/src/olap/out_stream.cpp
+++ b/be/src/olap/out_stream.cpp
@@ -26,7 +26,7 @@
 namespace doris {
 
 OutStreamFactory::OutStreamFactory(CompressKind compress_kind, uint32_t stream_buffer_size)
-        : _compress_kind(compress_kind), _stream_buffer_size(stream_buffer_size) {
+        : _stream_buffer_size(stream_buffer_size) {
     switch (compress_kind) {
     case COMPRESS_NONE:
         _compressor = nullptr;
diff --git a/be/src/olap/out_stream.h b/be/src/olap/out_stream.h
index 533f6a1fdb..013869c636 100644
--- a/be/src/olap/out_stream.h
+++ b/be/src/olap/out_stream.h
@@ -142,7 +142,6 @@ public:
 
 private:
     std::map<StreamName, OutStream*> _streams; // All created streams
-    CompressKind _compress_kind;
     Compressor _compressor;
     uint32_t _stream_buffer_size;
 
diff --git a/be/src/olap/rowset/column_writer.cpp b/be/src/olap/rowset/column_writer.cpp
index 5ca0ce94ea..e3dd0a8781 100644
--- a/be/src/olap/rowset/column_writer.cpp
+++ b/be/src/olap/rowset/column_writer.cpp
@@ -488,8 +488,7 @@ void ByteColumnWriter::record_position() {
 
 IntegerColumnWriter::IntegerColumnWriter(uint32_t column_id, uint32_t unique_column_id,
                                          OutStreamFactory* stream_factory, bool is_singed)
-        : _column_id(column_id),
-          _unique_column_id(unique_column_id),
+        : _unique_column_id(unique_column_id),
           _stream_factory(stream_factory),
           _writer(nullptr),
           _is_signed(is_singed) {}
diff --git a/be/src/olap/rowset/column_writer.h b/be/src/olap/rowset/column_writer.h
index 42bc54caa2..96ca157dcf 100644
--- a/be/src/olap/rowset/column_writer.h
+++ b/be/src/olap/rowset/column_writer.h
@@ -179,7 +179,6 @@ public:
     OLAPStatus flush() { return _writer->flush(); }
 
 private:
-    uint32_t _column_id;
     uint32_t _unique_column_id;
     OutStreamFactory* _stream_factory;
     RunLengthIntegerWriter* _writer;
diff --git a/be/src/olap/rowset/segment_v2/bitshuffle_page.h b/be/src/olap/rowset/segment_v2/bitshuffle_page.h
index 8ca4727835..9b5585f530 100644
--- a/be/src/olap/rowset/segment_v2/bitshuffle_page.h
+++ b/be/src/olap/rowset/segment_v2/bitshuffle_page.h
@@ -239,7 +239,7 @@ private:
     CppType _last_value;
 };
 
-static Status parse_bit_shuffle_header(const Slice& data, size_t& num_elements,
+static inline Status parse_bit_shuffle_header(const Slice& data, size_t& num_elements,
                                        size_t& compressed_size, size_t& num_element_after_padding,
                                        int& size_of_element) {
     if (data.size < BITSHUFFLE_PAGE_HEADER_SIZE) {
diff --git a/be/src/olap/storage_engine.cpp b/be/src/olap/storage_engine.cpp
index 58b3c8bca0..c3d139ed6f 100644
--- a/be/src/olap/storage_engine.cpp
+++ b/be/src/olap/storage_engine.cpp
@@ -112,8 +112,10 @@ StorageEngine::StorageEngine(const EngineOptions& options)
           _is_all_cluster_id_exist(true),
           _index_stream_lru_cache(nullptr),
           _file_cache(nullptr),
-          _compaction_mem_tracker(MemTracker::CreateTracker(-1, "AutoCompaction", nullptr, false,
+          _compaction_mem_tracker(MemTracker::CreateTracker(-1, "OldAutoCompaction", nullptr, false,
                                                             false, MemTrackerLevel::OVERVIEW)),
+          _new_compaction_mem_tracker(
+                  std::make_shared<MemTrackerLimiter>(-1, "StorageEngine::AutoCompaction")),
           _tablet_mem_tracker(MemTracker::CreateTracker(-1, "TabletHeader", nullptr, false, false,
                                                         MemTrackerLevel::OVERVIEW)),
           _convert_rowset_mem_tracker(MemTracker::CreateTracker(-1, "ConvertRowset", nullptr, false,
diff --git a/be/src/olap/storage_engine.h b/be/src/olap/storage_engine.h
index 18a6960030..990d1cc291 100644
--- a/be/src/olap/storage_engine.h
+++ b/be/src/olap/storage_engine.h
@@ -184,6 +184,7 @@ public:
 
     Status get_compaction_status_json(std::string* result);
 
+    std::shared_ptr<MemTrackerLimiter> new_compaction_mem_tracker() { return _new_compaction_mem_tracker; }
     std::shared_ptr<MemTracker> tablet_mem_tracker() { return _tablet_mem_tracker; }
     std::shared_ptr<MemTracker> schema_change_mem_tracker() { return _schema_change_mem_tracker; }
 
@@ -330,6 +331,8 @@ private:
     std::unordered_map<std::string, RowsetSharedPtr> _unused_rowsets;
 
     std::shared_ptr<MemTracker> _compaction_mem_tracker;
+    // Count the memory consumption of all Base and Cumulative tasks.
+    std::shared_ptr<MemTrackerLimiter> _new_compaction_mem_tracker;
     std::shared_ptr<MemTracker> _tablet_mem_tracker;
     std::shared_ptr<MemTracker> _schema_change_mem_tracker;
     std::shared_ptr<MemTracker> _convert_rowset_mem_tracker;
diff --git a/be/src/runtime/CMakeLists.txt b/be/src/runtime/CMakeLists.txt
index da50458794..bc23bd4c97 100644
--- a/be/src/runtime/CMakeLists.txt
+++ b/be/src/runtime/CMakeLists.txt
@@ -104,6 +104,10 @@ set(RUNTIME_FILES
     mysql_result_writer.cpp
     memory/system_allocator.cpp
     memory/chunk_allocator.cpp
+    memory/mem_tracker_limiter.cpp
+    memory/mem_tracker.cpp
+    memory/mem_tracker_task_pool.cpp
+    memory/thread_mem_tracker_mgr.cpp
     fold_constant_executor.cpp
     cache/result_node.cpp
     cache/result_cache.cpp
diff --git a/be/src/runtime/bufferpool/system_allocator.cc b/be/src/runtime/bufferpool/system_allocator.cc
index a2dfc394b1..1368b93a35 100644
--- a/be/src/runtime/bufferpool/system_allocator.cc
+++ b/be/src/runtime/bufferpool/system_allocator.cc
@@ -23,6 +23,7 @@
 #include "common/config.h"
 #include "gutil/strings/substitute.h"
 #include "util/bit_util.h"
+#include "runtime/thread_context.h"
 #include "util/error_util.h"
 
 // TODO: IMPALA-5073: this should eventually become the default once we are confident
@@ -75,9 +76,11 @@ Status SystemAllocator::AllocateViaMMap(int64_t len, uint8_t** buffer_mem) {
         // Map an extra huge page so we can fix up the alignment if needed.
         map_len += HUGE_PAGE_SIZE;
     }
+    CONSUME_THREAD_MEM_TRACKER(map_len);
     uint8_t* mem = reinterpret_cast<uint8_t*>(
             mmap(nullptr, map_len, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0));
     if (mem == MAP_FAILED) {
+        RELEASE_THREAD_MEM_TRACKER(map_len);
         return Status::BufferAllocFailed("mmap failed");
     }
 
@@ -89,10 +92,12 @@ Status SystemAllocator::AllocateViaMMap(int64_t len, uint8_t** buffer_mem) {
         if (misalignment != 0) {
             uintptr_t fixup = HUGE_PAGE_SIZE - misalignment;
             munmap(mem, fixup);
+            RELEASE_THREAD_MEM_TRACKER(fixup);
             mem += fixup;
             map_len -= fixup;
         }
         munmap(mem + len, map_len - len);
+        RELEASE_THREAD_MEM_TRACKER(map_len - len);
         DCHECK_EQ(reinterpret_cast<uintptr_t>(mem) % HUGE_PAGE_SIZE, 0) << mem;
         // Mark the buffer as a candidate for promotion to huge pages. The Linux Transparent
         // Huge Pages implementation will try to back the memory with a huge page if it is
@@ -142,6 +147,7 @@ Status SystemAllocator::AllocateViaMalloc(int64_t len, uint8_t** buffer_mem) {
 void SystemAllocator::Free(BufferPool::BufferHandle&& buffer) {
     if (config::mmap_buffers) {
         int rc = munmap(buffer.data(), buffer.len());
+        RELEASE_THREAD_MEM_TRACKER(buffer.len());
         DCHECK_EQ(rc, 0) << "Unexpected munmap() error: " << errno;
     } else {
         bool use_huge_pages = buffer.len() % HUGE_PAGE_SIZE == 0 && config::madvise_huge_pages;
diff --git a/be/src/runtime/data_stream_recvr.cc b/be/src/runtime/data_stream_recvr.cc
index f38049dc6f..aca437ef36 100644
--- a/be/src/runtime/data_stream_recvr.cc
+++ b/be/src/runtime/data_stream_recvr.cc
@@ -197,6 +197,9 @@ Status DataStreamRecvr::SenderQueue::get_batch(RowBatch** next_batch) {
 void DataStreamRecvr::SenderQueue::add_batch(const PRowBatch& pb_batch, int be_number,
                                              int64_t packet_seq,
                                              ::google::protobuf::Closure** done) {
+    // Avoid deadlock when calling SenderQueue::cancel() in tcmalloc hook,
+    // limit memory via DataStreamRecvr::exceeds_limit.
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
     lock_guard<mutex> l(_lock);
     if (_is_cancelled) {
         return;
@@ -266,6 +269,9 @@ void DataStreamRecvr::SenderQueue::add_batch(const PRowBatch& pb_batch, int be_n
 }
 
 void DataStreamRecvr::SenderQueue::add_batch(RowBatch* batch, bool use_move) {
+    // Avoid deadlock when calling SenderQueue::cancel() in tcmalloc hook,
+    // limit memory via DataStreamRecvr::exceeds_limit.
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
     unique_lock<mutex> l(_lock);
     if (_is_cancelled) {
         return;
diff --git a/be/src/runtime/exec_env.h b/be/src/runtime/exec_env.h
index ca04bf32e2..5959e8cf5b 100644
--- a/be/src/runtime/exec_env.h
+++ b/be/src/runtime/exec_env.h
@@ -45,7 +45,9 @@ class LoadPathMgr;
 class LoadStreamMgr;
 class MemTracker;
 class StorageEngine;
+class MemTrackerLimiter;
 class PoolMemTrackerRegistry;
+class MemTrackerTaskPool;
 class PriorityThreadPool;
 class PriorityWorkStealingThreadPool;
 class ReservationTracker;
@@ -118,6 +120,12 @@ public:
 
     std::shared_ptr<MemTracker> process_mem_tracker() { return _mem_tracker; }
     PoolMemTrackerRegistry* pool_mem_trackers() { return _pool_mem_trackers; }
+
+    std::shared_ptr<MemTrackerLimiter> new_process_mem_tracker() { return _process_mem_tracker; }
+    std::shared_ptr<MemTrackerLimiter> query_pool_mem_tracker() { return _query_pool_mem_tracker; }
+    std::shared_ptr<MemTrackerLimiter> load_pool_mem_tracker() { return _load_pool_mem_tracker; }
+    MemTrackerTaskPool* task_pool_mem_tracker_registry() { return _task_pool_mem_tracker_registry; }
+
     ThreadResourceMgr* thread_mgr() { return _thread_mgr; }
     PriorityThreadPool* scan_thread_pool() { return _scan_thread_pool; }
     ThreadPool* limited_scan_thread_pool() { return _limited_scan_thread_pool.get(); }
@@ -188,6 +196,15 @@ private:
     PoolMemTrackerRegistry* _pool_mem_trackers = nullptr;
     ThreadResourceMgr* _thread_mgr = nullptr;
 
+    // The ancestor for all trackers. Every tracker is visible from the process down.
+    // Not limit total memory by process tracker, and it's just used to track virtual memory of process.
+    std::shared_ptr<MemTrackerLimiter> _process_mem_tracker;
+    // The ancestor for all querys tracker.
+    std::shared_ptr<MemTrackerLimiter> _query_pool_mem_tracker;
+    // The ancestor for all load tracker.
+    std::shared_ptr<MemTrackerLimiter> _load_pool_mem_tracker;
+    MemTrackerTaskPool* _task_pool_mem_tracker_registry;
+
     // The following two thread pools are used in different scenarios.
     // _scan_thread_pool is a priority thread pool.
     // Scanner threads for common queries will use this thread pool,
diff --git a/be/src/runtime/exec_env_init.cpp b/be/src/runtime/exec_env_init.cpp
index c2e500b193..b0f66c2dcb 100644
--- a/be/src/runtime/exec_env_init.cpp
+++ b/be/src/runtime/exec_env_init.cpp
@@ -44,6 +44,9 @@
 #include "runtime/load_channel_mgr.h"
 #include "runtime/load_path_mgr.h"
 #include "runtime/mem_tracker.h"
+#include "runtime/memory/chunk_allocator.h"
+#include "runtime/memory/mem_tracker_task_pool.h"
+#include "runtime/thread_context.h"
 #include "runtime/result_buffer_mgr.h"
 #include "runtime/result_queue_mgr.h"
 #include "runtime/routine_load/routine_load_task_executor.h"
@@ -65,6 +68,11 @@
 #include "util/priority_work_stealing_thread_pool.hpp"
 #include "vec/runtime/vdata_stream_mgr.h"
 
+#if !defined(__SANITIZE_ADDRESS__) && !defined(ADDRESS_SANITIZER) && !defined(LEAK_SANITIZER) && \
+        !defined(THREAD_SANITIZER) && !defined(USE_JEMALLOC)
+#include "runtime/memory/tcmalloc_hook.h"
+#endif
+
 namespace doris {
 
 DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(scanner_thread_pool_queue_size, MetricUnit::NOUNIT);
@@ -97,6 +105,7 @@ Status ExecEnv::_init(const std::vector<StorePath>& store_paths) {
     _backend_client_cache = new BackendServiceClientCache(config::max_client_cache_size_per_host);
     _frontend_client_cache = new FrontendServiceClientCache(config::max_client_cache_size_per_host);
     _broker_client_cache = new BrokerServiceClientCache(config::max_client_cache_size_per_host);
+    _task_pool_mem_tracker_registry = new MemTrackerTaskPool();
     _extdatasource_client_cache =
             new ExtDataSourceServiceClientCache(config::max_client_cache_size_per_host);
     _pool_mem_trackers = new PoolMemTrackerRegistry();
@@ -190,10 +199,27 @@ Status ExecEnv::_init_mem_tracker() {
                      << ". Using physical memory instead";
         global_memory_limit_bytes = MemInfo::physical_mem();
     }
-    _mem_tracker = MemTracker::CreateTracker(global_memory_limit_bytes, "Process",
+    _mem_tracker = MemTracker::CreateTracker(global_memory_limit_bytes, "OldProcess",
                                              MemTracker::GetRootTracker(), false, false,
                                              MemTrackerLevel::OVERVIEW);
     REGISTER_HOOK_METRIC(query_mem_consumption, [this]() { return _mem_tracker->consumption(); });
+
+    _process_mem_tracker =
+            std::make_shared<MemTrackerLimiter>(global_memory_limit_bytes, "Process");
+    thread_context()->_thread_mem_tracker_mgr->init();
+    thread_context()->_thread_mem_tracker_mgr->set_check_attach(false);
+#if defined(USE_MEM_TRACKER) && !defined(__SANITIZE_ADDRESS__) && !defined(ADDRESS_SANITIZER) && \
+        !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) && !defined(USE_JEMALLOC)
+    if (doris::config::enable_tcmalloc_hook) {
+        init_hook();
+    }
+#endif
+
+    _query_pool_mem_tracker =
+            std::make_shared<MemTrackerLimiter>(-1, "QueryPool", _process_mem_tracker);
+    _load_pool_mem_tracker =
+            std::make_shared<MemTrackerLimiter>(-1, "LoadPool", _process_mem_tracker);
+
     LOG(INFO) << "Using global memory limit: "
               << PrettyPrinter::print(global_memory_limit_bytes, TUnit::BYTES)
               << ", origin config value: " << config::mem_limit;
@@ -261,8 +287,28 @@ Status ExecEnv::_init_mem_tracker() {
     RETURN_IF_ERROR(_disk_io_mgr->init(_mem_tracker));
     RETURN_IF_ERROR(_tmp_file_mgr->init());
 
-    // TODO(zc): The current memory usage configuration is a bit confusing,
-    // we need to sort out the use of memory
+    // 5. init chunk allocator
+    if (!BitUtil::IsPowerOf2(config::min_chunk_reserved_bytes)) {
+        ss << "Config min_chunk_reserved_bytes must be a power-of-two: "
+           << config::min_chunk_reserved_bytes;
+        return Status::InternalError(ss.str());
+    }
+
+    int64_t chunk_reserved_bytes_limit =
+            ParseUtil::parse_mem_spec(config::chunk_reserved_bytes_limit, global_memory_limit_bytes,
+                                      MemInfo::physical_mem(), &is_percent);
+    if (chunk_reserved_bytes_limit <= 0) {
+        ss << "Invalid config chunk_reserved_bytes_limit value, must be a percentage or "
+              "positive bytes value or percentage: "
+           << config::chunk_reserved_bytes_limit;
+        return Status::InternalError(ss.str());
+    }
+    chunk_reserved_bytes_limit =
+            BitUtil::RoundDown(chunk_reserved_bytes_limit, config::min_chunk_reserved_bytes);
+    ChunkAllocator::init_instance(chunk_reserved_bytes_limit);
+    LOG(INFO) << "Chunk allocator memory limit: "
+              << PrettyPrinter::print(chunk_reserved_bytes_limit, TUnit::BYTES)
+              << ", origin config value: " << config::chunk_reserved_bytes_limit;
     return Status::OK();
 }
 
@@ -326,6 +372,7 @@ void ExecEnv::_destroy() {
     SAFE_DELETE(_result_queue_mgr);
     SAFE_DELETE(_stream_mgr);
     SAFE_DELETE(_stream_load_executor);
+    SAFE_DELETE(_task_pool_mem_tracker_registry);
     SAFE_DELETE(_routine_load_task_executor);
     SAFE_DELETE(_external_scan_context_mgr);
     SAFE_DELETE(_heartbeat_flags);
diff --git a/be/src/runtime/fragment_mgr.cpp b/be/src/runtime/fragment_mgr.cpp
index 93bed66116..e5d6a7176e 100644
--- a/be/src/runtime/fragment_mgr.cpp
+++ b/be/src/runtime/fragment_mgr.cpp
@@ -39,6 +39,7 @@
 #include "runtime/descriptors.h"
 #include "runtime/exec_env.h"
 #include "runtime/plan_fragment_executor.h"
+#include "runtime/thread_context.h"
 #include "runtime/runtime_filter_mgr.h"
 #include "runtime/stream_load/load_stream_mgr.h"
 #include "runtime/stream_load/stream_load_context.h"
@@ -249,6 +250,9 @@ Status FragmentExecState::execute() {
 
 Status FragmentExecState::cancel_before_execute() {
     // set status as 'abort', cuz cancel() won't effect the status arg of DataSink::close().
+#ifndef BE_TEST
+    SCOPED_ATTACH_TASK(executor()->runtime_state());
+#endif
     _executor.set_abort();
     _executor.cancel();
     if (_pipe != nullptr) {
@@ -466,6 +470,9 @@ FragmentMgr::~FragmentMgr() {
 static void empty_function(PlanFragmentExecutor* exec) {}
 
 void FragmentMgr::_exec_actual(std::shared_ptr<FragmentExecState> exec_state, FinishCallback cb) {
+#ifndef BE_TEST
+    SCOPED_ATTACH_TASK(exec_state->executor()->runtime_state());
+#endif
     TAG(LOG(INFO))
             .log("PlanFragmentExecutor::_exec_actual")
             .query_id(exec_state->query_id())
diff --git a/be/src/runtime/load_channel_mgr.cpp b/be/src/runtime/load_channel_mgr.cpp
index a7beae3200..98ef8c724d 100644
--- a/be/src/runtime/load_channel_mgr.cpp
+++ b/be/src/runtime/load_channel_mgr.cpp
@@ -71,7 +71,6 @@ LoadChannelMgr::LoadChannelMgr() : _stop_background_threads_latch(1) {
         std::lock_guard<std::mutex> l(_lock);
         return _load_channels.size();
     });
-    _last_success_channel = new_lru_cache("LastestSuccessChannelCache", 1024, _mem_tracker);
 }
 
 LoadChannelMgr::~LoadChannelMgr() {
@@ -90,6 +89,7 @@ Status LoadChannelMgr::init(int64_t process_mem_limit) {
     REGISTER_HOOK_METRIC(load_mem_consumption, [this]() {
         return _mem_tracker->consumption();
     });
+    _last_success_channel = new_lru_cache("LastestSuccessChannelCache", 1024);
     RETURN_IF_ERROR(_start_bg_worker());
     return Status::OK();
 }
diff --git a/be/src/runtime/memory/chunk_allocator.cpp b/be/src/runtime/memory/chunk_allocator.cpp
index cbc2462953..9d5cbfd592 100644
--- a/be/src/runtime/memory/chunk_allocator.cpp
+++ b/be/src/runtime/memory/chunk_allocator.cpp
@@ -25,6 +25,7 @@
 #include "runtime/memory/chunk.h"
 #include "runtime/memory/system_allocator.h"
 #include "util/bit_util.h"
+#include "runtime/thread_context.h"
 #include "util/cpu_info.h"
 #include "util/doris_metrics.h"
 #include "util/runtime_profile.h"
@@ -114,6 +115,7 @@ ChunkAllocator::ChunkAllocator(size_t reserve_limit)
         : _reserve_bytes_limit(reserve_limit),
           _reserved_bytes(0),
           _arenas(CpuInfo::get_max_num_cores()) {
+    _mem_tracker = std::make_unique<MemTrackerLimiter>(-1, "ChunkAllocator");
     for (int i = 0; i < _arenas.size(); ++i) {
         _arenas[i].reset(new ChunkArena());
     }
@@ -138,6 +140,8 @@ bool ChunkAllocator::allocate(size_t size, Chunk* chunk) {
         DCHECK_GE(_reserved_bytes, 0);
         _reserved_bytes.fetch_sub(size);
         chunk_pool_local_core_alloc_count->increment(1);
+        // transfer the memory ownership of allocate from ChunkAllocator::tracker to the tls tracker.
+        THREAD_MEM_TRACKER_TRANSFER_FROM(size, _mem_tracker.get());
         return true;
     }
     if (_reserved_bytes > size) {
@@ -150,6 +154,8 @@ bool ChunkAllocator::allocate(size_t size, Chunk* chunk) {
                 chunk_pool_other_core_alloc_count->increment(1);
                 // reset chunk's core_id to other
                 chunk->core_id = core_id % _arenas.size();
+                // transfer the memory ownership of allocate from ChunkAllocator::tracker to the tls tracker.
+                THREAD_MEM_TRACKER_TRANSFER_FROM(size, _mem_tracker.get());
                 return true;
             }
         }
@@ -190,6 +196,8 @@ void ChunkAllocator::free(const Chunk& chunk) {
         }
     } while (!_reserved_bytes.compare_exchange_weak(old_reserved_bytes, new_reserved_bytes));
 
+    // The chunk's memory ownership is transferred from tls tracker to ChunkAllocator.
+    THREAD_MEM_TRACKER_TRANSFER_TO(chunk.size, _mem_tracker.get());
     _arenas[chunk.core_id]->push_free_chunk(chunk.data, chunk.size);
 }
 
diff --git a/be/src/runtime/memory/chunk_allocator.h b/be/src/runtime/memory/chunk_allocator.h
index cfdcb0bb1f..48a1ad1a42 100644
--- a/be/src/runtime/memory/chunk_allocator.h
+++ b/be/src/runtime/memory/chunk_allocator.h
@@ -28,6 +28,7 @@ namespace doris {
 struct Chunk;
 class ChunkArena;
 class MetricEntity;
+class MemTrackerLimiter;
 
 // Used to allocate memory with power-of-two length.
 // This Allocator allocate memory from system and cache free chunks for
@@ -79,6 +80,8 @@ private:
     std::vector<std::unique_ptr<ChunkArena>> _arenas;
 
     std::shared_ptr<MetricEntity> _chunk_allocator_metric_entity;
+
+    std::unique_ptr<MemTrackerLimiter> _mem_tracker;
 };
 
 } // namespace doris
diff --git a/be/src/runtime/memory/mem_tracker.cpp b/be/src/runtime/memory/mem_tracker.cpp
new file mode 100644
index 0000000000..dda2c43102
--- /dev/null
+++ b/be/src/runtime/memory/mem_tracker.cpp
@@ -0,0 +1,122 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+// This file is copied from
+// https://github.com/apache/impala/blob/branch-2.9.0/be/src/runtime/mem-tracker.cpp
+// and modified by Doris
+
+#include "runtime/memory/mem_tracker.h"
+
+#include <fmt/format.h>
+
+#include "runtime/thread_context.h"
+#include "util/pretty_printer.h"
+#include "util/string_util.h"
+#include "util/time.h"
+
+namespace doris {
+
+const std::string NewMemTracker::COUNTER_NAME = "PeakMemoryUsage";
+
+struct TrackerGroup {
+    std::list<NewMemTracker*> trackers;
+    std::mutex group_lock;
+};
+
+// Save all MemTrackers in use to maintain the weak relationship between NewMemTracker and MemTrackerLimiter.
+// When MemTrackerLimiter prints statistics, all NewMemTracker statistics with weak relationship will be printed together.
+// Each group corresponds to several MemTrackerLimiters and has a lock.
+// Multiple groups are used to reduce the impact of locks.
+static std::vector<TrackerGroup> mem_tracker_pool(1000);
+
+NewMemTracker::NewMemTracker(const std::string& label, RuntimeProfile* profile, bool is_limiter) {
+    if (profile == nullptr) {
+        _consumption = std::make_shared<RuntimeProfile::HighWaterMarkCounter>(TUnit::BYTES);
+    } else {
+        // By default, memory consumption is tracked via calls to consume()/release(), either to
+        // the tracker itself or to one of its descendents. Alternatively, a consumption metric
+        // can be specified, and then the metric's value is used as the consumption rather than
+        // the tally maintained by consume() and release(). A tcmalloc metric is used to track
+        // process memory consumption, since the process memory usage may be higher than the
+        // computed total memory (tcmalloc does not release deallocated memory immediately).
+        // Other consumption metrics are used in trackers below the process level to account
+        // for memory (such as free buffer pool buffers) that is not tracked by consume() and
+        // release().
+        _consumption = profile->AddSharedHighWaterMarkCounter(COUNTER_NAME, TUnit::BYTES);
+    }
+
+    _is_limiter = is_limiter;
+    if (!_is_limiter) {
+        if (thread_context()->_thread_mem_tracker_mgr->limiter_mem_tracker()) {
+            _label = fmt::format(
+                    "{} | {}", label,
+                    thread_context()->_thread_mem_tracker_mgr->limiter_mem_tracker()->label());
+        } else {
+            _label = label + " | ";
+        }
+
+        _bind_group_num =
+                thread_context()->_thread_mem_tracker_mgr->limiter_mem_tracker()->group_num();
+        {
+            std::lock_guard<std::mutex> l(mem_tracker_pool[_bind_group_num].group_lock);
+            _tracker_group_it = mem_tracker_pool[_bind_group_num].trackers.insert(
+                    mem_tracker_pool[_bind_group_num].trackers.end(), this);
+        }
+    } else {
+        _label = label;
+    }
+}
+
+NewMemTracker::~NewMemTracker() {
+    if (!_is_limiter) {
+        std::lock_guard<std::mutex> l(mem_tracker_pool[_bind_group_num].group_lock);
+        if (_tracker_group_it != mem_tracker_pool[_bind_group_num].trackers.end()) {
+            mem_tracker_pool[_bind_group_num].trackers.erase(_tracker_group_it);
+            _tracker_group_it = mem_tracker_pool[_bind_group_num].trackers.end();
+        }
+    }
+}
+
+NewMemTracker::Snapshot NewMemTracker::make_snapshot(size_t level) const {
+    Snapshot snapshot;
+    snapshot.label = split(_label, " | ")[0];
+    snapshot.parent = split(_label, " | ")[1];
+    snapshot.level = level;
+    snapshot.limit = -1;
+    snapshot.cur_consumption = _consumption->current_value();
+    snapshot.peak_consumption = _consumption->value();
+    snapshot.child_count = 0;
+    return snapshot;
+}
+
+void NewMemTracker::make_group_snapshot(std::vector<NewMemTracker::Snapshot>* snapshots, size_t level,
+                                     int64_t group_num, std::string related_label) {
+    std::lock_guard<std::mutex> l(mem_tracker_pool[group_num].group_lock);
+    for (auto tracker : mem_tracker_pool[group_num].trackers) {
+        if (split(tracker->label(), " | ")[1] == related_label) {
+            snapshots->push_back(tracker->make_snapshot(level));
+        }
+    }
+}
+
+std::string NewMemTracker::log_usage(NewMemTracker::Snapshot snapshot) {
+    return fmt::format("NewMemTracker Label={}, Parent Label={}, Used={}, Peak={}", snapshot.label,
+                       snapshot.parent,
+                       PrettyPrinter::print(snapshot.cur_consumption, TUnit::BYTES),
+                       PrettyPrinter::print(snapshot.peak_consumption, TUnit::BYTES));
+}
+
+} // namespace doris
\ No newline at end of file
diff --git a/be/src/runtime/memory/mem_tracker.h b/be/src/runtime/memory/mem_tracker.h
new file mode 100644
index 0000000000..41d2fe4d1c
--- /dev/null
+++ b/be/src/runtime/memory/mem_tracker.h
@@ -0,0 +1,116 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+// This file is copied from
+// https://github.com/apache/impala/blob/branch-2.9.0/be/src/runtime/mem-tracker.h
+// and modified by Doris
+#pragma once
+
+#include "util/runtime_profile.h"
+
+namespace doris {
+
+// Used to track memory usage.
+//
+// NewMemTracker can be consumed manually by consume()/release(), or put into SCOPED_CONSUME_MEM_TRACKER,
+// which will automatically track all memory usage of the code segment where it is located.
+//
+// This class is thread-safe.
+class NewMemTracker {
+public:
+    struct Snapshot {
+        std::string label;
+        // For NewMemTracker, it is only weakly related to parent through label, ensuring NewMemTracker Independence.
+        // For MemTrackerLimiter, it is strongly related to parent and saves pointer objects to each other.
+        std::string parent = "";
+        size_t level = 0;
+        int64_t limit = 0;
+        int64_t cur_consumption = 0;
+        int64_t peak_consumption = 0;
+        size_t child_count = 0;
+    };
+
+    // Creates and adds the tracker to the mem_tracker_pool.
+    NewMemTracker(const std::string& label = std::string(), RuntimeProfile* profile = nullptr,
+               bool is_limiter = false);
+
+    ~NewMemTracker();
+
+public:
+    const std::string& label() const { return _label; }
+    // Returns the memory consumed in bytes.
+    int64_t consumption() const { return _consumption->current_value(); }
+    int64_t peak_consumption() const { return _consumption->value(); }
+
+    void consume(int64_t bytes);
+    void release(int64_t bytes) { consume(-bytes); }
+    // Transfer 'bytes' of consumption from this tracker to 'dst'.
+    void transfer_to(NewMemTracker* dst, int64_t bytes);
+
+public:
+    bool limit_exceeded(int64_t limit) const { return limit >= 0 && limit < consumption(); }
+    // Return true, no exceeded limit
+    bool check_limit(int64_t limit, int64_t bytes) const {
+        return limit >= 0 && limit > consumption() + bytes;
+    }
+
+    Snapshot make_snapshot(size_t level) const;
+    // Specify group_num from mem_tracker_pool to generate snapshot, requiring tracker.label to be related
+    // with parameter related_label
+    static void make_group_snapshot(std::vector<Snapshot>* snapshots, size_t level,
+                                    int64_t group_num, std::string related_label);
+    static std::string log_usage(NewMemTracker::Snapshot snapshot);
+
+    std::string debug_string() {
+        std::stringstream msg;
+        msg << "label: " << _label << "; "
+            << "consumption: " << consumption() << "; "
+            << "peak_consumption: " << peak_consumption() << "; ";
+        return msg.str();
+    }
+
+    static const std::string COUNTER_NAME;
+
+protected:
+    // label used in the make snapshot, not guaranteed unique.
+    std::string _label;
+
+    std::shared_ptr<RuntimeProfile::HighWaterMarkCounter> _consumption; // in bytes
+
+    // Tracker is located in group num in mem_tracker_pool
+    int64_t _bind_group_num;
+
+    // Whether is a MemTrackerLimiter
+    bool _is_limiter;
+
+    // Iterator into mem_tracker_pool for this object. Stored to have O(1) remove.
+    std::list<NewMemTracker*>::iterator _tracker_group_it;
+};
+
+inline void NewMemTracker::consume(int64_t bytes) {
+    if (bytes == 0) {
+        return;
+    } else {
+        _consumption->add(bytes);
+    }
+}
+
+inline void NewMemTracker::transfer_to(NewMemTracker* dst, int64_t bytes) {
+    release(bytes);
+    dst->consume(bytes);
+}
+
+} // namespace doris
\ No newline at end of file
diff --git a/be/src/runtime/memory/mem_tracker_limiter.cpp b/be/src/runtime/memory/mem_tracker_limiter.cpp
new file mode 100644
index 0000000000..722495aee7
--- /dev/null
+++ b/be/src/runtime/memory/mem_tracker_limiter.cpp
@@ -0,0 +1,264 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "runtime/memory/mem_tracker_limiter.h"
+
+#include <fmt/format.h>
+
+#include <boost/stacktrace.hpp>
+
+#include "gutil/once.h"
+#include "runtime/runtime_state.h"
+#include "runtime/thread_context.h"
+#include "service/backend_options.h"
+#include "util/pretty_printer.h"
+#include "util/string_util.h"
+
+namespace doris {
+
+MemTrackerLimiter::MemTrackerLimiter(int64_t byte_limit, const std::string& label,
+                                     const std::shared_ptr<MemTrackerLimiter>& parent,
+                                     RuntimeProfile* profile)
+        : NewMemTracker(label, profile, true) {
+    DCHECK_GE(byte_limit, -1);
+    _limit = byte_limit;
+    _group_num = GetCurrentTimeMicros() % 1000;
+    _parent = parent ? parent : thread_context()->_thread_mem_tracker_mgr->limiter_mem_tracker();
+    DCHECK(_parent || label == "Process");
+
+    // Walks the MemTrackerLimiter hierarchy and populates _all_ancestors and _limited_ancestors
+    MemTrackerLimiter* tracker = this;
+    while (tracker != nullptr) {
+        _all_ancestors.push_back(tracker);
+        if (tracker->has_limit()) _limited_ancestors.push_back(tracker);
+        tracker = tracker->_parent.get();
+    }
+    DCHECK_GT(_all_ancestors.size(), 0);
+    DCHECK_EQ(_all_ancestors[0], this);
+    if (_parent) {
+        std::lock_guard<std::mutex> l(_parent->_child_tracker_limiter_lock);
+        _child_tracker_it = _parent->_child_tracker_limiters.insert(
+                _parent->_child_tracker_limiters.end(), this);
+        _had_child_count++;
+    }
+}
+
+MemTrackerLimiter::~MemTrackerLimiter() {
+    // TCMalloc hook will be triggered during destructor memtracker, may cause crash.
+    if (_label == "Process") doris::thread_context_ptr._init = false;
+    DCHECK(remain_child_count() == 0 || _label == "Process");
+    if (_parent) {
+        std::lock_guard<std::mutex> l(_parent->_child_tracker_limiter_lock);
+        if (_child_tracker_it != _parent->_child_tracker_limiters.end()) {
+            _parent->_child_tracker_limiters.erase(_child_tracker_it);
+            _child_tracker_it = _parent->_child_tracker_limiters.end();
+        }
+    }
+}
+
+NewMemTracker::Snapshot MemTrackerLimiter::make_snapshot(size_t level) const {
+    Snapshot snapshot;
+    snapshot.label = _label;
+    snapshot.parent = _parent != nullptr ? _parent->label() : "Root";
+    snapshot.level = level;
+    snapshot.limit = _limit;
+    snapshot.cur_consumption = _consumption->current_value();
+    snapshot.peak_consumption = _consumption->value();
+    snapshot.child_count = remain_child_count();
+    return snapshot;
+}
+
+void MemTrackerLimiter::make_snapshot(std::vector<NewMemTracker::Snapshot>* snapshots,
+                                      size_t cur_level, size_t upper_level) const {
+    Snapshot snapshot = MemTrackerLimiter::make_snapshot(cur_level);
+    (*snapshots).emplace_back(snapshot);
+    if (cur_level < upper_level) {
+        {
+            std::lock_guard<std::mutex> l(_child_tracker_limiter_lock);
+            for (const auto& child : _child_tracker_limiters) {
+                child->make_snapshot(snapshots, cur_level + 1, upper_level);
+            }
+        }
+        NewMemTracker::make_group_snapshot(snapshots, cur_level + 1, _group_num, _label);
+    }
+}
+
+int64_t MemTrackerLimiter::spare_capacity() const {
+    int64_t result = std::numeric_limits<int64_t>::max();
+    for (const auto& tracker : _limited_ancestors) {
+        int64_t mem_left = tracker->limit() - tracker->consumption();
+        result = std::min(result, mem_left);
+    }
+    return result;
+}
+
+int64_t MemTrackerLimiter::get_lowest_limit() const {
+    if (_limited_ancestors.empty()) return -1;
+    int64_t min_limit = std::numeric_limits<int64_t>::max();
+    for (const auto& tracker : _limited_ancestors) {
+        DCHECK(tracker->has_limit());
+        min_limit = std::min(min_limit, tracker->limit());
+    }
+    return min_limit;
+}
+
+bool MemTrackerLimiter::gc_memory(int64_t max_consumption) {
+    if (max_consumption < 0) return true;
+    std::lock_guard<std::mutex> l(_gc_lock);
+    int64_t pre_gc_consumption = consumption();
+    // Check if someone gc'd before us
+    if (pre_gc_consumption < max_consumption) return false;
+
+    int64_t curr_consumption = pre_gc_consumption;
+    // Free some extra memory to avoid frequent GC, 4M is an empirical value, maybe it will be tested later.
+    const int64_t EXTRA_BYTES_TO_FREE = 4L * 1024L * 1024L * 1024L;
+    // Try to free up some memory
+    for (int i = 0; i < _gc_functions.size(); ++i) {
+        // Try to free up the amount we are over plus some extra so that we don't have to
+        // immediately GC again. Don't free all the memory since that can be unnecessarily
+        // expensive.
+        int64_t bytes_to_free = curr_consumption - max_consumption + EXTRA_BYTES_TO_FREE;
+        _gc_functions[i](bytes_to_free);
+        curr_consumption = consumption();
+        if (max_consumption - curr_consumption <= EXTRA_BYTES_TO_FREE) break;
+    }
+
+    return curr_consumption > max_consumption;
+}
+
+Status MemTrackerLimiter::try_gc_memory(int64_t bytes) {
+    if (UNLIKELY(gc_memory(_limit - bytes))) {
+        return Status::MemoryLimitExceeded(
+                fmt::format("label={}, limit={}, used={}, failed consume size={}", label(), _limit, _consumption->current_value(), bytes));
+    }
+    VLOG_NOTICE << "GC succeeded, TryConsume bytes=" << bytes
+                << " consumption=" << _consumption->current_value() << " limit=" << _limit;
+    return Status::OK();
+}
+
+// Calling this on the query tracker results in output like:
+//
+//  Query(4a4c81fedaed337d:4acadfda00000000) Limit=10.00 GB Total=508.28 MB Peak=508.45 MB
+//    Fragment 4a4c81fedaed337d:4acadfda00000000: Total=8.00 KB Peak=8.00 KB
+//      EXCHANGE_NODE (id=4): Total=0 Peak=0
+//      DataStreamRecvr: Total=0 Peak=0
+//    Block Manager: Limit=6.68 GB Total=394.00 MB Peak=394.00 MB
+//    Fragment 4a4c81fedaed337d:4acadfda00000006: Total=233.72 MB Peak=242.24 MB
+//      AGGREGATION_NODE (id=1): Total=139.21 MB Peak=139.84 MB
+//      HDFS_SCAN_NODE (id=0): Total=93.94 MB Peak=102.24 MB
+//      DataStreamSender (dst_id=2): Total=45.99 KB Peak=85.99 KB
+//    Fragment 4a4c81fedaed337d:4acadfda00000003: Total=274.55 MB Peak=274.62 MB
+//      AGGREGATION_NODE (id=3): Total=274.50 MB Peak=274.50 MB
+//      EXCHANGE_NODE (id=2): Total=0 Peak=0
+//      DataStreamRecvr: Total=45.91 KB Peak=684.07 KB
+//      DataStreamSender (dst_id=4): Total=680.00 B Peak=680.00 B
+//
+// If 'reservation_metrics_' are set, we ge a more granular breakdown:
+//   TrackerName: Limit=5.00 MB Reservation=5.00 MB OtherMemory=1.04 MB
+//                Total=6.04 MB Peak=6.45 MB
+//
+std::string MemTrackerLimiter::log_usage(int max_recursive_depth, int64_t* logged_consumption) {
+    int64_t curr_consumption = consumption();
+    int64_t peak_consumption = _consumption->value();
+    if (logged_consumption != nullptr) *logged_consumption = curr_consumption;
+
+    std::string detail = "MemTrackerLimiter Label={}, Limit={}, Used={}, Peak={}, Exceeded={}";
+    detail = fmt::format(detail, _label, PrettyPrinter::print(_limit, TUnit::BYTES),
+                         PrettyPrinter::print(curr_consumption, TUnit::BYTES),
+                         PrettyPrinter::print(peak_consumption, TUnit::BYTES),
+                         limit_exceeded() ? "true" : "false");
+
+    // This call does not need the children, so return early.
+    if (max_recursive_depth == 0) return detail;
+
+    // Recurse and get information about the children
+    int64_t child_consumption;
+    std::string child_trackers_usage;
+    {
+        std::lock_guard<std::mutex> l(_child_tracker_limiter_lock);
+        child_trackers_usage =
+                log_usage(max_recursive_depth - 1, _child_tracker_limiters, &child_consumption);
+    }
+    std::vector<NewMemTracker::Snapshot> snapshots;
+    NewMemTracker::make_group_snapshot(&snapshots, 0, _group_num, _label);
+    for (const auto& snapshot : snapshots) {
+        child_trackers_usage += NewMemTracker::log_usage(snapshot);
+    }
+    if (!child_trackers_usage.empty()) detail += "\n" + child_trackers_usage;
+    return detail;
+}
+
+std::string MemTrackerLimiter::log_usage(int max_recursive_depth,
+                                         const std::list<MemTrackerLimiter*>& trackers,
+                                         int64_t* logged_consumption) {
+    *logged_consumption = 0;
+    std::vector<std::string> usage_strings;
+    for (const auto& tracker : trackers) {
+        int64_t tracker_consumption;
+        std::string usage_string = tracker->log_usage(max_recursive_depth, &tracker_consumption);
+        if (!usage_string.empty()) usage_strings.push_back(usage_string);
+        *logged_consumption += tracker_consumption;
+    }
+    return join(usage_strings, "\n");
+}
+
+Status MemTrackerLimiter::mem_limit_exceeded(const std::string& msg, int64_t failed_consume_size, Status failed_try_consume_rt, const TUniqueId& fragment_instance_id) {
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
+    std::string detail;
+    if (!failed_try_consume_rt) {
+        DCHECK(failed_try_consume_rt.is_mem_limit_exceeded());
+        detail += "in {} mem tracker consume log=<{}>.";
+        // failed_try_consume_rt.to_string() starts with `Memory exceed limit: `
+        detail = fmt::format(detail, msg, failed_try_consume_rt.to_string());
+    } else {
+        detail += "in {} mem tracker consume log=<label={}, limit={}, used={}, failed consume size={}>.";
+        detail = fmt::format(detail, msg, _label, _consumption->current_value(), _limit,
+                             PrettyPrinter::print(failed_consume_size, TUnit::BYTES));
+    }
+    detail += " fragment={}, backend={} free memory left={}.";
+    detail = fmt::format(
+            detail, print_id(fragment_instance_id), 
+            BackendOptions::get_localhost(),
+            PrettyPrinter::print(ExecEnv::GetInstance()->new_process_mem_tracker()->spare_capacity(),
+                                 TUnit::BYTES));
+    detail += " If this is a query, can change the limit by session variable exec_mem_limit.";
+    Status status = Status::MemoryLimitExceeded(detail);
+
+    detail += "\n" + boost::stacktrace::to_string(boost::stacktrace::stacktrace());
+    // only print the tracker log_usage in be log.
+    if (ExecEnv::GetInstance()->new_process_mem_tracker()->spare_capacity() < failed_consume_size) {
+        // Dumping the process NewMemTracker is expensive. Limiting the recursive depth to two
+        // levels limits the level of detail to a one-line summary for each query NewMemTracker.
+        detail += "\n" + ExecEnv::GetInstance()->new_process_mem_tracker()->log_usage(2);
+    } else {
+        detail += "\n" + log_usage();
+    }
+
+    LOG(WARNING) << detail;
+    return status;
+}
+
+Status MemTrackerLimiter::mem_limit_exceeded(RuntimeState* state, const std::string& msg,
+                              int64_t failed_alloc_size,
+                              Status failed_try_consume_rt) {
+    Status rt = mem_limit_exceeded(msg, failed_alloc_size, failed_try_consume_rt,
+                                    state->fragment_instance_id());
+    state->log_error(rt.to_string());
+    return rt;
+}
+
+} // namespace doris
diff --git a/be/src/runtime/memory/mem_tracker_limiter.h b/be/src/runtime/memory/mem_tracker_limiter.h
new file mode 100644
index 0000000000..104a1c20ca
--- /dev/null
+++ b/be/src/runtime/memory/mem_tracker_limiter.h
@@ -0,0 +1,287 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <atomic>
+
+#include "common/config.h"
+#include "runtime/exec_env.h"
+#include "runtime/memory/mem_tracker.h"
+#include "util/mem_info.h"
+#include "util/perf_counters.h"
+
+namespace doris {
+
+class RuntimeState;
+
+// Track and limit the memory usage of process and query.
+// Contains an limit, arranged into a tree structure, the consumption also tracked by its ancestors.
+//
+// Automatically track every once malloc/free of the system memory allocator (Currently, based on TCMlloc hook).
+// Put Query MemTrackerLimiter into SCOPED_ATTACH_TASK when the thread starts,all memory used by this thread
+// will be recorded on this Query, otherwise it will be recorded in Process Tracker by default.
+//
+// We use a five-level hierarchy of mem trackers: process, query pool, query, instance, node.
+// The first four layers are MemTrackerLimiter with limit, and the fifth layer is NewMemTracker without limit.
+// Specific parts of the fragment (exec nodes, sinks, etc) will add a fifth level when they are initialized.
+class MemTrackerLimiter final : public NewMemTracker {
+public:
+    // Creates and adds the tracker limiter to the tree
+    MemTrackerLimiter(
+            int64_t byte_limit = -1, const std::string& label = std::string(),
+            const std::shared_ptr<MemTrackerLimiter>& parent = std::shared_ptr<MemTrackerLimiter>(),
+            RuntimeProfile* profile = nullptr);
+
+    // If the final consumption is not as expected, this usually means that the same memory is calling
+    // consume and release on different trackers. If the two trackers have a parent-child relationship,
+    // the parent tracker consumption is correct, and the child tracker is wrong; if the two trackers have
+    // no parent-child relationship, the two tracker consumptions are wrong.
+    ~MemTrackerLimiter();
+
+    std::shared_ptr<MemTrackerLimiter> parent() const { return _parent; }
+
+    size_t remain_child_count() const { return _child_tracker_limiters.size(); }
+    size_t had_child_count() const { return _had_child_count; }
+
+    Snapshot make_snapshot(size_t level) const;
+    // Returns a list of all the valid tracker snapshots.
+    void make_snapshot(std::vector<NewMemTracker::Snapshot>* snapshots, size_t cur_level,
+                       size_t upper_level) const;
+
+public:
+    Status check_sys_mem_info(int64_t bytes) {
+        // Limit process memory usage using the actual physical memory of the process in `/proc/self/status`.
+        // This is independent of the consumption value of the mem tracker, which counts the virtual memory
+        // of the process malloc.
+        // for fast, expect MemInfo::initialized() to be true.
+        if (PerfCounters::get_vm_rss() + bytes >= MemInfo::mem_limit()) {
+            return Status::MemoryLimitExceeded(fmt::format(
+                    "{}: TryConsume failed, bytes={} process whole consumption={}  mem limit={}",
+                    _label, bytes, MemInfo::current_mem(), MemInfo::mem_limit()));
+        }
+        return Status::OK();
+    }
+
+    int64_t group_num() const { return _group_num; }
+    bool has_limit() const { return _limit >= 0; }
+    int64_t limit() const { return _limit; }
+    void update_limit(int64_t limit) {
+        DCHECK(has_limit());
+        _limit = limit;
+    }
+    bool limit_exceeded() const { return _limit >= 0 && _limit < consumption(); }
+
+    // Returns true if a valid limit of this tracker limiter or one of its ancestors is exceeded.
+    bool any_limit_exceeded() const {
+        for (const auto& tracker : _limited_ancestors) {
+            if (tracker->limit_exceeded()) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    Status check_limit(int64_t bytes);
+
+    // Returns the maximum consumption that can be made without exceeding the limit on
+    // this tracker limiter or any of its parents. Returns int64_t::max() if there are no
+    // limits and a negative value if any limit is already exceeded.
+    int64_t spare_capacity() const;
+
+    // Returns the lowest limit for this tracker limiter and its ancestors. Returns -1 if there is no limit.
+    int64_t get_lowest_limit() const;
+
+    typedef std::function<void(int64_t bytes_to_free)> GcFunction;
+    // Add a function 'f' to be called if the limit is reached, if none of the other
+    // previously-added GC functions were successful at freeing up enough memory.
+    // 'f' does not need to be thread-safe as long as it is added to only one tracker limiter.
+    // Note that 'f' must be valid for the lifetime of this tracker limiter.
+    void add_gc_function(GcFunction f) { _gc_functions.push_back(f); }
+
+    // TODO Should be managed in a separate process_mem_mgr, not in NewMemTracker
+    // If consumption is higher than max_consumption, attempts to free memory by calling
+    // any added GC functions.  Returns true if max_consumption is still exceeded. Takes gc_lock.
+    // Note: If the cache of segment/chunk is released due to insufficient query memory at a certain moment,
+    // the performance of subsequent queries may be degraded, so the use of gc function should be careful enough.
+    bool gc_memory(int64_t max_consumption);
+    Status try_gc_memory(int64_t bytes);
+
+public:
+    // It is used for revise mem tracker consumption.
+    // If the location of memory alloc and free is different, the consumption value of mem tracker will be inaccurate.
+    // But the consumption value of the process mem tracker is not affecte
+    void consumption_revise(int64_t bytes) {
+        DCHECK(_label != "Process");
+        _consumption->add(bytes);
+    }
+
+    // Logs the usage of this tracker limiter and optionally its children (recursively).
+    // If 'logged_consumption' is non-nullptr, sets the consumption value logged.
+    // 'max_recursive_depth' specifies the maximum number of levels of children
+    // to include in the dump. If it is zero, then no children are dumped.
+    // Limiting the recursive depth reduces the cost of dumping, particularly
+    // for the process tracker limiter.
+    std::string log_usage(int max_recursive_depth = INT_MAX, int64_t* logged_consumption = nullptr);
+
+    // Log the memory usage when memory limit is exceeded and return a status object with
+    // msg of the allocation which caused the limit to be exceeded.
+    // If 'failed_allocation_size' is greater than zero, logs the allocation size. If
+    // 'failed_allocation_size' is zero, nothing about the allocation size is logged.
+    // If 'state' is non-nullptr, logs the error to 'state'.
+    Status mem_limit_exceeded(const std::string& msg, int64_t failed_consume_size,
+                              Status failed_try_consume_rt,
+                              const TUniqueId& fragment_instance_id = TUniqueId());
+    Status mem_limit_exceeded(RuntimeState* state, const std::string& msg = std::string(),
+                              int64_t failed_consume_size = -1,
+                              Status failed_try_consume_rt = Status::OK());
+
+    std::string debug_string() {
+        std::stringstream msg;
+        msg << "limit: " << _limit << "; "
+            << "consumption: " << _consumption->current_value() << "; "
+            << "label: " << _label << "; "
+            << "all ancestor size: " << _all_ancestors.size() - 1 << "; "
+            << "limited ancestor size: " << _limited_ancestors.size() - 1 << "; ";
+        return msg.str();
+    }
+
+private:
+    // The following func, for automatic memory tracking and limiting based on system memory allocation.
+    friend class ThreadMemTrackerMgr;
+
+    // Increases consumption of this tracker and its ancestors by 'bytes'.
+    void consume(int64_t bytes);
+
+    // Decreases consumption of this tracker and its ancestors by 'bytes'.
+    void release(int64_t bytes) { consume(-bytes); }
+
+    // Increases consumption of this tracker and its ancestors by 'bytes' only if
+    // they can all consume 'bytes' without exceeding limit. If limit would be exceed,
+    // no MemTrackerLimiters are updated. Returns true if the consumption was successfully updated.
+    WARN_UNUSED_RESULT
+    Status try_consume(int64_t bytes);
+
+    // Log consumption of all the trackers provided. Returns the sum of consumption in
+    // 'logged_consumption'. 'max_recursive_depth' specifies the maximum number of levels
+    // of children to include in the dump. If it is zero, then no children are dumped.
+    static std::string log_usage(int max_recursive_depth,
+                                 const std::list<MemTrackerLimiter*>& trackers,
+                                 int64_t* logged_consumption);
+
+private:
+    // Limit on memory consumption, in bytes. If limit_ == -1, there is no consumption limit. Used in log_usage。
+    int64_t _limit;
+
+    // Group number in NewMemTracker::mem_tracker_pool, generated by the timestamp.
+    int64_t _group_num;
+
+    std::shared_ptr<MemTrackerLimiter> _parent; // The parent of this tracker.
+
+    // this tracker limiter plus all of its ancestors
+    std::vector<MemTrackerLimiter*> _all_ancestors;
+    // _all_ancestors with valid limits
+    std::vector<MemTrackerLimiter*> _limited_ancestors;
+
+    // Child trackers of this tracker limiter. Used for error reporting and
+    // listing only (i.e. updating the consumption of a parent tracker limiter does not
+    // update that of its children).
+    mutable std::mutex _child_tracker_limiter_lock;
+    std::list<MemTrackerLimiter*> _child_tracker_limiters;
+    // Iterator into parent_->_child_tracker_limiters for this object. Stored to have O(1) remove.
+    std::list<MemTrackerLimiter*>::iterator _child_tracker_it;
+
+    // The number of child trackers that have been added.
+    std::atomic_size_t _had_child_count = 0;
+
+    // Lock to protect gc_memory(). This prevents many GCs from occurring at once.
+    std::mutex _gc_lock;
+    // Functions to call after the limit is reached to free memory.
+    // GcFunctions can be attached to a NewMemTracker in order to free up memory if the limit is
+    // reached. If limit_exceeded() is called and the limit is exceeded, it will first call
+    // the GcFunctions to try to free memory and recheck the limit. For example, the process
+    // tracker has a GcFunction that releases any unused memory still held by tcmalloc, so
+    // this will be called before the process limit is reported as exceeded. GcFunctions are
+    // called in the order they are added, so expensive functions should be added last.
+    // GcFunctions are called with a global lock held, so should be non-blocking and not
+    // call back into MemTrackers, except to release memory.
+    std::vector<GcFunction> _gc_functions;
+};
+
+inline void MemTrackerLimiter::consume(int64_t bytes) {
+    if (bytes == 0) {
+        return;
+    } else {
+        for (auto& tracker : _all_ancestors) {
+            tracker->_consumption->add(bytes);
+        }
+    }
+}
+
+inline Status MemTrackerLimiter::try_consume(int64_t bytes) {
+    if (bytes <= 0) {
+        release(-bytes);
+        return Status::OK();
+    }
+    RETURN_IF_ERROR(check_sys_mem_info(bytes));
+    int i;
+    // Walk the tracker tree top-down.
+    for (i = _all_ancestors.size() - 1; i >= 0; --i) {
+        MemTrackerLimiter* tracker = _all_ancestors[i];
+        if (tracker->limit() < 0) {
+            tracker->_consumption->add(bytes); // No limit at this tracker.
+        } else {
+            // If TryConsume fails, we can try to GC, but we may need to try several times if
+            // there are concurrent consumers because we don't take a lock before trying to
+            // update _consumption.
+            while (true) {
+                if (LIKELY(tracker->_consumption->try_add(bytes, tracker->limit()))) break;
+                Status st = tracker->try_gc_memory(bytes);
+                if (!st) {
+                    // Failed for this mem tracker. Roll back the ones that succeeded.
+                    for (int j = _all_ancestors.size() - 1; j > i; --j) {
+                        _all_ancestors[j]->_consumption->add(-bytes);
+                    }
+                    return st;
+                }
+            }
+        }
+    }
+    // Everyone succeeded, return.
+    DCHECK_EQ(i, -1);
+    return Status::OK();
+}
+
+inline Status MemTrackerLimiter::check_limit(int64_t bytes) {
+    if (bytes <= 0) return Status::OK();
+    RETURN_IF_ERROR(check_sys_mem_info(bytes));
+    int i;
+    // Walk the tracker tree top-down.
+    for (i = _all_ancestors.size() - 1; i >= 0; --i) {
+        MemTrackerLimiter* tracker = _all_ancestors[i];
+        if (tracker->limit() > 0) {
+            while (true) {
+                if (LIKELY(tracker->_consumption->current_value() + bytes < tracker->limit()))
+                    break;
+                RETURN_IF_ERROR(tracker->try_gc_memory(bytes));
+            }
+        }
+    }
+    return Status::OK();
+}
+
+} // namespace doris
diff --git a/be/src/runtime/memory/mem_tracker_task_pool.cpp b/be/src/runtime/memory/mem_tracker_task_pool.cpp
new file mode 100644
index 0000000000..3c775db5ec
--- /dev/null
+++ b/be/src/runtime/memory/mem_tracker_task_pool.cpp
@@ -0,0 +1,145 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "runtime/memory/mem_tracker_task_pool.h"
+
+#include "common/config.h"
+#include "runtime/exec_env.h"
+#include "util/pretty_printer.h"
+
+namespace doris {
+
+std::shared_ptr<MemTrackerLimiter> MemTrackerTaskPool::register_task_mem_tracker_impl(
+        const std::string& task_id, int64_t mem_limit, const std::string& label,
+        const std::shared_ptr<MemTrackerLimiter>& parent) {
+    DCHECK(!task_id.empty());
+    // First time this task_id registered, make a new object, otherwise do nothing.
+    // Combine new tracker and emplace into one operation to avoid the use of locks
+    // Name for task MemTrackers. '$0' is replaced with the task id.
+    std::shared_ptr<MemTrackerLimiter> tracker;
+    bool new_emplace = _task_mem_trackers.lazy_emplace_l(
+            task_id, [&](const std::shared_ptr<MemTrackerLimiter>& v) { tracker = v; },
+            [&](const auto& ctor) {
+                tracker = std::make_shared<MemTrackerLimiter>(mem_limit, label, parent);
+                ctor(task_id, tracker);
+            });
+    if (new_emplace) {
+        LOG(INFO) << "Register query/load memory tracker, query/load id: " << task_id
+                  << " limit: " << PrettyPrinter::print(mem_limit, TUnit::BYTES);
+    }
+    return tracker;
+}
+
+std::shared_ptr<MemTrackerLimiter> MemTrackerTaskPool::register_query_mem_tracker(
+        const std::string& query_id, int64_t mem_limit) {
+    return register_task_mem_tracker_impl(query_id, mem_limit,
+                                          fmt::format("Query#queryId={}", query_id),
+                                          ExecEnv::GetInstance()->query_pool_mem_tracker());
+}
+
+std::shared_ptr<MemTrackerLimiter> MemTrackerTaskPool::register_load_mem_tracker(
+        const std::string& load_id, int64_t mem_limit) {
+    // In load, the query id of the fragment is executed, which is the same as the load id of the load channel.
+    return register_task_mem_tracker_impl(load_id, mem_limit,
+                                          fmt::format("Load#queryId={}", load_id),
+                                          ExecEnv::GetInstance()->load_pool_mem_tracker());
+}
+
+std::shared_ptr<MemTrackerLimiter> MemTrackerTaskPool::get_task_mem_tracker(
+        const std::string& task_id) {
+    DCHECK(!task_id.empty());
+    std::shared_ptr<MemTrackerLimiter> tracker = nullptr;
+    // Avoid using locks to resolve erase conflicts
+    _task_mem_trackers.if_contains(
+            task_id, [&tracker](const std::shared_ptr<MemTrackerLimiter>& v) { tracker = v; });
+    return tracker;
+}
+
+void MemTrackerTaskPool::logout_task_mem_tracker() {
+    std::vector<std::string> expired_task_ids;
+    for (auto it = _task_mem_trackers.begin(); it != _task_mem_trackers.end(); it++) {
+        if (!it->second) {
+            // Unknown exception case with high concurrency, after _task_mem_trackers.erase,
+            // the key still exists in _task_mem_trackers. https://github.com/apache/incubator-doris/issues/10006
+            expired_task_ids.emplace_back(it->first);
+        } else if (it->second.use_count() == 1 && it->second->had_child_count() != 0) {
+            // No RuntimeState uses this task MemTrackerLimiter, it is only referenced by this map,
+            // and tracker was not created soon, delete it.
+            //
+            // If consumption is not equal to 0 before query mem tracker is destructed,
+            // there are two possibilities in theory.
+            // 1. A memory leak occurs.
+            // 2. memory consumed on query mem tracker, released on other trackers, and no manual transfer
+            //  between the two trackers.
+            // At present, it is impossible to effectively locate which memory consume and release on different trackers,
+            // so query memory leaks cannot be found.
+            //
+            // In order to ensure that the query pool mem tracker is the sum of all currently running query mem trackers,
+            // the effect of the ended query mem tracker on the query pool mem tracker should be cleared, that is,
+            // the negative number of the current value of consume.
+            it->second->parent()->consumption_revise(-it->second->consumption());
+            LOG(INFO) << "Deregister query/load memory tracker, queryId/loadId: " << it->first;
+            expired_task_ids.emplace_back(it->first);
+        }
+    }
+    for (auto tid : expired_task_ids) {
+        // Verify the condition again to make sure the tracker is not being used again.
+        _task_mem_trackers.erase_if(tid, [&](const std::shared_ptr<MemTrackerLimiter>& v) {
+            return !v || v.use_count() == 1;
+        });
+    }
+}
+
+// TODO(zxy) More observable methods
+// /// Logs the usage of 'limit' number of queries based on maximum total memory
+// /// consumption.
+// std::string MemTracker::LogTopNQueries(int limit) {
+//     if (limit == 0) return "";
+//     priority_queue<pair<int64_t, string>, std::vector<pair<int64_t, string>>,
+//                    std::greater<pair<int64_t, string>>>
+//             min_pq;
+//     GetTopNQueries(min_pq, limit);
+//     std::vector<string> usage_strings(min_pq.size());
+//     while (!min_pq.empty()) {
+//         usage_strings.push_back(min_pq.top().second);
+//         min_pq.pop();
+//     }
+//     std::reverse(usage_strings.begin(), usage_strings.end());
+//     return join(usage_strings, "\n");
+// }
+
+// /// Helper function for LogTopNQueries that iterates through the MemTracker hierarchy
+// /// and populates 'min_pq' with 'limit' number of elements (that contain state related
+// /// to query MemTrackers) based on maximum total memory consumption.
+// void MemTracker::GetTopNQueries(
+//         priority_queue<pair<int64_t, string>, std::vector<pair<int64_t, string>>,
+//                        greater<pair<int64_t, string>>>& min_pq,
+//         int limit) {
+//     list<weak_ptr<MemTracker>> children;
+//     {
+//         lock_guard<SpinLock> l(child_trackers_lock_);
+//         children = child_trackers_;
+//     }
+//     for (const auto& child_weak : children) {
+//         shared_ptr<MemTracker> child = child_weak.lock();
+//         if (child) {
+//             child->GetTopNQueries(min_pq, limit);
+//         }
+//     }
+// }
+
+} // namespace doris
diff --git a/be/src/runtime/memory/mem_tracker_task_pool.h b/be/src/runtime/memory/mem_tracker_task_pool.h
new file mode 100644
index 0000000000..1958542fe9
--- /dev/null
+++ b/be/src/runtime/memory/mem_tracker_task_pool.h
@@ -0,0 +1,61 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <parallel_hashmap/phmap.h>
+
+#include "runtime/memory/mem_tracker_limiter.h"
+
+namespace doris {
+
+using TaskTrackersMap = phmap::parallel_flat_hash_map<
+        std::string, std::shared_ptr<MemTrackerLimiter>,
+        phmap::priv::hash_default_hash<std::string>, phmap::priv::hash_default_eq<std::string>,
+        std::allocator<std::pair<const std::string, std::shared_ptr<MemTrackerLimiter>>>, 12,
+        std::mutex>;
+
+// Global task pool for query MemTrackers. Owned by ExecEnv.
+class MemTrackerTaskPool {
+public:
+    // Construct a MemTrackerLimiter object for 'task_id' with 'mem_limit' as the memory limit.
+    // The MemTrackerLimiter is a child of the pool MemTrackerLimiter, Calling this with the same
+    // 'task_id' will return the same MemTrackerLimiter object. This is used to track the local
+    // memory usage of all tasks executing. The first time this is called for a task,
+    // a new MemTrackerLimiter object is created with the pool tracker as its parent.
+    // Newly created trackers will always have a limit of -1.
+    std::shared_ptr<MemTrackerLimiter> register_task_mem_tracker_impl(
+            const std::string& task_id, int64_t mem_limit, const std::string& label,
+            const std::shared_ptr<MemTrackerLimiter>& parent);
+    std::shared_ptr<MemTrackerLimiter> register_query_mem_tracker(const std::string& query_id,
+                                                                  int64_t mem_limit);
+    std::shared_ptr<MemTrackerLimiter> register_load_mem_tracker(const std::string& load_id,
+                                                                 int64_t mem_limit);
+
+    std::shared_ptr<MemTrackerLimiter> get_task_mem_tracker(const std::string& task_id);
+
+    // Remove the mem tracker that has ended the query.
+    void logout_task_mem_tracker();
+
+private:
+    // All per-task MemTrackerLimiter objects.
+    // The life cycle of task MemTrackerLimiter in the process is the same as task runtime state,
+    // MemTrackers will be removed from this map after query finish or cancel.
+    TaskTrackersMap _task_mem_trackers;
+};
+
+} // namespace doris
\ No newline at end of file
diff --git a/be/src/runtime/memory/system_allocator.cpp b/be/src/runtime/memory/system_allocator.cpp
index 374cec5557..c05c28861b 100644
--- a/be/src/runtime/memory/system_allocator.cpp
+++ b/be/src/runtime/memory/system_allocator.cpp
@@ -23,6 +23,7 @@
 
 #include "common/config.h"
 #include "common/logging.h"
+#include "runtime/thread_context.h"
 
 namespace doris {
 
@@ -43,6 +44,8 @@ void SystemAllocator::free(uint8_t* ptr, size_t length) {
             char buf[64];
             LOG(ERROR) << "fail to free memory via munmap, errno=" << errno
                        << ", errmsg=" << strerror_r(errno, buf, 64);
+        } else {
+            RELEASE_THREAD_MEM_TRACKER(length);
         }
     } else {
         ::free(ptr);
@@ -63,12 +66,14 @@ uint8_t* SystemAllocator::allocate_via_malloc(size_t length) {
 }
 
 uint8_t* SystemAllocator::allocate_via_mmap(size_t length) {
+    CONSUME_THREAD_MEM_TRACKER(length);
     auto ptr = (uint8_t*)mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE,
                               -1, 0);
     if (ptr == MAP_FAILED) {
         char buf[64];
         LOG(ERROR) << "fail to allocate memory via mmap, errno=" << errno
                    << ", errmsg=" << strerror_r(errno, buf, 64);
+        RELEASE_THREAD_MEM_TRACKER(length);
         return nullptr;
     }
     return ptr;
diff --git a/be/src/runtime/memory/tcmalloc_hook.h b/be/src/runtime/memory/tcmalloc_hook.h
new file mode 100644
index 0000000000..627f42795d
--- /dev/null
+++ b/be/src/runtime/memory/tcmalloc_hook.h
@@ -0,0 +1,72 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <gperftools/malloc_hook.h>
+#include <gperftools/nallocx.h>
+#include <gperftools/tcmalloc.h>
+
+#include "runtime/thread_context.h"
+
+// Notice: modify the command in New/Delete Hook should be careful enough!,
+// and should be as simple as possible, otherwise it may cause weird errors. E.g:
+//  1. The first New Hook call of the process may be before some variables of
+//  the process are initialized.
+//  2. Allocating memory in the Hook command causes the Hook to be entered again,
+//  infinite recursion.
+//  3. TCMalloc hook will be triggered during the process of initializing/Destructor
+//  memtracker shared_ptr, Using the object pointed to by this memtracker shared_ptr
+//  in TCMalloc hook may cause crash.
+//  4. Modifying additional thread local variables in ThreadContext construction and
+//  destructor to control the behavior of consume can lead to unexpected behavior,
+//  like this: if (LIKELY(doris::start_thread_mem_tracker)) {
+void new_hook(const void* ptr, size_t size) {
+    if (doris::btls_key != doris::EMPTY_BTLS_KEY && doris::bthread_context != nullptr) {
+        // Currently in bthread, consume thread context mem tracker in bthread tls.
+        doris::update_bthread_context();
+        doris::bthread_context->_thread_mem_tracker_mgr->consume(tc_nallocx(size, 0));
+    } else if (doris::thread_context_ptr._init) {
+        doris::thread_context_ptr._ptr->_thread_mem_tracker_mgr->consume(tc_nallocx(size, 0));
+    } else {
+        doris::ThreadMemTrackerMgr::consume_no_attach(tc_nallocx(size, 0));
+    }
+}
+
+void delete_hook(const void* ptr) {
+    if (doris::btls_key != doris::EMPTY_BTLS_KEY && doris::bthread_context != nullptr) {
+        doris::update_bthread_context();
+        doris::bthread_context->_thread_mem_tracker_mgr->consume(
+                -tc_malloc_size(const_cast<void*>(ptr)));
+    } else if (doris::thread_context_ptr._init) {
+        doris::thread_context_ptr._ptr->_thread_mem_tracker_mgr->consume(
+                -tc_malloc_size(const_cast<void*>(ptr)));
+    } else {
+        doris::ThreadMemTrackerMgr::consume_no_attach(-tc_malloc_size(const_cast<void*>(ptr)));
+    }
+}
+
+void init_hook() {
+    MallocHook::AddNewHook(&new_hook);
+    MallocHook::AddDeleteHook(&delete_hook);
+}
+
+// For later debug.
+// static void destroy_hook() {
+//     MallocHook::RemoveNewHook(&new_hook);
+//     MallocHook::RemoveDeleteHook(&delete_hook);
+// }
diff --git a/be/src/runtime/memory/thread_mem_tracker_mgr.cpp b/be/src/runtime/memory/thread_mem_tracker_mgr.cpp
new file mode 100644
index 0000000000..ab2d1fc1c0
--- /dev/null
+++ b/be/src/runtime/memory/thread_mem_tracker_mgr.cpp
@@ -0,0 +1,69 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "runtime/memory/thread_mem_tracker_mgr.h"
+
+#include "runtime/exec_env.h"
+#include "runtime/fragment_mgr.h"
+#include "runtime/memory/mem_tracker_task_pool.h"
+#include "service/backend_options.h"
+
+namespace doris {
+
+void ThreadMemTrackerMgr::attach_limiter_tracker(
+        const std::string& cancel_msg, const std::string& task_id,
+        const TUniqueId& fragment_instance_id,
+        const std::shared_ptr<MemTrackerLimiter>& mem_tracker) {
+    DCHECK(mem_tracker);
+    flush_untracked_mem<false>();
+    _task_id = task_id;
+    _fragment_instance_id = fragment_instance_id;
+    _exceed_cb.cancel_msg = cancel_msg;
+    _limiter_tracker = mem_tracker;
+}
+
+void ThreadMemTrackerMgr::detach_limiter_tracker() {
+    flush_untracked_mem<false>();
+    _task_id = "";
+    _fragment_instance_id = TUniqueId();
+    _exceed_cb.cancel_msg = "";
+    _limiter_tracker = ExecEnv::GetInstance()->new_process_mem_tracker();
+}
+
+void ThreadMemTrackerMgr::exceeded_cancel_task(const std::string& cancel_details) {
+    if (_fragment_instance_id != TUniqueId()) {
+        ExecEnv::GetInstance()->fragment_mgr()->cancel(
+                _fragment_instance_id, PPlanFragmentCancelReason::MEMORY_LIMIT_EXCEED,
+                cancel_details);
+    }
+}
+
+void ThreadMemTrackerMgr::exceeded(int64_t failed_consume_size, Status failed_try_consume_rt) {
+    if (_exceed_cb.cb_func != nullptr) {
+        _exceed_cb.cb_func();
+    }
+    if (is_attach_task()) {
+        if (_exceed_cb.cancel_task) {
+            auto st = _limiter_tracker->mem_limit_exceeded(
+                    fmt::format("query mem limit exceeded and cancel it, {}", _exceed_cb.cancel_msg),
+                    failed_consume_size, failed_try_consume_rt, _fragment_instance_id);
+            exceeded_cancel_task(st.to_string());
+            _exceed_cb.cancel_task = false; // Make sure it will only be canceled once
+        }
+    }
+}
+} // namespace doris
diff --git a/be/src/runtime/memory/thread_mem_tracker_mgr.h b/be/src/runtime/memory/thread_mem_tracker_mgr.h
new file mode 100644
index 0000000000..13eed946ba
--- /dev/null
+++ b/be/src/runtime/memory/thread_mem_tracker_mgr.h
@@ -0,0 +1,234 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <fmt/format.h>
+#include <parallel_hashmap/phmap.h>
+#include <service/brpc_conflict.h>
+
+#include "runtime/memory/mem_tracker.h"
+#include "runtime/memory/mem_tracker_limiter.h"
+// After brpc_conflict.h
+#include <bthread/bthread.h>
+
+namespace doris {
+
+extern bthread_key_t btls_key;
+static const bthread_key_t EMPTY_BTLS_KEY = {0, 0};
+
+using ExceedCallBack = void (*)();
+struct MemExceedCallBackInfo {
+    std::string cancel_msg;
+    bool cancel_task; // Whether to cancel the task when the current tracker exceeds the limit.
+    ExceedCallBack cb_func;
+
+    MemExceedCallBackInfo() { init(); }
+
+    MemExceedCallBackInfo(const std::string& cancel_msg, bool cancel_task, ExceedCallBack cb_func)
+            : cancel_msg(cancel_msg), cancel_task(cancel_task), cb_func(cb_func) {}
+
+    void init() {
+        cancel_msg = "";
+        cancel_task = true;
+        cb_func = nullptr;
+    }
+};
+
+// TCMalloc new/delete Hook is counted in the memory_tracker of the current thread.
+//
+// In the original design, the NewMemTracker consume method is called before the memory is allocated.
+// If the consume succeeds, the memory is actually allocated, otherwise an exception is thrown.
+// But the statistics of memory through TCMalloc new/delete Hook are after the memory is actually allocated,
+// which is different from the previous behavior. Therefore, when alloc for some large memory.
+class ThreadMemTrackerMgr {
+public:
+    ThreadMemTrackerMgr() {}
+
+    ~ThreadMemTrackerMgr() {
+        flush_untracked_mem<false>();
+        _exceed_cb.init();
+        DCHECK(_consumer_tracker_stack.empty());
+    }
+
+    // only for tcmalloc hook
+    static void consume_no_attach(int64_t size) {
+        ExecEnv::GetInstance()->new_process_mem_tracker()->consume(size);
+    }
+
+    // After thread initialization, calling `init` again must call `clear_untracked_mems` first
+    // to avoid memory tracking loss.
+    void init();
+
+    // After attach, the current thread TCMalloc Hook starts to consume/release task mem_tracker
+    void attach_limiter_tracker(const std::string& cancel_msg, const std::string& task_id,
+                                const TUniqueId& fragment_instance_id,
+                                const std::shared_ptr<MemTrackerLimiter>& mem_tracker);
+
+    void detach_limiter_tracker();
+
+    // Must be fast enough! Thread update_tracker may be called very frequently.
+    // So for performance, add tracker as early as possible, and then call update_tracker<Existed>.
+    void push_consumer_tracker(NewMemTracker* mem_tracker);
+    void pop_consumer_tracker();
+
+    MemExceedCallBackInfo update_exceed_call_back(const std::string& cancel_msg, bool cancel_task,
+                                                  ExceedCallBack cb_func) {
+        _temp_exceed_cb = _exceed_cb;
+        _exceed_cb.cancel_msg = cancel_msg;
+        _exceed_cb.cancel_task = cancel_task;
+        _exceed_cb.cb_func = cb_func;
+        return _temp_exceed_cb;
+    }
+
+    void update_exceed_call_back(const MemExceedCallBackInfo& exceed_cb) { _exceed_cb = exceed_cb; }
+
+    // Note that, If call the memory allocation operation in TCMalloc new/delete Hook,
+    // such as calling LOG/iostream/sstream/stringstream/etc. related methods,
+    // must increase the control to avoid entering infinite recursion, otherwise it may cause crash or stuck,
+    void consume(int64_t size);
+
+    void transfer_to(int64_t size, MemTrackerLimiter* mem_tracker) {
+        consume(-size);
+        mem_tracker->consume(size);
+    }
+    void transfer_from(int64_t size, MemTrackerLimiter* mem_tracker) {
+        mem_tracker->release(size);
+        consume(size);
+    }
+
+    template <bool CheckLimit>
+    void flush_untracked_mem();
+
+    bool is_attach_task() { return _task_id != ""; }
+
+    std::shared_ptr<MemTrackerLimiter> limiter_mem_tracker() { return _limiter_tracker; }
+
+    void set_check_limit(bool check_limit) { _check_limit = check_limit; }
+    void set_check_attach(bool check_attach) { _check_attach = check_attach; }
+
+    std::string print_debug_string() {
+        fmt::memory_buffer consumer_tracker_buf;
+        for (const auto& v : _consumer_tracker_stack) {
+            fmt::format_to(consumer_tracker_buf, "{}, ",
+                           NewMemTracker::log_usage(v->make_snapshot(0)));
+        }
+        return fmt::format(
+                "ThreadMemTrackerMgr debug, _untracked_mem:{}, _task_id:{}, "
+                "_limiter_tracker:<{}>, _consumer_tracker_stack:<{}>",
+                std::to_string(_untracked_mem), _task_id, _limiter_tracker->log_usage(1),
+                fmt::to_string(consumer_tracker_buf));
+    }
+
+private:
+    // If tryConsume fails due to task mem tracker exceeding the limit, the task must be canceled
+    void exceeded_cancel_task(const std::string& cancel_details);
+
+    void exceeded(int64_t failed_consume_size, Status failed_try_consume_rt);
+
+private:
+    // Cache untracked mem, only update to _untracked_mems when switching mem tracker.
+    // Frequent calls to unordered_map _untracked_mems[] in consume will degrade performance.
+    int64_t _untracked_mem = 0;
+
+    std::shared_ptr<MemTrackerLimiter> _limiter_tracker;
+    std::vector<NewMemTracker*> _consumer_tracker_stack;
+
+    // If true, call memtracker try_consume, otherwise call consume.
+    bool _check_limit = false;
+    // If there is a memory new/delete operation in the consume method, it may enter infinite recursion.
+    bool _stop_consume = false;
+    bool _check_attach = true;
+    std::string _task_id;
+    TUniqueId _fragment_instance_id;
+    MemExceedCallBackInfo _exceed_cb;
+    MemExceedCallBackInfo _temp_exceed_cb;
+};
+
+inline void ThreadMemTrackerMgr::init() {
+    DCHECK(_consumer_tracker_stack.empty());
+    _task_id = "";
+    _exceed_cb.init();
+    _limiter_tracker = ExecEnv::GetInstance()->new_process_mem_tracker();
+    _check_limit = true;
+}
+
+inline void ThreadMemTrackerMgr::push_consumer_tracker(NewMemTracker* tracker) {
+    DCHECK(tracker) << print_debug_string();
+    DCHECK(!std::count(_consumer_tracker_stack.begin(), _consumer_tracker_stack.end(), tracker))
+            << print_debug_string();
+    _consumer_tracker_stack.push_back(tracker);
+    tracker->release(_untracked_mem);
+}
+
+inline void ThreadMemTrackerMgr::pop_consumer_tracker() {
+    DCHECK(!_consumer_tracker_stack.empty());
+    _consumer_tracker_stack.back()->consume(_untracked_mem);
+    _consumer_tracker_stack.pop_back();
+}
+
+inline void ThreadMemTrackerMgr::consume(int64_t size) {
+    _untracked_mem += size;
+    // When some threads `0 < _untracked_mem < config::mem_tracker_consume_min_size_bytes`
+    // and some threads `_untracked_mem <= -config::mem_tracker_consume_min_size_bytes` trigger consumption(),
+    // it will cause tracker->consumption to be temporarily less than 0.
+    if ((_untracked_mem >= config::mem_tracker_consume_min_size_bytes ||
+         _untracked_mem <= -config::mem_tracker_consume_min_size_bytes) &&
+        !_stop_consume) {
+        if (_check_limit) {
+            flush_untracked_mem<true>();
+        } else {
+            flush_untracked_mem<false>();
+        }
+    }
+}
+
+template <bool CheckLimit>
+inline void ThreadMemTrackerMgr::flush_untracked_mem() {
+    // Temporary memory may be allocated during the consumption of the mem tracker, which will lead to entering
+    // the TCMalloc Hook again, so suspend consumption to avoid falling into an infinite loop.
+    _stop_consume = true;
+    DCHECK(_limiter_tracker);
+    if (CheckLimit) {
+#ifndef BE_TEST
+        // When all threads are started, `attach_limiter_tracker` is expected to be called to bind the limiter tracker.
+        // If _check_attach is true and it is not in the brpc server (the protobuf will be operated when bthread is started),
+        // it will check whether the tracker label is equal to the default "Process" when flushing.
+        // If you do not want this check, set_check_attach=true
+        // TODO(zxy) The current p0 test cannot guarantee that all threads are checked,
+        // so disable it and try to open it when memory tracking is not on time.
+        // DCHECK(!_check_attach || btls_key != EMPTY_BTLS_KEY ||
+        //        _limiter_tracker->label() != "Process");
+#endif
+        Status st = _limiter_tracker->try_consume(_untracked_mem);
+        if (!st) {
+            // The memory has been allocated, so when TryConsume fails, need to continue to complete
+            // the consume to ensure the accuracy of the statistics.
+            _limiter_tracker->consume(_untracked_mem);
+            exceeded(_untracked_mem, st);
+        }
+    } else {
+        _limiter_tracker->consume(_untracked_mem);
+    }
+    for (auto tracker : _consumer_tracker_stack) {
+        tracker->consume(_untracked_mem);
+    }
+    _untracked_mem = 0;
+    _stop_consume = false;
+}
+
+} // namespace doris
diff --git a/be/src/runtime/plan_fragment_executor.cpp b/be/src/runtime/plan_fragment_executor.cpp
index 04843e3091..fcce7fa43c 100644
--- a/be/src/runtime/plan_fragment_executor.cpp
+++ b/be/src/runtime/plan_fragment_executor.cpp
@@ -33,7 +33,9 @@
 #include "runtime/mem_tracker.h"
 #include "runtime/result_buffer_mgr.h"
 #include "runtime/result_queue_mgr.h"
+#include "runtime/runtime_filter_mgr.h"
 #include "runtime/row_batch.h"
+#include "runtime/thread_context.h"
 #include "util/container_util.hpp"
 #include "util/cpu_info.h"
 #include "util/logging.h"
@@ -87,6 +89,8 @@ Status PlanFragmentExecutor::prepare(const TExecPlanFragmentParams& request,
     _runtime_state->set_query_fragments_ctx(fragments_ctx);
 
     RETURN_IF_ERROR(_runtime_state->init_mem_trackers(_query_id));
+    SCOPED_ATTACH_TASK(_runtime_state.get());
+    _runtime_state->runtime_filter_mgr()->init();
     _runtime_state->set_be_number(request.backend_num);
     if (request.__isset.backend_id) {
         _runtime_state->set_backend_id(request.backend_id);
@@ -266,6 +270,8 @@ Status PlanFragmentExecutor::open() {
     if (status.is_cancelled()) {
         if (_cancel_reason == PPlanFragmentCancelReason::CALL_RPC_ERROR) {
             status = Status::RuntimeError(_cancel_msg);
+        } else if (_cancel_reason == PPlanFragmentCancelReason::MEMORY_LIMIT_EXCEED) {
+            status = Status::MemoryAllocFailed(_cancel_msg);
         }
     }
 
@@ -458,6 +464,7 @@ void PlanFragmentExecutor::_collect_node_statistics() {
 }
 
 void PlanFragmentExecutor::report_profile() {
+    SCOPED_ATTACH_TASK(_runtime_state.get());
     VLOG_FILE << "report_profile(): instance_id=" << _runtime_state->fragment_instance_id();
     DCHECK(_report_status_cb);
 
diff --git a/be/src/runtime/result_sink.cpp b/be/src/runtime/result_sink.cpp
index 8b68b6b12b..98ea3a61a2 100644
--- a/be/src/runtime/result_sink.cpp
+++ b/be/src/runtime/result_sink.cpp
@@ -100,6 +100,9 @@ Status ResultSink::open(RuntimeState* state) {
 }
 
 Status ResultSink::send(RuntimeState* state, RowBatch* batch) {
+    // The memory consumption in the process of sending the results is not check query memory limit.
+    // Avoid the query being cancelled when the memory limit is reached after the query result comes out.
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
     return _writer->append_row_batch(batch);
 }
 
diff --git a/be/src/runtime/runtime_state.cpp b/be/src/runtime/runtime_state.cpp
index ccbf2a0f11..2107c74d65 100644
--- a/be/src/runtime/runtime_state.cpp
+++ b/be/src/runtime/runtime_state.cpp
@@ -36,6 +36,7 @@
 #include "runtime/initial_reservations.h"
 #include "runtime/load_path_mgr.h"
 #include "runtime/mem_tracker.h"
+#include "runtime/memory/mem_tracker_task_pool.h"
 #include "runtime/runtime_filter_mgr.h"
 #include "util/cpu_info.h"
 #include "util/disk_info.h"
@@ -206,6 +207,15 @@ Status RuntimeState::init(const TUniqueId& fragment_instance_id, const TQueryOpt
 Status RuntimeState::init_mem_trackers(const TUniqueId& query_id) {
     bool has_query_mem_tracker = _query_options.__isset.mem_limit && (_query_options.mem_limit > 0);
     int64_t bytes_limit = has_query_mem_tracker ? _query_options.mem_limit : -1;
+    if (bytes_limit > ExecEnv::GetInstance()->process_mem_tracker()->limit()) {
+        VLOG_NOTICE << "Query memory limit " << PrettyPrinter::print(bytes_limit, TUnit::BYTES)
+                    << " exceeds process memory limit of "
+                    << PrettyPrinter::print(ExecEnv::GetInstance()->process_mem_tracker()->limit(),
+                                            TUnit::BYTES)
+                    << ". Using process memory limit instead";
+        bytes_limit = ExecEnv::GetInstance()->process_mem_tracker()->limit();
+    }
+
     // we do not use global query-map  for now, to avoid mem-exceeded different fragments
     // running on the same machine.
     // TODO(lingbin): open it later. note that open with BufferedBlockMgr's BlockMgrsMap
@@ -223,6 +233,22 @@ Status RuntimeState::init_mem_trackers(const TUniqueId& query_id) {
     _instance_mem_tracker =
             MemTracker::CreateTracker(&_profile, -1, "RuntimeState:instance:", _query_mem_tracker);
 
+    if (query_type() == TQueryType::SELECT) {
+        _new_query_mem_tracker =
+                _exec_env->task_pool_mem_tracker_registry()->register_query_mem_tracker(
+                        print_id(query_id), bytes_limit);
+    } else if (query_type() == TQueryType::LOAD) {
+        _new_query_mem_tracker = _exec_env->task_pool_mem_tracker_registry()->register_load_mem_tracker(
+                print_id(query_id), bytes_limit);
+    } else {
+        DCHECK(false);
+        _new_query_mem_tracker = ExecEnv::GetInstance()->query_pool_mem_tracker();
+    }
+
+    _new_instance_mem_tracker = std::make_shared<MemTrackerLimiter>(
+            bytes_limit, "RuntimeState:instance:" + print_id(_fragment_instance_id),
+            _new_query_mem_tracker);
+
     /*
     // TODO: this is a stopgap until we implement ExprContext
     _udf_mem_tracker.reset(
@@ -243,10 +269,7 @@ Status RuntimeState::init_mem_trackers(const TUniqueId& query_id) {
         _instance_buffer_reservation->InitChildTracker(&_profile, _buffer_reservation,
                                                        _instance_mem_tracker.get(),
                                                        std::numeric_limits<int64_t>::max());
-    }
-
-    // filter manager depends _instance_mem_tracker
-    _runtime_filter_mgr->init();
+    }    
     return Status::OK();
 }
 
@@ -330,46 +353,13 @@ void RuntimeState::get_unreported_errors(std::vector<std::string>* new_errors) {
     }
 }
 
-Status RuntimeState::set_mem_limit_exceeded(MemTracker* tracker, int64_t failed_allocation_size,
-                                            const std::string* msg) {
-    DCHECK_GE(failed_allocation_size, 0);
+Status RuntimeState::set_mem_limit_exceeded(const std::string& msg) {
     {
         std::lock_guard<std::mutex> l(_process_status_lock);
         if (_process_status.ok()) {
-            if (msg != nullptr) {
-                _process_status = Status::MemoryLimitExceeded(*msg);
-            } else {
-                _process_status = Status::MemoryLimitExceeded("Memory limit exceeded");
-            }
-        } else {
-            return _process_status;
+            _process_status = Status::MemoryLimitExceeded(msg);
         }
     }
-
-    DCHECK(_query_mem_tracker.get() != nullptr);
-    std::stringstream ss;
-    ss << "Memory Limit Exceeded\n";
-    if (failed_allocation_size != 0) {
-        DCHECK(tracker != nullptr);
-        ss << "  " << tracker->label() << " could not allocate "
-           << PrettyPrinter::print(failed_allocation_size, TUnit::BYTES)
-           << " without exceeding limit." << std::endl;
-    }
-
-    // if (_exec_env->process_mem_tracker()->LimitExceeded()) {
-    //     ss << _exec_env->process_mem_tracker()->LogUsage();
-    // } else {
-    //     ss << _query_mem_tracker->LogUsage();
-    // }
-    // log_error(ErrorMsg(TErrorCode::GENERAL, ss.str()));
-    log_error(ss.str());
-    // Add warning about missing stats except for compute stats child queries.
-    // if (!query_ctx().__isset.parent_query_id &&
-    //         query_ctx().__isset.tables_missing_stats &&
-    //         !query_ctx().tables_missing_stats.empty()) {
-    //     LogError(ErrorMsg(TErrorCode::GENERAL,
-    //                 GetTablesMissingStatsWarning(query_ctx().tables_missing_stats)));
-    // }
     DCHECK(_process_status.is_mem_limit_exceeded());
     return _process_status;
 }
diff --git a/be/src/runtime/runtime_state.h b/be/src/runtime/runtime_state.h
index 32f4bb97d4..4f03a206e0 100644
--- a/be/src/runtime/runtime_state.h
+++ b/be/src/runtime/runtime_state.h
@@ -36,6 +36,7 @@
 #include "runtime/thread_resource_mgr.h"
 #include "util/logging.h"
 #include "util/runtime_profile.h"
+#include "runtime/thread_context.h"
 
 namespace doris {
 
@@ -113,6 +114,7 @@ public:
     int max_errors() const { return _query_options.max_errors; }
     int max_io_buffers() const { return _query_options.max_io_buffers; }
     int num_scanner_threads() const { return _query_options.num_scanner_threads; }
+    TQueryType::type query_type() const { return _query_options.query_type; }
     int64_t timestamp_ms() const { return _timestamp_ms; }
     const std::string& timezone() const { return _timezone; }
     const cctz::time_zone& timezone_obj() const { return _timezone_obj; }
@@ -125,6 +127,8 @@ public:
     std::shared_ptr<MemTracker> fragment_mem_tracker() { return _fragment_mem_tracker; }
     std::shared_ptr<MemTracker> query_mem_tracker() { return _query_mem_tracker; }
     std::shared_ptr<MemTracker> instance_mem_tracker() { return _instance_mem_tracker; }
+    std::shared_ptr<MemTrackerLimiter> new_query_mem_tracker() { return _new_query_mem_tracker; }
+    std::shared_ptr<MemTrackerLimiter> new_instance_mem_tracker() { return _new_instance_mem_tracker; }
     ThreadResourceMgr::ResourcePool* resource_pool() { return _resource_pool; }
 
     void set_fragment_root_id(PlanNodeId id) {
@@ -226,19 +230,11 @@ public:
         _process_status = status;
     }
 
-    // Sets query_status_ to MEM_LIMIT_EXCEEDED and logs all the registered trackers.
-    // Subsequent calls to this will be no-ops. Returns query_status_.
-    // If 'failed_allocation_size' is not 0, then it is the size of the allocation (in
-    // bytes) that would have exceeded the limit allocated for 'tracker'.
-    // This value and tracker are only used for error reporting.
+    // Sets _process_status to MEM_LIMIT_EXCEEDED.
+    // Subsequent calls to this will be no-ops. Returns _process_status.
     // If 'msg' is non-nullptr, it will be appended to query_status_ in addition to the
     // generic "Memory limit exceeded" error.
-    Status set_mem_limit_exceeded(MemTracker* tracker = nullptr, int64_t failed_allocation_size = 0,
-                                  const std::string* msg = nullptr);
-
-    Status set_mem_limit_exceeded(const std::string& msg) {
-        return set_mem_limit_exceeded(nullptr, 0, &msg);
-    }
+    Status set_mem_limit_exceeded(const std::string& msg = "Memory limit exceeded");
 
     // Returns a non-OK status if query execution should stop (e.g., the query was cancelled
     // or a mem limit was exceeded). Exec nodes should check this periodically so execution
@@ -414,6 +410,13 @@ private:
     // Memory usage of this fragment instance
     std::shared_ptr<MemTracker> _instance_mem_tracker;
 
+    // MemTracker that is shared by all fragment instances running on this host.
+    // The query mem tracker must be released after the _instance_mem_tracker.
+    std::shared_ptr<MemTrackerLimiter> _new_query_mem_tracker;
+
+    // Memory usage of this fragment instance
+    std::shared_ptr<MemTrackerLimiter> _new_instance_mem_tracker;
+
     // put runtime state before _obj_pool, so that it will be deconstructed after
     // _obj_pool. Because some of object in _obj_pool will use profile when deconstructing.
     RuntimeProfile _profile;
diff --git a/be/src/runtime/sorted_run_merger.cc b/be/src/runtime/sorted_run_merger.cc
index 28baab462e..3bb2d9169c 100644
--- a/be/src/runtime/sorted_run_merger.cc
+++ b/be/src/runtime/sorted_run_merger.cc
@@ -24,6 +24,7 @@
 #include "runtime/descriptors.h"
 #include "runtime/row_batch.h"
 #include "runtime/sorter.h"
+#include "runtime/thread_context.h"
 #include "runtime/tuple_row.h"
 #include "util/debug_util.h"
 #include "util/defer_op.h"
@@ -124,7 +125,7 @@ public:
     Status init(bool* done) override {
         *done = false;
         _pull_task_thread = std::thread(
-                &SortedRunMerger::ParallelBatchedRowSupplier::process_sorted_run_task, this);
+                &SortedRunMerger::ParallelBatchedRowSupplier::process_sorted_run_task, this, thread_context()->_thread_mem_tracker_mgr->limiter_mem_tracker());
 
         RETURN_IF_ERROR(next(nullptr, done));
         return Status::OK();
@@ -177,7 +178,8 @@ private:
     // signal of new batch or the eos/cancelled condition
     std::condition_variable _batch_prepared_cv;
 
-    void process_sorted_run_task() {
+    void process_sorted_run_task(const std::shared_ptr<MemTrackerLimiter>& mem_tracker) {
+        SCOPED_ATTACH_TASK(mem_tracker, ThreadContext::TaskType::QUERY);
         std::unique_lock<std::mutex> lock(_mutex);
         while (true) {
             _batch_prepared_cv.wait(lock, [this]() { return !_backup_ready.load(); });
diff --git a/be/src/runtime/tablets_channel.cpp b/be/src/runtime/tablets_channel.cpp
index e8ecfa7e51..5ce3fe0ab0 100644
--- a/be/src/runtime/tablets_channel.cpp
+++ b/be/src/runtime/tablets_channel.cpp
@@ -24,6 +24,7 @@
 #include "runtime/row_batch.h"
 #include "runtime/tuple_row.h"
 #include "util/doris_metrics.h"
+#include <boost/lexical_cast.hpp>
 
 namespace doris {
 
@@ -219,7 +220,7 @@ void TabletsChannel::_close_wait(DeltaWriter* writer,
     } else {
         PTabletError* tablet_error = tablet_errors->Add();
         tablet_error->set_tablet_id(writer->tablet_id());
-        tablet_error->set_msg("close wait failed: " + st);
+        tablet_error->set_msg("close wait failed: " + boost::lexical_cast<string>(st));
     }
 }
 
diff --git a/be/src/runtime/thread_context.cpp b/be/src/runtime/thread_context.cpp
index 871cd1ebf0..6ae9c644a0 100644
--- a/be/src/runtime/thread_context.cpp
+++ b/be/src/runtime/thread_context.cpp
@@ -17,16 +17,105 @@
 
 #include "runtime/thread_context.h"
 
+#include "runtime/runtime_state.h"
+
 namespace doris {
 
-DEFINE_STATIC_THREAD_LOCAL(ThreadContext, ThreadContextPtr, thread_local_ctx);
+DEFINE_STATIC_THREAD_LOCAL(ThreadContext, ThreadContextPtr, _ptr);
 
 ThreadContextPtr::ThreadContextPtr() {
-    INIT_STATIC_THREAD_LOCAL(ThreadContext, thread_local_ctx);
+    INIT_STATIC_THREAD_LOCAL(ThreadContext, _ptr);
+    _init = true;
+}
+
+AttachTask::AttachTask(const std::shared_ptr<MemTrackerLimiter>& mem_tracker,
+                       const ThreadContext::TaskType& type, const std::string& task_id,
+                       const TUniqueId& fragment_instance_id) {
+    DCHECK(mem_tracker);
+#ifdef USE_MEM_TRACKER
+    thread_context()->attach_task(type, task_id, fragment_instance_id, mem_tracker);
+#endif
+}
+
+AttachTask::AttachTask(RuntimeState* runtime_state) {
+#ifndef BE_TEST
+    DCHECK(print_id(runtime_state->query_id()) != "");
+    DCHECK(runtime_state->fragment_instance_id() != TUniqueId());
+#endif // BE_TEST
+    DCHECK(runtime_state->new_instance_mem_tracker());
+#ifdef USE_MEM_TRACKER
+    thread_context()->attach_task(
+            query_to_task_type(runtime_state->query_type()), print_id(runtime_state->query_id()),
+            runtime_state->fragment_instance_id(), runtime_state->new_instance_mem_tracker());
+#endif // USE_MEM_TRACKER
+}
+
+AttachTask::~AttachTask() {
+#ifdef USE_MEM_TRACKER
+    thread_context()->detach_task();
+#endif
+}
+
+AddThreadMemTrackerConsumer::AddThreadMemTrackerConsumer(NewMemTracker* mem_tracker) {
+#ifdef USE_MEM_TRACKER
+    if (config::memory_verbose_track) {
+        thread_context()->_thread_mem_tracker_mgr->push_consumer_tracker(mem_tracker);
+    }
+#endif // USE_MEM_TRACKER
+}
+
+AddThreadMemTrackerConsumer::~AddThreadMemTrackerConsumer() {
+#ifdef USE_MEM_TRACKER
+    if (config::memory_verbose_track) {
+        thread_context()->_thread_mem_tracker_mgr->pop_consumer_tracker();
+    }
+#endif // USE_MEM_TRACKER
+}
+
+UpdateMemExceedCallBack::UpdateMemExceedCallBack(const std::string& cancel_msg, bool cancel_task,
+                                                 ExceedCallBack cb_func) {
+#ifdef USE_MEM_TRACKER
+    DCHECK(cancel_msg != std::string());
+    _old_cb = thread_context()->_thread_mem_tracker_mgr->update_exceed_call_back(
+            cancel_msg, cancel_task, cb_func);
+#endif
+}
+
+UpdateMemExceedCallBack::~UpdateMemExceedCallBack() {
+#ifdef USE_MEM_TRACKER
+    thread_context()->_thread_mem_tracker_mgr->update_exceed_call_back(_old_cb);
+#endif // USE_MEM_TRACKER
+}
+
+SwitchBthread::SwitchBthread() {
+#ifdef USE_MEM_TRACKER
+    _bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
+    // First call to bthread_getspecific (and before any bthread_setspecific) returns NULL
+    if (_bthread_context == nullptr) {
+        // Create thread-local data on demand.
+        _bthread_context = new ThreadContext;
+        // set the data so that next time bthread_getspecific in the thread returns the data.
+        CHECK_EQ(0, bthread_setspecific(btls_key, _bthread_context));
+    } else {
+        DCHECK(_bthread_context->type() == ThreadContext::TaskType::UNKNOWN);
+        _bthread_context->_thread_mem_tracker_mgr->flush_untracked_mem<false>();
+    }
+    _bthread_context->_thread_mem_tracker_mgr->init();
+    _bthread_context->set_type(ThreadContext::TaskType::BRPC);
+    bthread_context_key = btls_key;
+    bthread_context = _bthread_context;
+#endif
 }
 
-ThreadContext* ThreadContextPtr::get() {
-    return thread_local_ctx;
+SwitchBthread::~SwitchBthread() {
+#ifdef USE_MEM_TRACKER
+    DCHECK(_bthread_context != nullptr);
+    _bthread_context->_thread_mem_tracker_mgr->flush_untracked_mem<false>();
+    _bthread_context->_thread_mem_tracker_mgr->init();
+    _bthread_context->set_type(ThreadContext::TaskType::UNKNOWN);
+    bthread_context = nullptr;
+    bthread_context_key = EMPTY_BTLS_KEY;
+#endif // USE_MEM_TRACKER
 }
 
 } // namespace doris
diff --git a/be/src/runtime/thread_context.h b/be/src/runtime/thread_context.h
index 7c2a97faac..254b465b00 100644
--- a/be/src/runtime/thread_context.h
+++ b/be/src/runtime/thread_context.h
@@ -17,22 +17,76 @@
 
 #pragma once
 
+#include <service/brpc_conflict.h>
+// After brpc_conflict.h
+#include <bthread/bthread.h>
+
 #include <string>
 #include <thread>
 
 #include "common/logging.h"
-#include "gen_cpp/Types_types.h"
+#include "gen_cpp/PaloInternalService_types.h" // for TQueryType
+#include "runtime/memory/thread_mem_tracker_mgr.h"
 #include "runtime/threadlocal.h"
 
-#define SCOPED_ATTACH_TASK_THREAD(type, ...) \
-    auto VARNAME_LINENUM(attach_task_thread) = AttachTaskThread(type, ## __VA_ARGS__)
+// Add thread mem tracker consumer during query execution.
+#define SCOPED_CONSUME_MEM_TRACKER(mem_tracker) \
+    auto VARNAME_LINENUM(add_mem_consumer) = doris::AddThreadMemTrackerConsumer(mem_tracker)
+
+#define SCOPED_UPDATE_MEM_EXCEED_CALL_BACK(cancel_msg, ...) \
+    auto VARNAME_LINENUM(update_exceed_cb) =                \
+            doris::UpdateMemExceedCallBack(cancel_msg, ##__VA_ARGS__)
 
 namespace doris {
 
 class TUniqueId;
+class ThreadContext;
+
+extern bthread_key_t btls_key;
+
+// Using gcc11 compiles thread_local variable on lower versions of GLIBC will report an error,
+// see https://github.com/apache/doris/pull/7911
+//
+// If we want to avoid this error,
+// 1. For non-trivial variables in thread_local, such as std::string, you need to store them as pointers to
+//    ensure that thread_local is trivial, these non-trivial pointers will uniformly call destructors elsewhere.
+// 2. The default destructor of the thread_local variable cannot be overridden.
+//
+// This is difficult to implement. Because the destructor is not overwritten, it means that the outside cannot
+// be notified when the thread terminates, and the non-trivial pointers in thread_local cannot be released in time.
+// The func provided by pthread and std::thread doesn't help either.
+//
+// So, kudu Class-scoped static thread local implementation was introduced. Solve the above problem by
+// Thread-scoped thread local + Class-scoped thread local.
+//
+// This may look very trick, but it's the best way I can find.
+//
+// refer to:
+//  https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Thread-Local.html
+//  https://stackoverflow.com/questions/12049684/
+//  https://sourceware.org/glibc/wiki/Destructor%20support%20for%20thread_local%20variables
+//  https://www.jianshu.com/p/756240e837dd
+//  https://man7.org/linux/man-pages/man3/pthread_tryjoin_np.3.html
+class ThreadContextPtr {
+public:
+    ThreadContextPtr();
+    // Cannot add destructor `~ThreadContextPtr`, otherwise it will no longer be of type POD, the reason is as above.
+
+    // TCMalloc hook is triggered during ThreadContext construction, which may lead to deadlock.
+    bool _init = false;
+
+    DECLARE_STATIC_THREAD_LOCAL(ThreadContext, _ptr);
+};
+
+inline thread_local ThreadContextPtr thread_context_ptr;
+
+// To avoid performance problems caused by frequently calling `bthread_getspecific` to obtain bthread TLS
+// in tcmalloc hook, cache the key and value of bthread TLS in pthread TLS.
+inline thread_local ThreadContext* bthread_context;
+inline thread_local bthread_key_t bthread_context_key;
 
 // The thread context saves some info about a working thread.
-// 2 requried info:
+// 2 required info:
 //   1. thread_id:   Current thread id, Auto generated.
 //   2. type:        The type is a enum value indicating which type of task current thread is running.
 //                   For example: QUERY, LOAD, COMPACTION, ...
@@ -45,99 +99,184 @@ public:
         UNKNOWN = 0,
         QUERY = 1,
         LOAD = 2,
-        COMPACTION = 3
+        COMPACTION = 3,
+        STORAGE = 4,
+        BRPC = 5
         // to be added ...
     };
+    inline static const std::string TaskTypeStr[] = {"UNKNOWN", "QUERY", "LOAD", "COMPACTION",
+                                                     "STORAGE"};
 
 public:
-    ThreadContext() : _thread_id(std::this_thread::get_id()), _type(TaskType::UNKNOWN) {}
+    ThreadContext() {
+        _thread_mem_tracker_mgr.reset(new ThreadMemTrackerMgr());
+        init();
+    }
+
+    ~ThreadContext() {
+        // Restore to the memory state before _init=true to ensure accurate overall memory statistics.
+        // Thereby ensuring that the memory alloc size is not tracked during the initialization of the
+        // ThreadContext before `_init = true in ThreadContextPtr()`,
+        // Equal to the size of the memory release that is not tracked during the destruction of the
+        // ThreadContext after `_init = false in ~ThreadContextPtr()`,
+        init();
+        thread_context_ptr._init = false;
+    }
 
-    void attach(const TaskType& type, const std::string& task_id,
-                const TUniqueId& fragment_instance_id) {
-        DCHECK(_type == TaskType::UNKNOWN && _task_id == "");
+    void init() {
+        _type = TaskType::UNKNOWN;
+        _thread_mem_tracker_mgr->init();
+        _thread_id = get_thread_id();
+    }
+
+    void attach_task(const TaskType& type, const std::string& task_id,
+                     const TUniqueId& fragment_instance_id,
+                     const std::shared_ptr<MemTrackerLimiter>& mem_tracker) {
+        DCHECK((_type == TaskType::UNKNOWN || _type == TaskType::BRPC) && _task_id == "")
+                << ",new tracker label: " << mem_tracker->label() << ",old tracker label: "
+                << _thread_mem_tracker_mgr->limiter_mem_tracker()->label();
+        DCHECK(type != TaskType::UNKNOWN);
         _type = type;
         _task_id = task_id;
         _fragment_instance_id = fragment_instance_id;
+        _thread_mem_tracker_mgr->attach_limiter_tracker(TaskTypeStr[_type], task_id,
+                                                        fragment_instance_id, mem_tracker);
     }
 
-    void detach() {
+    void detach_task() {
         _type = TaskType::UNKNOWN;
         _task_id = "";
         _fragment_instance_id = TUniqueId();
+        _thread_mem_tracker_mgr->detach_limiter_tracker();
     }
 
-    const std::string type() const;
+    const TaskType& type() const { return _type; }
+    const void set_type(const TaskType& type) { _type = type; }
     const std::string& task_id() const { return _task_id; }
-    const std::thread::id& thread_id() const { return _thread_id; }
+    const std::string& thread_id_str() const { return _thread_id; }
     const TUniqueId& fragment_instance_id() const { return _fragment_instance_id; }
 
+    std::string get_thread_id() {
+        std::stringstream ss;
+        ss << std::this_thread::get_id();
+        return ss.str();
+    }
+
+    // After _thread_mem_tracker_mgr is initialized, the current thread TCMalloc Hook starts to
+    // consume/release mem_tracker.
+    // Note that the use of shared_ptr will cause a crash. The guess is that there is an
+    // intermediate state during the copy construction of shared_ptr. Shared_ptr is not equal
+    // to nullptr, but the object it points to is not initialized. At this time, when the memory
+    // is released somewhere, the TCMalloc hook is triggered to cause the crash.
+    std::unique_ptr<ThreadMemTrackerMgr> _thread_mem_tracker_mgr;
+
 private:
-    std::thread::id _thread_id;
+    std::string _thread_id;
     TaskType _type;
     std::string _task_id;
     TUniqueId _fragment_instance_id;
 };
 
-// Using gcc11 compiles thread_local variable on lower versions of GLIBC will report an error,
-// see https://github.com/apache/incubator-doris/pull/7911
-//
-// If we want to avoid this error,
-// 1. For non-trivial variables in thread_local, such as std::string, you need to store them as pointers to
-//    ensure that thread_local is trivial, these non-trivial pointers will uniformly call destructors elsewhere.
-// 2. The default destructor of the thread_local variable cannot be overridden.
-//
-// This is difficult to implement. Because the destructor is not overwritten, it means that the outside cannot
-// be notified when the thread terminates, and the non-trivial pointers in thread_local cannot be released in time.
-// The func provided by pthread and std::thread doesn't help either.
-//
-// So, kudu Class-scoped static thread local implementation was introduced. Solve the above problem by
-// Thread-scopedthread local + Class-scoped thread local.
-//
-// This may look very trick, but it's the best way I can find.
-//
-// refer to:
-//  https://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Thread-Local.html
-//  https://stackoverflow.com/questions/12049684/
-//  https://sourceware.org/glibc/wiki/Destructor%20support%20for%20thread_local%20variables
-//  https://www.jianshu.com/p/756240e837dd
-//  https://man7.org/linux/man-pages/man3/pthread_tryjoin_np.3.html
-class ThreadContextPtr {
+static void update_bthread_context() {
+    if (btls_key != bthread_context_key) {
+        // pthread switch occurs, updating bthread_context and bthread_context_key cached in pthread tls.
+        bthread_context = static_cast<ThreadContext*>(bthread_getspecific(btls_key));
+        bthread_context_key = btls_key;
+    }
+}
+
+static ThreadContext* thread_context() {
+    if (btls_key != EMPTY_BTLS_KEY && bthread_context != nullptr) {
+        update_bthread_context();
+        return bthread_context;
+    } else {
+        return thread_context_ptr._ptr;
+    }
+}
+
+class AttachTask {
 public:
-    ThreadContextPtr();
+    explicit AttachTask(const std::shared_ptr<MemTrackerLimiter>& mem_tracker,
+                        const ThreadContext::TaskType& type = ThreadContext::TaskType::UNKNOWN,
+                        const std::string& task_id = "",
+                        const TUniqueId& fragment_instance_id = TUniqueId());
 
-    ThreadContext* get();
+    explicit AttachTask(RuntimeState* runtime_state);
+
+    const ThreadContext::TaskType query_to_task_type(const TQueryType::type& query_type) {
+        switch (query_type) {
+        case TQueryType::SELECT:
+            return ThreadContext::TaskType::QUERY;
+        case TQueryType::LOAD:
+            return ThreadContext::TaskType::LOAD;
+        default:
+            DCHECK(false);
+            return ThreadContext::TaskType::UNKNOWN;
+        }
+    }
+
+    ~AttachTask();
+};
+
+class AddThreadMemTrackerConsumer {
+public:
+    explicit AddThreadMemTrackerConsumer(NewMemTracker* mem_tracker);
+
+    ~AddThreadMemTrackerConsumer();
+};
+
+class UpdateMemExceedCallBack {
+public:
+    explicit UpdateMemExceedCallBack(const std::string& cancel_msg, bool cancel_task = true,
+                                     ExceedCallBack cb_func = nullptr);
+
+    ~UpdateMemExceedCallBack();
 
 private:
-    DECLARE_STATIC_THREAD_LOCAL(ThreadContext, thread_local_ctx);
+#ifdef USE_MEM_TRACKER
+    MemExceedCallBackInfo _old_cb;
+#endif
 };
 
-inline thread_local ThreadContextPtr thread_local_ctx;
-
-inline const std::string task_type_string(ThreadContext::TaskType type) {
-    switch (type) {
-    case ThreadContext::TaskType::QUERY:
-        return "QUERY";
-    case ThreadContext::TaskType::LOAD:
-        return "LOAD";
-    case ThreadContext::TaskType::COMPACTION:
-        return "COMPACTION";
-    default:
-        return "UNKNOWN";
-    }
-}
+class SwitchBthread {
+public:
+    explicit SwitchBthread();
 
-inline const std::string ThreadContext::type() const {
-    return task_type_string(_type);
-}
+    ~SwitchBthread();
+
+private:
+#ifdef USE_MEM_TRACKER
+    ThreadContext* _bthread_context;
+#endif
+};
 
-class AttachTaskThread {
+class StopCheckThreadMemTrackerLimit {
 public:
-    explicit AttachTaskThread(const ThreadContext::TaskType& type, const std::string& task_id = "",
-                              const TUniqueId& fragment_instance_id = TUniqueId()) {
-        thread_local_ctx.get()->attach(type, task_id, fragment_instance_id);
+    explicit StopCheckThreadMemTrackerLimit() {
+        thread_context()->_thread_mem_tracker_mgr->set_check_limit(false);
     }
 
-    ~AttachTaskThread() { thread_local_ctx.get()->detach(); }
+    ~StopCheckThreadMemTrackerLimit() {
+        thread_context()->_thread_mem_tracker_mgr->set_check_limit(true);
+    }
 };
 
+#define SCOPED_SWITCH_BTHREAD_TLS() auto VARNAME_LINENUM(switch_bthread) = SwitchBthread()
+
+// Attach to task when thread starts
+#define SCOPED_ATTACH_TASK(arg1, ...) \
+    auto VARNAME_LINENUM(attach_task) = AttachTask(arg1, ##__VA_ARGS__)
+
+#define STOP_CHECK_THREAD_MEM_TRACKER_LIMIT() \
+    auto VARNAME_LINENUM(stop_check_limit) = StopCheckThreadMemTrackerLimit()
+
+#define CONSUME_THREAD_MEM_TRACKER(size) \
+    doris::thread_context()->_thread_mem_tracker_mgr->consume(size)
+#define RELEASE_THREAD_MEM_TRACKER(size) \
+    doris::thread_context()->_thread_mem_tracker_mgr->consume(-size)
+#define THREAD_MEM_TRACKER_TRANSFER_TO(size, tracker) \
+    doris::thread_context()->_thread_mem_tracker_mgr->transfer_to(size, tracker)
+#define THREAD_MEM_TRACKER_TRANSFER_FROM(size, tracker) \
+    doris::thread_context()->_thread_mem_tracker_mgr->transfer_from(size, tracker)
+
 } // namespace doris
diff --git a/be/src/runtime/threadlocal.cc b/be/src/runtime/threadlocal.cc
index ac2bf2e62a..83e38e6a45 100644
--- a/be/src/runtime/threadlocal.cc
+++ b/be/src/runtime/threadlocal.cc
@@ -20,7 +20,6 @@
 
 #include <memory>
 #include <ostream>
-#include <string>
 
 #include "common/logging.h"
 #include "gutil/once.h"
diff --git a/be/src/runtime/threadlocal.h b/be/src/runtime/threadlocal.h
index a202815457..7f59c689bd 100644
--- a/be/src/runtime/threadlocal.h
+++ b/be/src/runtime/threadlocal.h
@@ -17,7 +17,7 @@
 
 // Reference from kudu, Solve the problem of gcc11 compiling
 // non-trivial thread_local variables on lower versions of GLIBC.
-// see https://github.com/apache/incubator-doris/pull/7911
+// see https://github.com/apache/doris/pull/7911
 //
 // Block-scoped static thread local implementation.
 //
diff --git a/be/src/runtime/thread_context.cpp b/be/src/service/brpc_conflict.h
similarity index 56%
copy from be/src/runtime/thread_context.cpp
copy to be/src/service/brpc_conflict.h
index 871cd1ebf0..35ef1b815c 100644
--- a/be/src/runtime/thread_context.cpp
+++ b/be/src/service/brpc_conflict.h
@@ -15,18 +15,34 @@
 // specific language governing permissions and limitations
 // under the License.
 
-#include "runtime/thread_context.h"
+#pragma once
 
-namespace doris {
+// This file is used to fixed macro conflict between butil and gutil
+// and this file must put the first include in source file
 
-DEFINE_STATIC_THREAD_LOCAL(ThreadContext, ThreadContextPtr, thread_local_ctx);
+#include "gutil/macros.h"
+// Macros in the guti/macros.h, use butil's define
+#ifdef DISALLOW_IMPLICIT_CONSTRUCTORS
+#undef DISALLOW_IMPLICIT_CONSTRUCTORS
+#endif
 
-ThreadContextPtr::ThreadContextPtr() {
-    INIT_STATIC_THREAD_LOCAL(ThreadContext, thread_local_ctx);
-}
+#ifdef arraysize
+#undef arraysize
+#endif
 
-ThreadContext* ThreadContextPtr::get() {
-    return thread_local_ctx;
-}
+#ifdef ARRAY_SIZE
+#undef ARRAY_SIZE
+#endif
 
-} // namespace doris
+#undef OVERRIDE
+#undef FINAL
+
+// use be/src/gutil/integral_types.h override butil/basictypes.h
+#include "gutil/integral_types.h"
+#ifdef BASE_INTEGRAL_TYPES_H_
+#define BUTIL_BASICTYPES_H_
+#endif
+
+#ifdef DEBUG_MODE
+#undef DEBUG_MODE
+#endif
diff --git a/be/src/service/doris_main.cpp b/be/src/service/doris_main.cpp
index 59fbdc8330..fdbf879f3e 100644
--- a/be/src/service/doris_main.cpp
+++ b/be/src/service/doris_main.cpp
@@ -51,6 +51,7 @@
 #include "runtime/exec_env.h"
 #include "runtime/heartbeat_flags.h"
 #include "service/backend_options.h"
+#include "runtime/memory/mem_tracker_task_pool.h"
 #include "service/backend_service.h"
 #include "service/brpc_service.h"
 #include "service/http_service.h"
@@ -395,6 +396,10 @@ int main(int argc, char** argv) {
         exit(-1);
     }
 
+    // init exec env
+    auto exec_env = doris::ExecEnv::GetInstance();
+    doris::ExecEnv::init(exec_env, paths);
+
     // init and open storage engine
     doris::EngineOptions options;
     options.store_paths = paths;
@@ -405,10 +410,6 @@ int main(int argc, char** argv) {
         LOG(FATAL) << "fail to open StorageEngine, res=" << st.get_error_msg();
         exit(-1);
     }
-
-    // init exec env
-    auto exec_env = doris::ExecEnv::GetInstance();
-    doris::ExecEnv::init(exec_env, paths);
     exec_env->set_storage_engine(engine);
     engine->set_heartbeat_flags(exec_env->heartbeat_flags());
 
@@ -477,6 +478,9 @@ int main(int argc, char** argv) {
         doris::MemInfo::refresh_current_mem();
 #endif
         doris::PerfCounters::refresh_proc_status();
+
+        // 1s clear the expired task mem tracker, a query mem tracker is about 57 bytes.
+        doris::ExecEnv::GetInstance()->task_pool_mem_tracker_registry()->logout_task_mem_tracker();
         sleep(1);
     }
 
diff --git a/be/src/service/internal_service.cpp b/be/src/service/internal_service.cpp
index c4c48a3c8b..2b9ee2fb3f 100644
--- a/be/src/service/internal_service.cpp
+++ b/be/src/service/internal_service.cpp
@@ -29,6 +29,8 @@
 #include "runtime/result_buffer_mgr.h"
 #include "runtime/routine_load/routine_load_task_executor.h"
 #include "runtime/runtime_state.h"
+#include "runtime/thread_context.h"
+#include "runtime/memory/mem_tracker_task_pool.h"
 #include "service/brpc.h"
 #include "util/brpc_client_cache.h"
 #include "util/md5.h"
@@ -42,6 +44,12 @@ namespace doris {
 
 DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(add_batch_task_queue_size, MetricUnit::NOUNIT);
 
+bthread_key_t btls_key;
+
+static void thread_context_deleter(void* d) {
+    delete static_cast<ThreadContext*>(d);
+}
+
 template <typename T>
 class NewHttpClosure : public ::google::protobuf::Closure {
 public:
@@ -69,11 +77,13 @@ PInternalServiceImpl<T>::PInternalServiceImpl(ExecEnv* exec_env)
         : _exec_env(exec_env), _tablet_worker_pool(config::number_tablet_writer_threads, 10240) {
     REGISTER_HOOK_METRIC(add_batch_task_queue_size,
                          [this]() { return _tablet_worker_pool.get_queue_size(); });
+    CHECK_EQ(0, bthread_key_create(&btls_key, thread_context_deleter));
 }
 
 template <typename T>
 PInternalServiceImpl<T>::~PInternalServiceImpl() {
     DEREGISTER_HOOK_METRIC(add_batch_task_queue_size);
+    CHECK_EQ(0, bthread_key_delete(btls_key));
 }
 
 template <typename T>
@@ -81,6 +91,7 @@ void PInternalServiceImpl<T>::transmit_data(google::protobuf::RpcController* cnt
                                             const PTransmitDataParams* request,
                                             PTransmitDataResult* response,
                                             google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     VLOG_ROW << "transmit data: fragment_instance_id=" << print_id(request->finst_id())
              << " node=" << request->node_id();
     brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);
@@ -94,6 +105,7 @@ void PInternalServiceImpl<T>::transmit_data_by_http(google::protobuf::RpcControl
                                                  const PEmptyRequest* request,
                                                  PTransmitDataResult* response,
                                                  google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     PTransmitDataParams* request_raw = new PTransmitDataParams();
     google::protobuf::Closure* done_raw =
             new NewHttpClosure<PTransmitDataParams>(request_raw, done);
@@ -109,12 +121,21 @@ void PInternalServiceImpl<T>::_transmit_data(google::protobuf::RpcController* cn
                                           google::protobuf::Closure* done,
                                           const Status& extract_st) {
     std::string query_id;
+    TUniqueId finst_id;
+    std::shared_ptr<MemTrackerLimiter> transmit_tracker;
     if (request->has_query_id()) {
         query_id = print_id(request->query_id());
-        TUniqueId finst_id;
         finst_id.__set_hi(request->finst_id().hi());
         finst_id.__set_lo(request->finst_id().lo());
+        // In some cases, query mem tracker does not exist in BE when transmit block, will get null pointer.
+        transmit_tracker = std::make_shared<MemTrackerLimiter>(
+                -1, fmt::format("QueryTransmit#queryId={}", query_id),
+                _exec_env->task_pool_mem_tracker_registry()->get_task_mem_tracker(query_id));
+    } else {
+        query_id = "unkown_transmit_data";
+        transmit_tracker = std::make_shared<MemTrackerLimiter>(-1, "unkown_transmit_data");
     }
+    SCOPED_ATTACH_TASK(transmit_tracker, ThreadContext::TaskType::QUERY, query_id, finst_id);
     VLOG_ROW << "transmit data: fragment_instance_id=" << print_id(request->finst_id())
              << " query_id=" << query_id << " node=" << request->node_id();
     // The response is accessed when done->Run is called in transmit_data(),
@@ -142,6 +163,7 @@ void PInternalServiceImpl<T>::tablet_writer_open(google::protobuf::RpcController
                                                  const PTabletWriterOpenRequest* request,
                                                  PTabletWriterOpenResult* response,
                                                  google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     VLOG_RPC << "tablet writer open, id=" << request->id() << ", index_id=" << request->index_id()
              << ", txn_id=" << request->txn_id();
     brpc::ClosureGuard closure_guard(done);
@@ -159,6 +181,7 @@ void PInternalServiceImpl<T>::exec_plan_fragment(google::protobuf::RpcController
                                                  const PExecPlanFragmentRequest* request,
                                                  PExecPlanFragmentResult* response,
                                                  google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     auto st = Status::OK();
     bool compact = request->has_compact() ? request->compact() : false;
@@ -184,6 +207,7 @@ void PInternalServiceImpl<T>::exec_plan_fragment_start(google::protobuf::RpcCont
                                                     const PExecPlanFragmentStartRequest* request,
                                                     PExecPlanFragmentResult* result,
                                                     google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     auto st = _exec_env->fragment_mgr()->start_query_execution(request);
     st.to_protobuf(result->mutable_status());
@@ -194,6 +218,7 @@ void PInternalServiceImpl<T>::tablet_writer_add_batch(google::protobuf::RpcContr
                                                    const PTabletWriterAddBatchRequest* request,
                                                    PTabletWriterAddBatchResult* response,
                                                    google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     _tablet_writer_add_batch(cntl_base, request, response, done);
 }
 
@@ -201,6 +226,7 @@ template <typename T>
 void PInternalServiceImpl<T>::tablet_writer_add_batch_by_http(
         google::protobuf::RpcController* cntl_base, const ::doris::PEmptyRequest* request,
         PTabletWriterAddBatchResult* response, google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     PTabletWriterAddBatchRequest* request_raw = new PTabletWriterAddBatchRequest();
     google::protobuf::Closure* done_raw =
             new NewHttpClosure<PTabletWriterAddBatchRequest>(request_raw, done);
@@ -255,6 +281,7 @@ void PInternalServiceImpl<T>::tablet_writer_cancel(google::protobuf::RpcControll
                                                    const PTabletWriterCancelRequest* request,
                                                    PTabletWriterCancelResult* response,
                                                    google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     VLOG_RPC << "tablet writer cancel, id=" << request->id() << ", index_id=" << request->index_id()
              << ", sender_id=" << request->sender_id();
     brpc::ClosureGuard closure_guard(done);
@@ -300,6 +327,7 @@ void PInternalServiceImpl<T>::cancel_plan_fragment(google::protobuf::RpcControll
                                                    const PCancelPlanFragmentRequest* request,
                                                    PCancelPlanFragmentResult* result,
                                                    google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     TUniqueId tid;
     tid.__set_hi(request->finst_id().hi());
@@ -324,6 +352,7 @@ template <typename T>
 void PInternalServiceImpl<T>::fetch_data(google::protobuf::RpcController* cntl_base,
                                          const PFetchDataRequest* request, PFetchDataResult* result,
                                          google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);
     GetResultBatchCtx* ctx = new GetResultBatchCtx(cntl, result, done);
     _exec_env->result_mgr()->fetch_data(request->finst_id(), ctx);
@@ -333,6 +362,7 @@ template <typename T>
 void PInternalServiceImpl<T>::get_info(google::protobuf::RpcController* controller,
                                        const PProxyRequest* request, PProxyResult* response,
                                        google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     // PProxyRequest is defined in gensrc/proto/internal_service.proto
     // Currently it supports 2 kinds of requests:
@@ -395,6 +425,7 @@ void PInternalServiceImpl<T>::update_cache(google::protobuf::RpcController* cont
                                            const PUpdateCacheRequest* request,
                                            PCacheResponse* response,
                                            google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     _exec_env->result_cache()->update(request, response);
 }
@@ -404,6 +435,7 @@ void PInternalServiceImpl<T>::fetch_cache(google::protobuf::RpcController* contr
                                           const PFetchCacheRequest* request,
                                           PFetchCacheResult* result,
                                           google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     _exec_env->result_cache()->fetch(request, result);
 }
@@ -413,6 +445,7 @@ void PInternalServiceImpl<T>::clear_cache(google::protobuf::RpcController* contr
                                           const PClearCacheRequest* request,
                                           PCacheResponse* response,
                                           google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     _exec_env->result_cache()->clear(request, response);
 }
@@ -422,6 +455,7 @@ void PInternalServiceImpl<T>::merge_filter(::google::protobuf::RpcController* co
                                            const ::doris::PMergeFilterRequest* request,
                                            ::doris::PMergeFilterResponse* response,
                                            ::google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     auto buf = static_cast<brpc::Controller*>(controller)->request_attachment();
     Status st = _exec_env->fragment_mgr()->merge_filter(request, buf.to_string().data());
@@ -436,6 +470,7 @@ void PInternalServiceImpl<T>::apply_filter(::google::protobuf::RpcController* co
                                            const ::doris::PPublishFilterRequest* request,
                                            ::doris::PPublishFilterResponse* response,
                                            ::google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     auto attachment = static_cast<brpc::Controller*>(controller)->request_attachment();
     UniqueId unique_id(request->query_id());
@@ -452,6 +487,7 @@ template <typename T>
 void PInternalServiceImpl<T>::send_data(google::protobuf::RpcController* controller,
                                         const PSendDataRequest* request, PSendDataResult* response,
                                         google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     TUniqueId fragment_instance_id;
     fragment_instance_id.hi = request->fragment_instance_id().hi();
@@ -475,6 +511,7 @@ template <typename T>
 void PInternalServiceImpl<T>::commit(google::protobuf::RpcController* controller,
                                      const PCommitRequest* request, PCommitResult* response,
                                      google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     TUniqueId fragment_instance_id;
     fragment_instance_id.hi = request->fragment_instance_id().hi();
@@ -493,6 +530,7 @@ template <typename T>
 void PInternalServiceImpl<T>::rollback(google::protobuf::RpcController* controller,
                                        const PRollbackRequest* request, PRollbackResult* response,
                                        google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     TUniqueId fragment_instance_id;
     fragment_instance_id.hi = request->fragment_instance_id().hi();
@@ -512,6 +550,7 @@ void PInternalServiceImpl<T>::fold_constant_expr(google::protobuf::RpcController
                                                  const PConstantExprRequest* request,
                                                  PConstantExprResult* response,
                                                  google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);
 
@@ -548,6 +587,7 @@ void PInternalServiceImpl<T>::transmit_block(google::protobuf::RpcController* cn
                                           const PTransmitDataParams* request,
                                           PTransmitDataResult* response,
                                           google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     // TODO(zxy) delete in 1.2 version
     brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);
     attachment_transfer_request_block<PTransmitDataParams>(request, cntl);
@@ -560,6 +600,7 @@ void PInternalServiceImpl<T>::transmit_block_by_http(google::protobuf::RpcContro
                                                   const PEmptyRequest* request,
                                                   PTransmitDataResult* response,
                                                   google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     PTransmitDataParams* request_raw = new PTransmitDataParams();
     google::protobuf::Closure* done_raw =
             new NewHttpClosure<PTransmitDataParams>(request_raw, done);
@@ -575,12 +616,21 @@ void PInternalServiceImpl<T>::_transmit_block(google::protobuf::RpcController* c
                                            google::protobuf::Closure* done,
                                            const Status& extract_st) {
     std::string query_id;
+    TUniqueId finst_id;
+    std::shared_ptr<MemTrackerLimiter> transmit_tracker;
     if (request->has_query_id()) {
         query_id = print_id(request->query_id());
-        TUniqueId finst_id;
         finst_id.__set_hi(request->finst_id().hi());
         finst_id.__set_lo(request->finst_id().lo());
+        // In some cases, query mem tracker does not exist in BE when transmit block, will get null pointer.
+        transmit_tracker = std::make_shared<MemTrackerLimiter>(
+                -1, fmt::format("QueryTransmit#queryId={}", query_id),
+                _exec_env->task_pool_mem_tracker_registry()->get_task_mem_tracker(query_id));
+    } else {
+        query_id = "unkown_transmit_block";
+        transmit_tracker = std::make_shared<MemTrackerLimiter>(-1, "unkown_transmit_block");
     }
+    SCOPED_ATTACH_TASK(transmit_tracker, ThreadContext::TaskType::QUERY, query_id, finst_id);
     VLOG_ROW << "transmit block: fragment_instance_id=" << print_id(request->finst_id())
              << " query_id=" << query_id << " node=" << request->node_id();
     // The response is accessed when done->Run is called in transmit_block(),
@@ -608,6 +658,7 @@ void PInternalServiceImpl<T>::check_rpc_channel(google::protobuf::RpcController*
                                                 const PCheckRPCChannelRequest* request,
                                                 PCheckRPCChannelResponse* response,
                                                 google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     response->mutable_status()->set_status_code(0);
     if (request->data().size() != request->size()) {
@@ -635,6 +686,7 @@ void PInternalServiceImpl<T>::reset_rpc_channel(google::protobuf::RpcController*
                                                 const PResetRPCChannelRequest* request,
                                                 PResetRPCChannelResponse* response,
                                                 google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     response->mutable_status()->set_status_code(0);
     if (request->all()) {
@@ -669,6 +721,7 @@ void PInternalServiceImpl<T>::hand_shake(google::protobuf::RpcController* cntl_b
                                          const PHandShakeRequest* request,
                                          PHandShakeResponse* response,
                                          google::protobuf::Closure* done) {
+    SCOPED_SWITCH_BTHREAD_TLS();
     brpc::ClosureGuard closure_guard(done);
     if (request->has_hello()) {
         response->set_hello(request->hello());
diff --git a/be/src/util/file_utils.cpp b/be/src/util/file_utils.cpp
index dd31a04da5..f0e12fb3ab 100644
--- a/be/src/util/file_utils.cpp
+++ b/be/src/util/file_utils.cpp
@@ -34,6 +34,7 @@
 #include "gutil/strings/strip.h"
 #include "gutil/strings/substitute.h"
 #include "olap/file_helper.h"
+#include "runtime/thread_context.h"
 #include "util/defer_op.h"
 
 namespace doris {
@@ -201,11 +202,13 @@ Status FileUtils::md5sum(const std::string& file, std::string* md5sum) {
         return Status::InternalError("failed to stat file");
     }
     size_t file_len = statbuf.st_size;
+    CONSUME_THREAD_MEM_TRACKER(file_len);
     void* buf = mmap(0, file_len, PROT_READ, MAP_SHARED, fd, 0);
 
     unsigned char result[MD5_DIGEST_LENGTH];
     MD5((unsigned char*)buf, file_len, result);
     munmap(buf, file_len);
+    RELEASE_THREAD_MEM_TRACKER(file_len);
 
     std::stringstream ss;
     for (int32_t i = 0; i < MD5_DIGEST_LENGTH; i++) {
diff --git a/be/src/vec/common/allocator.h b/be/src/vec/common/allocator.h
index d1f748d5b9..ef55a630a8 100644
--- a/be/src/vec/common/allocator.h
+++ b/be/src/vec/common/allocator.h
@@ -20,7 +20,6 @@
 
 #pragma once
 
-// TODO: Tracker
 // TODO: Readable
 
 #include <fmt/format.h>
@@ -29,6 +28,7 @@
 #include <exception>
 
 #include "common/status.h"
+#include "runtime/thread_context.h"
 
 #ifdef NDEBUG
 #define ALLOCATOR_ASLR 0
@@ -137,15 +137,18 @@ public:
         } else if (old_size >= MMAP_THRESHOLD && new_size >= MMAP_THRESHOLD) {
             /// Resize mmap'd memory region.
             // CurrentMemoryTracker::realloc(old_size, new_size);
+            CONSUME_THREAD_MEM_TRACKER(new_size - old_size);
 
             // On apple and freebsd self-implemented mremap used (common/mremap.h)
             buf = clickhouse_mremap(buf, old_size, new_size, MREMAP_MAYMOVE, PROT_READ | PROT_WRITE,
                                     mmap_flags, -1, 0);
-            if (MAP_FAILED == buf)
+            if (MAP_FAILED == buf){
+                RELEASE_THREAD_MEM_TRACKER(new_size - old_size);
                 doris::vectorized::throwFromErrno("Allocator: Cannot mremap memory chunk from " +
                                                           std::to_string(old_size) + " to " +
                                                           std::to_string(new_size) + ".",
                                                   doris::TStatusCode::VEC_CANNOT_MREMAP);
+            }
 
             /// No need for zero-fill, because mmap guarantees it.
 
@@ -204,10 +207,13 @@ private:
                                 alignment, size),
                         doris::TStatusCode::VEC_BAD_ARGUMENTS);
 
+            CONSUME_THREAD_MEM_TRACKER(size);
             buf = mmap(get_mmap_hint(), size, PROT_READ | PROT_WRITE, mmap_flags, -1, 0);
-            if (MAP_FAILED == buf)
+            if (MAP_FAILED == buf){
+                RELEASE_THREAD_MEM_TRACKER(size);
                 doris::vectorized::throwFromErrno(fmt::format("Allocator: Cannot mmap {}.", size),
                                                   doris::TStatusCode::VEC_CANNOT_ALLOCATE_MEMORY);
+            }
 
             /// No need for zero-fill, because mmap guarantees it.
         } else {
@@ -238,9 +244,12 @@ private:
 
     void free_no_track(void* buf, size_t size) {
         if (size >= MMAP_THRESHOLD) {
-            if (0 != munmap(buf, size))
+            if (0 != munmap(buf, size)) {
                 doris::vectorized::throwFromErrno(fmt::format("Allocator: Cannot munmap {}.", size),
                                                   doris::TStatusCode::VEC_CANNOT_MUNMAP);
+            } else {
+                RELEASE_THREAD_MEM_TRACKER(size);
+            }
         } else {
             ::free(buf);
         }
diff --git a/be/src/vec/exec/join/vhash_join_node.cpp b/be/src/vec/exec/join/vhash_join_node.cpp
index efab21aaf1..e6aa53b1da 100644
--- a/be/src/vec/exec/join/vhash_join_node.cpp
+++ b/be/src/vec/exec/join/vhash_join_node.cpp
@@ -1077,6 +1077,7 @@ Status HashJoinNode::open(RuntimeState* state) {
 
 Status HashJoinNode::_hash_table_build(RuntimeState* state) {
     RETURN_IF_ERROR(child(1)->open(state));
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Hash join, while constructing the hash table.");
     SCOPED_TIMER(_build_timer);
     MutableBlock mutable_block(child(1)->row_desc().tuple_descriptors());
 
@@ -1095,7 +1096,6 @@ Status HashJoinNode::_hash_table_build(RuntimeState* state) {
         RETURN_IF_ERROR(child(1)->get_next(state, &block, &eos));
         _mem_tracker->Consume(block.allocated_bytes());
         _mem_used += block.allocated_bytes();
-        RETURN_IF_LIMIT_EXCEEDED(state, "Hash join, while getting next from the child 1.");
 
         if (block.rows() != 0) {
             mutable_block.merge(block);
@@ -1111,7 +1111,6 @@ Status HashJoinNode::_hash_table_build(RuntimeState* state) {
             // TODO:: Rethink may we should do the proess after we recevie all build blocks ?
             // which is better.
             RETURN_IF_ERROR(_process_build_block(state, _build_blocks[index], index));
-            RETURN_IF_LIMIT_EXCEEDED(state, "Hash join, while constructing the hash table.");
 
             mutable_block = MutableBlock();
             ++index;
@@ -1128,7 +1127,6 @@ Status HashJoinNode::_hash_table_build(RuntimeState* state) {
         _build_blocks.emplace_back(mutable_block.to_block());
         RETURN_IF_ERROR(_process_build_block(state, _build_blocks[index], index));
     }
-    RETURN_IF_LIMIT_EXCEEDED(state, "Hash join, while constructing the hash table.");
 
     return std::visit(
             [&](auto&& arg) -> Status {
diff --git a/be/src/vec/exec/vaggregation_node.cpp b/be/src/vec/exec/vaggregation_node.cpp
index 172a194c47..5907d3c802 100644
--- a/be/src/vec/exec/vaggregation_node.cpp
+++ b/be/src/vec/exec/vaggregation_node.cpp
@@ -351,6 +351,7 @@ Status AggregationNode::prepare(RuntimeState* state) {
 Status AggregationNode::open(RuntimeState* state) {
     RETURN_IF_ERROR(ExecNode::open(state));
     SCOPED_TIMER(_runtime_profile->total_time_counter());
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("aggregator, while execute open.");
 
     RETURN_IF_ERROR(VExpr::open(_probe_expr_ctxs, state));
 
@@ -374,7 +375,6 @@ Status AggregationNode::open(RuntimeState* state) {
         }
         RETURN_IF_ERROR(_executor.execute(&block));
         _executor.update_memusage();
-        RETURN_IF_LIMIT_EXCEEDED(state, "aggregator, while execute open.");
     }
 
     return Status::OK();
@@ -386,6 +386,7 @@ Status AggregationNode::get_next(RuntimeState* state, RowBatch* row_batch, bool*
 
 Status AggregationNode::get_next(RuntimeState* state, Block* block, bool* eos) {
     SCOPED_TIMER(_runtime_profile->total_time_counter());
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("aggregator, while execute get_next.");
 
     if (_is_streaming_preagg) {
         bool child_eos = false;
@@ -414,7 +415,6 @@ Status AggregationNode::get_next(RuntimeState* state, Block* block, bool* eos) {
     }
 
     _executor.update_memusage();
-    RETURN_IF_LIMIT_EXCEEDED(state, "aggregator, while execute get_next.");
     return Status::OK();
 }
 
diff --git a/be/src/vec/exec/vblocking_join_node.cpp b/be/src/vec/exec/vblocking_join_node.cpp
index af1adb957e..9e7ccc82a2 100644
--- a/be/src/vec/exec/vblocking_join_node.cpp
+++ b/be/src/vec/exec/vblocking_join_node.cpp
@@ -67,6 +67,7 @@ Status VBlockingJoinNode::close(RuntimeState* state) {
 }
 
 void VBlockingJoinNode::build_side_thread(RuntimeState* state, std::promise<Status>* status) {
+    SCOPED_ATTACH_TASK(state);
     status->set_value(construct_build_side(state));
     // Release the thread token as soon as possible (before the main thread joins
     // on it).  This way, if we had a chain of 10 joins using 1 additional thread,
diff --git a/be/src/vec/exec/vcross_join_node.cpp b/be/src/vec/exec/vcross_join_node.cpp
index 6d48527f73..4c79355326 100644
--- a/be/src/vec/exec/vcross_join_node.cpp
+++ b/be/src/vec/exec/vcross_join_node.cpp
@@ -52,6 +52,7 @@ Status VCrossJoinNode::close(RuntimeState* state) {
 Status VCrossJoinNode::construct_build_side(RuntimeState* state) {
     // Do a full scan of child(1) and store all build row batches.
     RETURN_IF_ERROR(child(1)->open(state));
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Vec Cross join, while getting next from the child 1");
 
     bool eos = false;
     while (true) {
@@ -69,8 +70,6 @@ Status VCrossJoinNode::construct_build_side(RuntimeState* state) {
             _build_blocks.emplace_back(std::move(block));
             _mem_tracker->Consume(mem_usage);
         }
-        // to prevent use too many memory
-        RETURN_IF_LIMIT_EXCEEDED(state, "Cross join, while getting next from the child 1.");
 
         if (eos) {
             break;
diff --git a/be/src/vec/exec/volap_scan_node.cpp b/be/src/vec/exec/volap_scan_node.cpp
index 33e208808a..343d670fd9 100644
--- a/be/src/vec/exec/volap_scan_node.cpp
+++ b/be/src/vec/exec/volap_scan_node.cpp
@@ -36,6 +36,7 @@ VOlapScanNode::VOlapScanNode(ObjectPool* pool, const TPlanNode& tnode, const Des
 
 void VOlapScanNode::transfer_thread(RuntimeState* state) {
     // scanner open pushdown to scanThread
+    SCOPED_ATTACH_TASK(state);
     Status status = Status::OK();
 
     if (_vconjunct_ctx_ptr) {
@@ -138,6 +139,7 @@ void VOlapScanNode::transfer_thread(RuntimeState* state) {
 }
 
 void VOlapScanNode::scanner_thread(VOlapScanner* scanner) {
+    SCOPED_ATTACH_TASK(_runtime_state);
     int64_t wait_time = scanner->update_wait_worker_timer();
     // Do not use ScopedTimer. There is no guarantee that, the counter
     // (_scan_cpu_timer, the class member) is not destroyed after `_running_thread==0`.
diff --git a/be/src/vec/exec/vset_operation_node.cpp b/be/src/vec/exec/vset_operation_node.cpp
index 63a1ccbc16..44c1638463 100644
--- a/be/src/vec/exec/vset_operation_node.cpp
+++ b/be/src/vec/exec/vset_operation_node.cpp
@@ -227,6 +227,7 @@ void VSetOperationNode::hash_table_init() {
 //build a hash table from child(0)
 Status VSetOperationNode::hash_table_build(RuntimeState* state) {
     RETURN_IF_ERROR(child(0)->open(state));
+    SCOPED_UPDATE_MEM_EXCEED_CALL_BACK("Vec Set Operation Node, while constructing the hash table");
     Block block;
     MutableBlock mutable_block(child(0)->row_desc().tuple_descriptors());
 
@@ -243,7 +244,6 @@ Status VSetOperationNode::hash_table_build(RuntimeState* state) {
         _mem_tracker->Consume(allocated_bytes);
         _mem_used += allocated_bytes;
 
-        RETURN_IF_LIMIT_EXCEEDED(state, "Set Operation Node, while getting next from the child 0.");
         if (block.rows() != 0) { mutable_block.merge(block); }
 
         // make one block for each 4 gigabytes
@@ -253,7 +253,6 @@ Status VSetOperationNode::hash_table_build(RuntimeState* state) {
             // TODO:: Rethink may we should do the proess after we recevie all build blocks ?
             // which is better.
             RETURN_IF_ERROR(process_build_block(_build_blocks[index], index));
-            RETURN_IF_LIMIT_EXCEEDED(state, "Set Operation Node, while constructing the hash table.");
             mutable_block = MutableBlock();
             ++index;
             last_mem_used = _mem_used;
@@ -262,7 +261,6 @@ Status VSetOperationNode::hash_table_build(RuntimeState* state) {
 
     _build_blocks.emplace_back(mutable_block.to_block());
     RETURN_IF_ERROR(process_build_block(_build_blocks[index], index));
-    RETURN_IF_LIMIT_EXCEEDED(state, "Set Operation Node, while constructing the hash table.");
     return Status::OK();
 }
 
diff --git a/be/src/vec/runtime/vdata_stream_recvr.cpp b/be/src/vec/runtime/vdata_stream_recvr.cpp
index 24244312cc..14630c2533 100644
--- a/be/src/vec/runtime/vdata_stream_recvr.cpp
+++ b/be/src/vec/runtime/vdata_stream_recvr.cpp
@@ -90,6 +90,9 @@ Status VDataStreamRecvr::SenderQueue::get_batch(Block** next_block) {
 void VDataStreamRecvr::SenderQueue::add_block(const PBlock& pblock, int be_number,
                                               int64_t packet_seq,
                                               ::google::protobuf::Closure** done) {
+    // Avoid deadlock when calling SenderQueue::cancel() in tcmalloc hook,
+    // limit memory via DataStreamRecvr::exceeds_limit.
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
     std::lock_guard<std::mutex> l(_lock);
     if (_is_cancelled) {
         return;
@@ -140,6 +143,9 @@ void VDataStreamRecvr::SenderQueue::add_block(const PBlock& pblock, int be_numbe
 }
 
 void VDataStreamRecvr::SenderQueue::add_block(Block* block, bool use_move) {
+    // Avoid deadlock when calling SenderQueue::cancel() in tcmalloc hook,
+    // limit memory via DataStreamRecvr::exceeds_limit.
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
     std::unique_lock<std::mutex> l(_lock);
     if (_is_cancelled) {
         return;
diff --git a/be/src/vec/sink/result_sink.cpp b/be/src/vec/sink/result_sink.cpp
index e3db9fef32..d34927c5f7 100644
--- a/be/src/vec/sink/result_sink.cpp
+++ b/be/src/vec/sink/result_sink.cpp
@@ -99,6 +99,9 @@ Status VResultSink::send(RuntimeState* state, RowBatch* batch) {
 }
 
 Status VResultSink::send(RuntimeState* state, Block* block) {
+    // The memory consumption in the process of sending the results is not check query memory limit.
+    // Avoid the query being cancelled when the memory limit is reached after the query result comes out.
+    STOP_CHECK_THREAD_MEM_TRACKER_LIMIT();
     return _writer->append_block(*block);
 }
 
diff --git a/build.sh b/build.sh
index 04be3879ae..c58dfc61bc 100755
--- a/build.sh
+++ b/build.sh
@@ -219,7 +219,9 @@ fi
 if [[ -z ${STRIP_DEBUG_INFO} ]]; then
     STRIP_DEBUG_INFO=OFF
 fi
-
+if [[ -z ${USE_MEM_TRACKER} ]]; then
+    USE_MEM_TRACKER=ON
+fi
 if [[ -z ${STRICT_MEMORY_USE} ]]; then
     STRICT_MEMORY_USE=OFF
 fi
@@ -241,6 +243,7 @@ echo "Get params:
     BUILD_META_TOOL     -- $BUILD_META_TOOL
     USE_LLD             -- $USE_LLD
     STRIP_DEBUG_INFO    -- $STRIP_DEBUG_INFO
+    USE_MEM_TRACKER     -- $USE_MEM_TRACKER
     STRICT_MEMORY_USE   -- $STRICT_MEMORY_USE
 "
 
@@ -278,6 +281,7 @@ if [ ${BUILD_BE} -eq 1 ] ; then
             -DBUILD_META_TOOL=${BUILD_META_TOOL} \
             -DUSE_LLD=${USE_LLD} \
             -DSTRIP_DEBUG_INFO=${STRIP_DEBUG_INFO} \
+            -DUSE_MEM_TRACKER=${USE_MEM_TRACKER} \
             -DSTRICT_MEMORY_USE=${STRICT_MEMORY_USE} \
             -DUSE_AVX2=${USE_AVX2} \
             -DGLIBC_COMPATIBILITY=${GLIBC_COMPATIBILITY} ../
diff --git a/gensrc/proto/types.proto b/gensrc/proto/types.proto
index aaa2a70771..e1f8445620 100644
--- a/gensrc/proto/types.proto
+++ b/gensrc/proto/types.proto
@@ -222,4 +222,5 @@ enum PPlanFragmentCancelReason {
     INTERNAL_ERROR = 3;
     TIMEOUT = 4;
     CALL_RPC_ERROR = 5;
+    MEMORY_LIMIT_EXCEED = 6;
 }
diff --git a/run-be-ut.sh b/run-be-ut.sh
index 930c013918..a6af60e3da 100755
--- a/run-be-ut.sh
+++ b/run-be-ut.sh
@@ -142,6 +142,7 @@ ${CMAKE_CMD} -G "${GENERATOR}" \
     -DBUILD_META_TOOL=OFF \
     -DWITH_MYSQL=OFF \
     -DWITH_KERBEROS=OFF \
+    -DUSE_MEM_TRACKER=ON \
     -DSTRICT_MEMORY_USE=OFF \
     ${CMAKE_USE_CCACHE} ../
 ${BUILD_SYSTEM} -j ${PARALLEL} $RUN_FILE


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org