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
| Item | Value |
|---|---|
| Execution model | One process (mysqld), thread model |
| One connection | One thread (thread_handling = one-thread-per-connection). The thread pool plugin exists only in the Enterprise Edition |
| Maximum connections | max_connections, 151 by default. One more is accepted for an account with the CONNECTION_ADMIN privilege |
| Thread reuse | Thread cache thread_cache_size. By default it is set automatically at startup (8 + max_connections / 100, at most 100) |
| Buffer pool | innodb_buffer_pool_size, 128MB by default. Fully allocated at startup. Can be changed at runtime (in chunks) |
| Log buffer | innodb_log_buffer_size. 16MB by default in 8.0, 64MB in 8.4 |
| Sort buffer | sort_buffer_size, 256KB by default. Per sort |
| Join buffer | join_buffer_size, 256KB by default. Per join that cannot use an index, and per hash join |
| Sequential read / post-sort read buffer | read_buffer_size 128KB / read_rnd_buffer_size 256KB |
| Connection buffer | Starts at net_buffer_length 16KB and grows up to max_allowed_packet (64MB by default) |
| Thread stack | thread_stack. Per thread |
| Internal temporary tables | TempTable 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 cache | None. The query cache was removed in 8.0 |
| Data file I/O | innodb_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.
- The
Connection manager threadaccepts connections on the TCP port (3306 by default) and the Unix socket (①). It assigns aConnection threadto 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 (③). - The connection thread reads and modifies pages in the
InnoDB buffer poolin theGlobal memorybox, and appends a redo record to theLog bufferon every modification. - The threads in the
InnoDB background threadsbox run regardless of connections. Thepage cleanerwrites dirty pages to theData files, andlog writer, log flusherwrite the log buffer to theRedo log files.purgeremoves undo records that no transaction reads anymore and rows marked as deleted. - As the dashed arrow shows, the
I/O threadsdo not issue requests themselves. They handle the completion of async I/O issued by read-ahead and the page cleaner.masterdoes chores such as merging the change buffer on a 1-second cycle.
Thread list
| Thread | Count (default) | What it does |
|---|---|---|
| Connection manager thread | One per listener type | Accepts connections on TCP/IP and the Unix socket (shared memory and named pipe on Windows) |
| Connection thread | One per connection | Authentication, parsing, optimization, execution. When the connection ends, it returns to the thread cache or exits |
| page cleaner | innodb_page_cleaners. 8.0: 4, 8.4: number of buffer pool instances | Picks 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 others | One 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 checkpointer | One | Records the checkpoint position in the redo log |
| purge | innodb_purge_threads. 8.0: 4, 8.4: 1 with 16 or fewer logical CPUs, 4 with more | Removes unneeded undo records and index entries marked as deleted |
| Read I/O threads | innodb_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 threads | innodb_write_io_threads, 4 | Handle the completion of async writes |
| master | One | Periodic tasks such as merging the change buffer and cleaning up unused table cache entries |
| Buffer pool dump and load | One | Saves the list of buffer pool pages at shutdown and reads it back at startup |
| Other server threads | Signal 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 poolis fully allocated at server startup, at the size ofinnodb_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 bufferholds 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 cacheandDictionary cachehold open table handles (table_open_cache, 4,000 by default) and table definitions (table_definition_cache).TempTable memoryholds the internal temporary tables created byGROUP BY,UNION, and derived tables. When the sum over all sessions exceedstemptable_max_ram, they spill to disk. - The six cells in the session row belong to a single connection thread. The
Thread stackand theConnection bufferandresult bufferstay for as long as the connection exists. TheSort buffer,Join buffer, andRead bufferare allocated only while a statement performs that operation and are released afterward. Thebinlog cacheholds the binary log events a transaction produces until commit (binlog_cache_size, 32KB by default, spills to a temporary file when exceeded).
Session buffers
| Buffer | Setting (default) | When allocated |
|---|---|---|
| Thread stack | thread_stack | When the thread is created |
| Connection buffer, result buffer | net_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 buffer | sort_buffer_size (256KB) | For ORDER BY and GROUP BY that an index cannot resolve. If exceeded, merge sort with temporary files |
| Join buffer | join_buffer_size (256KB) | For each table joined without an index, and for the hash table of a hash join |
| Read buffer | read_buffer_size (128KB) | Sequential scans and similar |
| Post-sort read buffer | read_rnd_buffer_size (256KB) | When reading rows in sorted order after a sort, MRR |
| binlog cache | binlog_cache_size (32KB) | When a transaction produces binary log events |
| Prepared statements, user variables | The 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.
- The
Connection threadfinds the page in the buffer pool inGlobal 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. - At
COMMIT, the connection thread waits until the log has been recorded in the file up to its own commit point. TheLog threads(log writer and log flusher) write the log buffer to theRedo log file,fsync, and wake the waiting thread. When several connections commit at the same time, they ride on onefsync. Whether to wait is decided byinnodb_flush_log_at_trx_commit. - 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. - Below the
Noteis the later work. Thepage cleanerfirst writes dirty pages to the doublewrite buffer, and then writes them in place in theData file.
Defaults that changed between 8.0 and 8.4
| Setting | 8.0 | 8.4 |
|---|---|---|
innodb_log_buffer_size | 16MB | 64MB |
innodb_flush_method (Linux) | fsync | O_DIRECT (if supported) |
innodb_adaptive_hash_index | ON | OFF |
innodb_change_buffering | all | none |
innodb_buffer_pool_instances | 8 (1 if the buffer pool is under 1GB) | Calculated automatically from the buffer pool size and CPU count |
innodb_page_cleaners | 4 | Number of buffer pool instances |
innodb_purge_threads | 4 | 1 with 16 or fewer logical CPUs, 4 with more |
innodb_read_io_threads | 4 | Half 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_createdkeeps 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 mysqldortop -H.performance_schema.threads.thread_os_idis that thread ID.
Comparison with other DBMSs
| MySQL | PostgreSQL | Oracle | SQL Server | KDBS | |
|---|---|---|---|---|---|
| One connection | Thread | Process | Server process (dedicated server) | Session. A worker per request | Connection inside a per-core reactor |
| Shared area | Process address space | Shared memory | SGA | Process address space | Process address space |
| Working memory | Session buffers (settings per purpose) | work_mem (per operation) | PGA (instance-wide target) | Memory grant | Row count limit |
| Writing dirty pages | page cleaner threads | checkpointer, background writer | DBWn | Checkpoint, lazy writer | Checkpoint 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
- DBMS Architecture at a Glance
- MySQL (InnoDB)
- MySQL Connections, Cursors, and SQL Cache
- InnoDB Buffer Pool
- InnoDB redo log
- InnoDB Undo Log
- InnoDB doublewrite buffer
- innodb_flush_log_at_trx_commit
- PostgreSQL Memory and Process Architecture
- Oracle memory and process structure
- SQL Server Memory and Thread Structure
- KDBS Memory and Thread Architecture