MySQL memory and thread structure

The MySQL server is a single mysqld process. Inside it, one thread per client connection runs SQL, and InnoDB's background threads handle writing dirty pages, writing the redo log, and cleaning up old versions. All threads share one address space, so MySQL does not create a separate shared memory segment. Memory splits into a global area (the InnoDB buffer pool and others) that the server allocates at startup, and a session area (sort buffers, join buffers, and others) that connection threads allocate when needed.

MySQL splits into a server layer that processes SQL and a storage engine layer that stores data. In this document, connection threads and session buffers belong to the server layer, and the buffer pool and background threads belong to InnoDB.

Key specs

ItemValue
Execution modelOne process (mysqld), thread model
One connectionOne thread (thread_handling = one-thread-per-connection). The thread pool plugin exists only in the Enterprise Edition
Maximum connectionsmax_connections, 151 by default. One more is accepted for an account with the CONNECTION_ADMIN privilege
Thread reuseThread cache thread_cache_size. By default it is set automatically at startup (8 + max_connections / 100, at most 100)
Buffer poolinnodb_buffer_pool_size, 128MB by default. Fully allocated at startup. Can be changed at runtime (in chunks)
Log bufferinnodb_log_buffer_size. 16MB by default in 8.0, 64MB in 8.4
Sort buffersort_buffer_size, 256KB by default. Per sort
Join bufferjoin_buffer_size, 256KB by default. Per join that cannot use an index, and per hash join
Sequential read / post-sort read bufferread_buffer_size 128KB / read_rnd_buffer_size 256KB
Connection bufferStarts at net_buffer_length 16KB and grows up to max_allowed_packet (64MB by default)
Thread stackthread_stack. Per thread
Internal temporary tablesTempTable engine. Total limit temptable_max_ram (8.4: 3% of memory, at least 1GB and at most 4GB), per-table limit tmp_table_size
Execution plan cacheNone. The query cache was removed in 8.0
Data file I/Oinnodb_flush_method. On Linux, 8.0 defaults to fsync (uses the operating system cache) and 8.4 defaults to O_DIRECT

Thread structure

Figure. Threads inside mysqld

flowchart TB
  CL["Client"] -->|"① Connection request"| LS["Connection manager thread<br/>TCP 3306, Unix socket"]
  LS -->|"② Assign a thread<br/>reuse one from the thread cache if available"| UT["Connection thread<br/>one per connection"]
  CL -->|"③ SQL and results"| UT
  subgraph MEM ["Global memory"]
    BP["InnoDB buffer pool"]
    LB["Log buffer"]
  end
  subgraph BGT ["InnoDB background threads"]
    PC["page cleaner"]
    LW["log writer, log flusher"]
    PG["purge"]
    IO["I/O threads"]
    MT["master"]
  end
  subgraph DISK ["Disk"]
    DF["Data files .ibd"]
    RF["Redo log files"]
    UF["Undo tablespace"]
  end
  UT -->|"Read and modify pages"| BP
  UT -->|"Append redo records"| LB
  PC -->|"Write dirty pages"| DF
  LW -->|"Write log and fsync"| RF
  PG -->|"Clean up unneeded undo"| UF
  IO -.->|"Handle async I/O completion"| DF

Diagram explanation: Everything is inside a single mysqld process.

  1. The Connection manager thread accepts connections on the TCP port (3306 by default) and the Unix socket (①). It assigns a Connection thread to each accepted connection (②). If the thread cache has an idle thread, it uses that one, otherwise it creates a new one. From then on, that thread runs every SQL statement of the connection (③).
  2. The connection thread reads and modifies pages in the InnoDB buffer pool in the Global memory box, and appends a redo record to the Log buffer on every modification.
  3. The threads in the InnoDB background threads box run regardless of connections. The page cleaner writes dirty pages to the Data files, and log writer, log flusher write the log buffer to the Redo log files. purge removes undo records that no transaction reads anymore and rows marked as deleted.
  4. As the dashed arrow shows, the I/O threads do not issue requests themselves. They handle the completion of async I/O issued by read-ahead and the page cleaner. master does chores such as merging the change buffer on a 1-second cycle.

Thread list

ThreadCount (default)What it does
Connection manager threadOne per listener typeAccepts connections on TCP/IP and the Unix socket (shared memory and named pipe on Windows)
Connection threadOne per connectionAuthentication, parsing, optimization, execution. When the connection ends, it returns to the thread cache or exits
page cleanerinnodb_page_cleaners. 8.0: 4, 8.4: number of buffer pool instancesPicks dirty pages from the flush list and the end of the LRU and writes them. Writes go through the doublewrite buffer
log writer, log flusher, and othersOne each (innodb_log_writer_threads = ON)Write the log buffer to the redo log file and fsync. Wake up the waiting connection threads (Redo log)
log checkpointerOneRecords the checkpoint position in the redo log
purgeinnodb_purge_threads. 8.0: 4, 8.4: 1 with 16 or fewer logical CPUs, 4 with moreRemoves unneeded undo records and index entries marked as deleted
Read I/O threadsinnodb_read_io_threads. 8.0: 4, 8.4: half of the logical CPUs (minimum 4)Handle the completion of async reads such as read-ahead
Write I/O threadsinnodb_write_io_threads, 4Handle the completion of async writes
masterOnePeriodic tasks such as merging the change buffer and cleaning up unused table cache entries
Buffer pool dump and loadOneSaves the list of buffer pool pages at shutdown and reads it back at startup
Other server threadsSignal handling, the event scheduler, replication (dump threads on the source, receiver and applier threads on the replica)

Limits of thread per connection. There are as many threads as concurrently connected clients, so when connections grow into the thousands, thread stack memory and context-switch cost grow. In the Community Edition, reduce the number of connections with an application-side connection pool or a proxy such as ProxySQL. The Enterprise Edition's thread pool plugin groups connections into thread groups and limits the number of statements that run at the same time.

Memory structure

Figure. Global memory and session memory

block-beta
  columns 6
  t1["Global memory: shared by the whole server"]:6
  bp["InnoDB buffer pool<br/>data and index pages, change buffer, adaptive hash index"]:4 lb["Log buffer"] tc["Table cache<br/>Dictionary cache"]
  tt["TempTable memory<br/>internal temporary tables"]:2 ps["Performance Schema"]:2 kb["MyISAM key buffer"] bc["Other caches"]
  t2["Session memory: separate for each connection thread, allocated when needed"]:6
  ts["Thread stack"] nb["Connection buffer<br/>result buffer"] so["Sort buffer"] jb["Join buffer"] rb["Read buffer"] bl["binlog cache"]
  class t1,t2 plain
  class bp data
  class lb hot
  class tc,tt,ps,kb,bc meta
  class ts,nb,so,jb,rb,bl slot

Diagram explanation: The top two rows are global, and the bottom row is session.

  • The InnoDB buffer pool is fully allocated at server startup, at the size of innodb_buffer_pool_size. Besides data and index pages, the change buffer (collects changes to secondary index pages that are not in the buffer pool) and the adaptive hash index (remembers the location of frequently searched index values with a hash) also use memory inside it.
  • The Log buffer holds redo records that have not yet been written to the redo log file. If a large transaction fills the whole log buffer before commit, every fill must be written to the file, so enlarge it when many transactions change many rows.
  • The Table cache and Dictionary cache hold open table handles (table_open_cache, 4,000 by default) and table definitions (table_definition_cache). TempTable memory holds the internal temporary tables created by GROUP BY, UNION, and derived tables. When the sum over all sessions exceeds temptable_max_ram, they spill to disk.
  • The six cells in the session row belong to a single connection thread. The Thread stack and the Connection buffer and result buffer stay for as long as the connection exists. The Sort buffer, Join buffer, and Read buffer are allocated only while a statement performs that operation and are released afterward. The binlog cache holds the binary log events a transaction produces until commit (binlog_cache_size, 32KB by default, spills to a temporary file when exceeded).

Session buffers

BufferSetting (default)When allocated
Thread stackthread_stackWhen the thread is created
Connection buffer, result buffernet_buffer_length (16KB) → max_allowed_packet (64MB)At connection. Grows when needed, and the result buffer shrinks back to its initial size when the statement ends
Sort buffersort_buffer_size (256KB)For ORDER BY and GROUP BY that an index cannot resolve. If exceeded, merge sort with temporary files
Join bufferjoin_buffer_size (256KB)For each table joined without an index, and for the hash table of a hash join
Read bufferread_buffer_size (128KB)Sequential scans and similar
Post-sort read bufferread_rnd_buffer_size (256KB)When reading rows in sorted order after a sort, MRR
binlog cachebinlog_cache_size (32KB)When a transaction produces binary log events
Prepared statements, user variablesThe limit is a count (max_prepared_stmt_count)When created

Session buffers can be allocated several times by a single statement. A join buffer is allocated per joined table and a sort buffer per sort. So if you raise sort_buffer_size or join_buffer_size globally, the value multiplies by the number of connections and memory can run out. Raise them with SET SESSION only in sessions that need larger values.

Estimating memory size

innodb_buffer_pool_size + innodb_log_buffer_size + table and dictionary caches + Performance Schema
+ number of connections × (thread_stack + connection buffer)
+ sort, join, and read buffers of concurrently running statements
+ internal temporary tables (up to temptable_max_ram)

Since 8.0.28 you can put a limit on connection memory. Turn on global_connection_memory_tracking (OFF by default) and set connection_memory_limit (one connection) and global_connection_memory_limit (sum over all), and statements from regular users that exceed the limit end with an error. The defaults of both limits are effectively unlimited.

With innodb_dedicated_server = ON (OFF by default), the server looks at its memory size and sets the buffer pool size and other values automatically. This setting assumes a server that runs only MySQL.

The path of one statement

Figure. Threads that UPDATE and COMMIT go through

sequenceDiagram
  participant C as Client
  participant U as Connection thread
  participant M as Global memory
  participant L as Log threads
  participant R as Redo log file
  participant P as page cleaner
  participant D as Data file
  C->>U: UPDATE
  U->>M: Find the page in the buffer pool, read it from the data file if absent
  U->>M: Record the undo record, modify the page
  U->>M: Append the redo record to the log buffer
  C->>U: COMMIT
  U->>L: Wait until the log is recorded up to the commit point
  L->>R: Write the log buffer and fsync
  L-->>U: Recording complete
  U-->>C: Commit complete
  Note over P,D: From here on, it happens later, independent of the commit
  P->>M: Pick dirty pages from the flush list
  P->>D: Write pages through the doublewrite buffer

Diagram explanation: Time flows from top to bottom.

  1. The Connection thread finds the page in the buffer pool in Global memory, leaves the old value as an undo record, and then modifies the page. It turns both changes into redo records and appends them to the log buffer.
  2. At COMMIT, the connection thread waits until the log has been recorded in the file up to its own commit point. The Log threads (log writer and log flusher) write the log buffer to the Redo log file, fsync, and wake the waiting thread. When several connections commit at the same time, they ride on one fsync. Whether to wait is decided by innodb_flush_log_at_trx_commit.
  3. On a server with the binary log enabled (the default since 8.0), commit has two phases. InnoDB records the prepare, the transaction is written to the binary log and synchronized (sync_binlog), and then InnoDB records the commit. The figure shows only the InnoDB side.
  4. Below the Note is the later work. The page cleaner first writes dirty pages to the doublewrite buffer, and then writes them in place in the Data file.

Defaults that changed between 8.0 and 8.4

Setting8.08.4
innodb_log_buffer_size16MB64MB
innodb_flush_method (Linux)fsyncO_DIRECT (if supported)
innodb_adaptive_hash_indexONOFF
innodb_change_bufferingallnone
innodb_buffer_pool_instances8 (1 if the buffer pool is under 1GB)Calculated automatically from the buffer pool size and CPU count
innodb_page_cleaners4Number of buffer pool instances
innodb_purge_threads41 with 16 or fewer logical CPUs, 4 with more
innodb_read_io_threads4Half of the logical CPUs (minimum 4)

Settings and checks

-- Thread list: connection threads (FOREGROUND) and background threads
SELECT thread_id, name, type, processlist_id, thread_os_id
FROM performance_schema.threads ORDER BY type, name;

-- Connection count and thread cache
SHOW GLOBAL STATUS LIKE 'Threads_%';        -- Threads_connected, Threads_running, Threads_cached, Threads_created
SHOW GLOBAL STATUS LIKE 'Max_used_connections';

-- Who uses the memory (sys schema, Performance Schema memory instrumentation)
SELECT event_name, current_alloc FROM sys.memory_global_by_current_bytes LIMIT 10;
SELECT thread_id, user, current_allocated FROM sys.memory_by_thread_by_current_bytes LIMIT 10;

-- Buffer pool and log buffer state
SHOW ENGINE INNODB STATUS;                  -- BUFFER POOL AND MEMORY, LOG, BACKGROUND THREAD sections
SELECT @@innodb_buffer_pool_size / 1024 / 1024 AS bp_mb, @@innodb_log_buffer_size / 1024 / 1024 AS log_mb;

-- Sorts and temporary tables that spilled to disk
SHOW GLOBAL STATUS LIKE 'Sort_merge_passes';
SHOW GLOBAL STATUS LIKE 'Created_tmp%';
  • If Threads_created keeps growing, the thread cache is too small and a new thread is created for each connection.
  • At the operating system level, look at threads with ps -eLf | grep mysqld or top -H. performance_schema.threads.thread_os_id is that thread ID.

Comparison with other DBMSs

MySQLPostgreSQLOracleSQL ServerKDBS
One connectionThreadProcessServer process (dedicated server)Session. A worker per requestConnection inside a per-core reactor
Shared areaProcess address spaceShared memorySGAProcess address spaceProcess address space
Working memorySession buffers (settings per purpose)work_mem (per operation)PGA (instance-wide target)Memory grantRow count limit
Writing dirty pagespage cleaner threadscheckpointer, background writerDBWnCheckpoint, lazy writerCheckpoint task and data file write threads

The full comparison is in DBMS architecture at a glance.

In the articles

NOTE The defaults follow the MySQL 8.0 and 8.4 reference manuals and can vary by minor version. This site has no MySQL sandbox, so the values in this document were not measured. MariaDB differs from this document, for example by providing a thread pool by default.

Related pages