Mafiree logo
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
Schedule a Call
Menu
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
  • Schedule a Call
Database
Database Managed Database Services
MySQL MySQL
MySQL Consulting
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB MongoDB
MongoDB Consulting
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL PostgreSQL
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
SQL Server MSSQL
MSSQL Consulting
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Aerospike
Aerospike Consulting
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Database Administration
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
Clickhouse Clickhouse
ClickHouse Consulting
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB TiDB
TiDB Consulting
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB ScyllaDB
ScyllaDB Consulting
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
DevOps
DevOps DevOps Services
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Networking
Networking Networking Services
Basic Basic
Advanced Advanced
MySQL MySQL
MongoDB MongoDB
PostgreSQL PostgreSQL
MSSQL MSSQL
Aerospike Aerospike
Clickhouse Clickhouse
TiDB TiDB
ScyllaDB ScyllaDB
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Basic Basic
Advanced Advanced
MySQL Consulting
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB Consulting
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
MSSQL Consulting
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Consulting
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Database Administration
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
ClickHouse Consulting
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB Consulting
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB Consulting
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
  1. Home
  2. > Blogs
  3. > TiDB
  4. > TiDB Out of Memory (OOM) Errors: Root Cause Analysis & Memory Tuning Guide

TiDB Out of Memory (OOM) Errors: Root Cause Analysis & Memory Tuning Guide

TiDB OOM Errors fall into two types — a full node crash triggered by the OS, or a single query cancelled by TiDB's own memory controls. This guide walks through how to confirm which occurred, identify the SQL patterns most responsible (HashJoin, HashAgg, large transactions, stale statistics), configure the four key memory parameters, enable disk spill as a safety net, and verify production readiness with a structured checklist.

Abishek S August 26, 2026

Subscribe for email updates

Summarize with AI: ChatGPT Google AI Perplexity Claude Grok

TiDB OOM Errors tend to strike at the worst possible time — during peak traffic, a large data migration, or at 2 AM when no one is watching. The immediate fix is usually simple: restart TiDB. The harder part is troubleshooting TiDB out of memory conditions well enough to understand what actually caused the OOM and making sure it does not happen again.

This guide explains how TiDB uses memory, what causes OOM conditions, how to diagnose them, and which configuration parameters and SQL patterns can help prevent future incidents. For the authoritative reference, see PingCAP's official TiDB memory control documentation.

80%
default memory limit before TiDB starts killing queries
1GB
default per-query memory quota
50+
events retained for post-incident analysis
?
Dealing with a TiDB OOM error right now? Mafiree's TiDB team offers 24×7 incident support to stabilize a crashing cluster before you dig into root cause. Contact Mafiree.

Not sure where to start?

Repeated OOM incidents usually point to something deeper than a single bad query. Common contributing factors include:

  • Undersized hardware
  • Missing memory limits
  • Excessive query concurrency
  • Poor query plans
  • Large transactions
  • Stale table statistics
  • Memory-heavy SQL operators

Mafiree's TiDB Performance and Query Optimization Services can help identify the root cause through configuration reviews, query optimization, and performance audits.

There Are Two Different TiDB OOM Situations

Before troubleshooting an OOM event, determine which type of OOM occurred. The response is different depending on whether the operating system killed TiDB or whether TiDB cancelled an individual query.

1. The Node Crashes
Mar 14 kernel: tidb-server invoked oom-killer
Mar 14 kernel: Kill process 21945 (tidb-server)

The operating system ran out of available memory and killed the TiDB process — active connections drop, running queries terminate, and TiDB restarts. Applications may see connection failures in the meantime. This is the more serious type of OOM, since the entire server process is affected.

2. A Query Gets Cancelled
ERROR 1105 (HY000):
Out Of Memory Quota!
[conn_id=54]

TiDB's internal memory controller terminated the query before the server itself ran out of memory. The node stays healthy — this is the protection mechanism working as designed. Still worth investigating why the query needed that much memory, but it's a fundamentally different problem than a server crash.

How TiDB Memory Controls Work

Where TiDB's Memory Controls Actually Kick In
0%25%50%75%100%
0–70% Normal operating range.
70–80% Good point for early-warning alerts — set tidb_memory_usage_alarm_ratio to 0.7 here.
80%+ Default tidb_server_memory_limit threshold.
SQL
SET GLOBAL tidb_memory_usage_alarm_ratio = 0.7;

This allows TiDB to warn you before memory usage reaches a critical level.

First: Confirm What Actually Happened

Before changing any configuration, confirm whether the OOM was caused by the operating system or TiDB's own memory manager.

Check the OS logs for oom-killer activity

This tells you whether the Linux kernel killed the TiDB process.

BASH
dmesg -T | grep tidb-server

If the kernel killed TiDB, you'll see something like this:

Mar 14 16:55:03 localhost kernel: tidb-server invoked oom-killer
Mar 14 16:55:03 localhost kernel: Out of memory: Kill process 21945 (tidb-server)
Mar 14 16:55:03 localhost kernel: Killed process 21945

This confirms that the OS terminated the process.

Confirm the restart in tidb.log

This line means TiDB restarted — it's a useful timestamp anchor for identifying when it happened.

[INFO] [printer.go:33] ["Welcome to TiDB."]
Cross-check against Grafana

On TiDB → Server → Memory Usage, watching memory over time is one of the fastest ways to confirm a restart: a pattern that gradually increases, suddenly drops to zero, and then starts increasing again usually indicates a process restart.

What Usually Causes TiDB OOM Errors?

Most TiDB OOM errors stem from one or more of the following causes.

CauseWhat's happeningHow it shows upHow often
Memory-heavy queries Large intermediate result sets consume RAM One query uses several GB Most common
Too many concurrent sessions Multiple queries collectively exceed available memory Spikes during peak traffic Common
Memory not being released Memory gradually grows over time Slow upward trend Occasional
Under-provisioned deployment Insufficient system RAM OOM even under light load Less common

The first two causes are responsible for a large proportion of production OOM events.

SQL Patterns That Consume Large Amounts of Memory

Configuration changes can help, but they cannot completely protect a fundamentally expensive query. TiDB query optimization at the SQL level is often the real fix — the following patterns commonly appear in OOM post-mortems.

1. HashJoin Against a Large Table

A HashJoin loads the inner side of the join into an in-memory hash table before it starts matching rows. If the inner table has millions of rows, a single query can consume several gigabytes of memory. Run EXPLAIN and look for a HashJoin with a very large estRows on the inner side. If you see it, consider hinting toward MergeJoin instead — it uses far less memory because it works with sorted streams rather than building a large in-memory hash table.

SQL
-- check what the planner chose
EXPLAIN SELECT * FROM orders JOIN order_items ON orders.id = order_items.order_id;
-- if HashJoin shows estRows in the millions on the inner side, that's the problem

-- nudge it toward a less memory-hungry join
SELECT /*+ MERGE_JOIN(orders, order_items) */
  orders.id, order_items.quantity
FROM orders
JOIN order_items ON orders.id = order_items.order_id
WHERE orders.created_at > '2024-01-01';

Expert Tip: Spotting one bad HashJoin is easy. Finding every query in a busy cluster that's quietly doing this is a different problem entirely — it usually needs systematic plan review across your TiDB slow query log, not a one-off EXPLAIN. Mafiree's TiDB team does exactly this kind of audit if you'd rather not chase it query by query.

2. HashAgg on Large Grouped Datasets

HashAgg is fast because it can process data in parallel, but each worker may maintain its own hash table. With a large number of distinct grouping values, memory usage can grow rapidly. StreamAgg processes rows in sorted order and generally uses less memory — a reasonable trade-off for memory-constrained workloads.

SQL
SELECT /*+ STREAM_AGG() */ region, SUM(revenue)
FROM sales
GROUP BY region;

3. Stale Statistics Causing Bad Query Plans

If TiDB's statistics are outdated, the optimizer might estimate 1,000 rows for a scan that actually returns 10 million, and pick algorithms suited for a small dataset. Check the health of your statistics regularly, especially on tables that get a lot of writes:

SQL
SHOW STATS_HEALTHY;

-- for high-write tables, refresh statistics when necessary
ANALYZE TABLE orders;
ANALYZE TABLE order_items;

Stale statistics can lead to bad plans, and bad plans can directly contribute to excessive memory usage.

4. Large Transactions Holding Too Much Memory

TiDB's transaction model caches all write operations in memory before commit. A transaction modifying millions of rows may consume two to three times — or potentially more — than the actual size of the data involved. Break large bulk operations into smaller batches, or look at the tidb_dml_type variable (set to "bulk") or non-transactional DML for cases that specifically need this.

SQL
-- instead of one giant delete:
-- DELETE FROM logs WHERE created_at < '2024-01-01';

-- loop this until affected rows = 0, sleep briefly between rounds
DELETE FROM logs
WHERE created_at < '2024-01-01'
LIMIT 10000;
A 50–100ms sleep between batches gives TiDB time to release memory from the previous operation before starting the next one. It's worth it.

TiDB Memory Parameters Worth Configuring

TiDB memory protection works in layers — per-query limits, per-instance memory limits, and operating-system or cgroup limits. Each layer should be configured deliberately as part of any TiDB memory tuning strategy; relying on the defaults in production is risky.

?️
Defaults aren't tuning Getting these right for your specific hardware and workload is the difference between a cluster that occasionally throttles a query and one that occasionally falls over. Mafiree's TiDB administration and maintenance team can review and tune this alongside you before it's a production incident.
tidb_mem_quota_query default: 1 GB · session / global

The maximum memory a single SQL query can consume. Analytical queries may require more, but raise this carefully — multiple queries can consume memory concurrently.

tidb_mem_oom_action default: CANCEL · session / global

What TiDB does when a query exceeds its memory quota. With CANCEL, TiDB terminates the query and returns an error — the right choice for production. LOG allows the query to continue while logging the event, which may be useful temporarily for investigation but is not recommended as a permanent production setting.

tidb_server_memory_limit default: 80% of system memory · v6.5.0+

The total memory budget for the TiDB server process. The default 80% may be unsuitable when TiDB shares a server with other database services, monitoring agents, backup processes, or general operating-system workloads. In hybrid deployments, an explicit memory limit is strongly recommended.

tidb_memory_usage_alarm_ratio default: 0.8 · global

Controls when TiDB generates memory usage warnings and starts collecting diagnostic information. Setting it to 0.7 gives you a chance to investigate before memory usage reaches a critical level.

TiDB Disk Spill: Let TiDB Use Disk Instead of RAM

TiDB supports spilling intermediate execution data to disk when memory pressure becomes high. Disk spill behavior is controlled by tidb_mem_quota_query, tidb_enable_tmp_storage_on_oom, tmp-storage-path, and tmp-storage-quota.

Disk spill support has expanded across TiDB versions — HashAgg spill support, in particular, has improved in newer releases. When running a modern TiDB version, verify the exact behavior for your release.

Recommended Practice: Configure a dedicated temporary storage path explicitly with tmp-storage-path. This provides additional protection against memory-heavy queries. However, disk spill should be treated as a safety mechanism, not a replacement for query optimization.

View TiDB Memory Usage Through INFORMATION_SCHEMA

TiDB provides memory-related system tables for monitoring current and historical memory usage. To view current and historical memory usage, query:

  • INFORMATION_SCHEMA.MEMORY_USAGE
  • INFORMATION_SCHEMA.CLUSTER_MEMORY_USAGE
  • INFORMATION_SCHEMA.MEMORY_USAGE_OPS_HISTORY
  • INFORMATION_SCHEMA.CLUSTER_MEMORY_USAGE_OPS_HISTORY

The OPS_HISTORY tables retain the latest 50 records per instance. These tables are useful for identifying which operations consumed memory and investigating OOM events after they occur.

Production Readiness Checklist

Before putting a TiDB cluster into production, verify the following.

Memory Configuration

  • Set tidb_server_memory_limit explicitly
  • Configure tidb_mem_quota_query based on workload
  • Ensure tidb_mem_oom_action is set to CANCEL
  • Set tidb_memory_usage_alarm_ratio to an appropriate early-warning threshold

Query Optimization

  • Review expensive queries using EXPLAIN ANALYZE
  • Check for large HashJoin operations
  • Review large HashAgg operations
  • Refresh stale table statistics
  • Monitor memory usage for high-memory queries

Transaction Management

  • Batch large DELETE operations
  • Batch large UPDATE operations
  • Avoid transactions that modify millions of rows unnecessarily
  • Evaluate bulk or non-transactional DML where appropriate

TiDB Disk Spill

  • Configure a dedicated temporary storage path
  • Ensure sufficient disk space
  • Monitor disk spill and temporary storage usage

Infrastructure

  • Avoid running TiDB on undersized infrastructure
  • Account for memory used by other services
  • Use resource controls in hybrid deployments
  • Configure appropriate cgroup memory boundaries

Conclusion

TiDB OOM errors are rarely random. They're the predictable result of specific SQL patterns, undersized memory limits, or configuration defaults that don't match your workload. Confirming whether the operating system or TiDB's own memory manager caused the event is the first step in troubleshooting any recurring OOM pattern — from there, tuning tidb_mem_quota_query and tidb_server_memory_limit for your hardware, applying targeted query optimization to the worst offenders, and enabling disk spill as a safety net will prevent most repeat incidents.

For TiDB out of memory issues you can't fully resolve in-house, Mafiree's TiDB performance tuning and consulting team can audit your configuration and query patterns before the next incident happens.

?Root-cause audits
⚙️Config & memory tuning
?24×7 incident support

Need help with a TiDB OOM issue?

Mafiree's TiDB consulting and performance optimization team can help with root-cause audits, configuration and memory tuning, and 24×7 incident support.

Contact Mafiree →

FAQ

Most TiDB OOM errors come down to a handful of causes: memory-heavy queries running large HashJoins or full-table scans, too many concurrent sessions collectively exceeding available RAM, memory that isn't released between queries, or a deployment that's simply under-provisioned for the workload. Memory-heavy queries and concurrent sessions account for the majority of production incidents.
There's no universal number it depends on the workload. For most OLTP workloads, a lower quota keeps the blast radius of a single runaway query small. Analytical queries may legitimately need more, but raise the limit carefully and watch the effect on concurrent load, since multiple queries can consume memory at the same time.
Yes — disk spill. When a query's Sort, MergeJoin, HashJoin, HashAgg, or TopN operator exceeds its memory quota, TiDB can spill the intermediate data to disk instead of crashing. It's controlled by tidb_mem_quota_query, tidb_enable_tmp_storage_on_oom, and tmp-storage-path. It's a safety net, though, not a substitute for fixing the underlying expensive query.
tidb_mem_quota_query caps how much memory a single SQL query can use, and TiDB cancels just that query when it hits the limit. tidb_server_memory_limit caps the entire tidb-server process, and TiDB starts killing whichever running queries are using the most memory until usage drops back under the limit. In short: one protects the query, the other protects the server.

Author Bio

Abishek S

Abishek S is a MongoDB and TiDB Certified DBA at Mafiree with strong expertise in distributed databases, TiDB architecture, and cross-database consistency tools. He writes technical content focused on practical database solutions, data consistency verification, replication strategies, and performance optimization for modern data platforms. His work helps engineers and DBAs improve reliability and efficiency in real-world database operations.

Leave a Comment

Related Blogs

Manage Large Data Import in TiDB

Managing large-scale data import in TiDB requires specialized tools and strategies due to its distributed architecture. Unlike traditional databases, TiDB must efficiently distribute data across multiple nodes while maintaining consistency and performance. TiDB Lightning is the primary high-performance tool designed for bulk data ingestion, supporting formats like CSV, Parquet, and Dumpling exports. It offers two import modes: physical mode for maximum speed during initial loads and logical mode for safer imports into active production environments. Additionally, TiDB introduces IMPORT INTO, a SQL-based import method that simplifies data loading for moderate datasets with minimal setup. This guide covers TiDB Lightning architecture, import modes, performance comparisons, complete migration workflows, and best practices to help you efficiently manage large amounts of data, avoid common failures, and choose the right import strategy for your use case.

  1216 views
Automate Expired Data Deletion in TiDB with TTL

Say goodbye to manual cleanup! Learn how TiDB’s TTL feature automates expired data deletion and keeps your database lean and efficient.

  4376 views
Sync-Diff-Inspector: Your Go-To Tool for Verifying Data Consistency Across TiDB and MySQL

A powerful tool to compare, detect, and fix data inconsistencies across distributed databases—ensure accurate migrations and seamless replication with Sync-Diff-Inspector.

  2732 views
The Feature You’ve Been Looking For – Speed Up Your Queries with TiDB Cached Tables!

Boost database performance with TiDB cached tables—reduce latency and accelerate read-heavy queries.

  2619 views
Introducing Foreign Keys and more: Exploring New Features in TiDB v8.5.0

Explore the latest features in TiDB v8.5.0, including support for Foreign Keys, improved performance, and enhanced security for modern database management.

  3096 views

Subscribe for email updates

Get in touch with us

Highlights

More than 6000 Servers Monitored

Happy Clients

Certified DBAs

24 x 7 x 365 Support

PCI

Database Services

MySQL MongoDB PostgreSQL SQL Server Aerospike Clickhouse TiDB ScyllaDB

Quick Links

Careers Blog Contact Privacy Policy Disclaimer Policy

Contacts

Linkedin Mafiree Facebook Mafiree Twitter Mafiree

Nagercoil Office

Miru IT Park, Vallankumaranvillai,

Nagercoil, Tamilnadu - 629 002.

Bangalore Office

Unit 303, Vanguard Rise,

5th Main, Konena Agrahara,

Old Airport Road, Bangalore - 560 017.

Call: +91 6383016411

Email: sales@mafiree.com


Copyright © - All Rights Reserved - Mafiree