MySQL Storage Engines: InnoDB vs MyISAM (and the rest)
"InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data." — MySQL 8.4 Reference Manual, "Alternative Storage Engines"
Summary: MySQL separates the SQL layer from pluggable storage engines; InnoDB is the transactional default (clustered index, buffer pool, redo and undo, doublewrite, row locks) while MyISAM, MEMORY and MyRocks make different trade-offs on crash safety and locking. Focus: The handler API, InnoDB in-memory and on-disk structures, the life of an UPDATE and a crash recovery, MyISAM files and repair, the other engines, MyRocks, tuning knobs, error codes, and PostgreSQL comparisons. Learning goal: Pick the right engine for a workload, explain what InnoDB does between UPDATE and durable disk, convert a legacy MyISAM table safely, and read the status output to find the bottleneck.
This page covers MySQL's storage engines in full. It explains how InnoDB stores, caches, logs, locks and recovers a row, from the buffer pool down to the doublewrite file. It explains how MyISAM writes two files with no log, and why a crash can leave a MyISAM table marked as crashed. It positions MEMORY, CSV, ARCHIVE, BLACKHOLE, NDB and MyRocks, and compares all of them with the PostgreSQL heap. The general B-tree vs LSM theory is on Storage Engines: B-tree vs LSM-tree. WAL theory is on Durability, WAL & Crash Recovery. Version chains and VACUUM are on MVCC, VACUUM & Bloat, and lock modes on Locks & Concurrency. Everything here is about MySQL 8.4 (LTS) unless a version is named.
Page map
| If you are looking for | Go to |
|---|---|
| A one-screen summary you can memorise | Everything in one minute |
| What "pluggable storage engine" and the handler API mean | Pluggable engines |
How InnoDB lays out rows (clustered index, GEN_CLUST_INDEX) | Clustered index |
| Buffer pool, LRU midpoint insertion, change buffer, adaptive hash index | Buffer pool |
Redo log, log buffer, innodb_flush_log_at_trx_commit | Redo log |
| Undo log, purge, history list length | Undo log |
| Doublewrite buffer, torn pages, checkpoints | Doublewrite |
ibdata1, .ibd, tablespaces, the 8.0 data dictionary | Tablespaces |
| Row formats (REDUNDANT, COMPACT, DYNAMIC, COMPRESSED), off-page storage | Row formats |
| How MyISAM stores data, key cache, table locks, repair | MyISAM |
| MEMORY, CSV, ARCHIVE, BLACKHOLE, NDB, MyRocks | The other engines |
| The life of an UPDATE in InnoDB, and of a write in MyISAM | Mechanics |
| Every knob with its default and when to change it | Tuning table |
| Feature matrix InnoDB × MyISAM × MEMORY × MyRocks × PostgreSQL | Comparison matrix |
| Converting MyISAM, picking a PK, hit rate, flush settings, hot rows | Solving the classic problems |
| Which engine for which workload | Choosing an engine |
| Monolith → microservices → Group Replication/Vitess/TiDB | In architecture |
| A hands-on crash test | Lab |
Everything in one minute
The engines.
| Engine | One line | Transactions | Locking | Survives a crash? | Use it for |
|---|---|---|---|---|---|
| InnoDB | Default since MySQL 5.5. Rows live inside the primary-key B-tree. Has redo and undo logs | Yes | Row | Yes: redo + doublewrite + undo | Everything, unless you have a proven reason not to |
| MyISAM | Two files per table (.MYD data, .MYI index), no log | No | Table | No: may need REPAIR TABLE | Legacy only; read-only packed data |
| MEMORY | Rows in RAM, formerly HEAP | No | Table | Data is lost on restart (the table definition stays) | Small scratch or lookup tables |
| CSV | A plain .CSV text file, no indexes | No | Table | n/a | Import/export with spreadsheets and scripts |
| ARCHIVE | Compressed, insert-only, indexed only on AUTO_INCREMENT | No | Row | n/a | Rarely read history |
| BLACKHOLE | Accepts writes, stores nothing, still writes the binlog | No | n/a | n/a | Binlog relay/filter tricks |
| NDB | The engine of MySQL NDB Cluster: distributed, shared-nothing | Yes | Row | Yes (cluster) | Telecom-style HA key lookups |
| MyRocks | RocksDB (LSM tree) inside MySQL; ships with Percona Server and MariaDB, not Oracle MySQL | Yes | Row, no gap locks | Yes (WAL) | Write-heavy, space-sensitive data on SSD |
InnoDB's moving parts.
| Structure | Lives in | Job in one line |
|---|---|---|
| Buffer pool | RAM | Caches 16 KB data and index pages; the main memory knob |
| Change buffer | RAM + system tablespace | Delays writes to secondary-index pages that are not cached (off by default in 8.4) |
| Adaptive hash index | RAM | Hash shortcut over hot B-tree pages (off by default in 8.4) |
| Log buffer | RAM | Holds redo records until they are written to the redo log |
| Redo log | #innodb_redo/ files | Physical record of every page change; replayed after a crash |
| Undo log | Undo tablespaces (undo_001, undo_002) | Old row versions for rollback and MVCC reads |
| Doublewrite buffer | #ib_*.dblwr files | A second copy of each flushed page, so a torn page can be repaired |
| Tablespaces | ibdata1, *.ibd, mysql.ibd, ibtmp1, #innodb_temp/ | Where pages finally live on disk |
InnoDB vs MyISAM in six lines.
| Question | InnoDB | MyISAM |
|---|---|---|
ROLLBACK after two updates | Both undone | Nothing undone; warning 1196 |
| Two sessions update different rows | Both proceed | Second waits for the table lock |
kill -9 in the middle of a write | Restart replays redo, rolls back uncommitted work | Table may be marked as crashed; partial changes stay |
| Foreign keys | Enforced | Parsed and ignored |
| Row order on disk | Primary-key order (clustered) | Insertion order (heap file) |
| Cache | Buffer pool caches data and index | Key cache caches index only; data relies on the OS cache |
Why storage engines exist
Where it comes from
MySQL splits the SQL layer from the storage layer. The parser, optimizer, privileges, binary log and connection handling live in the server. Every table is handed to a storage engine, which decides how rows are laid out, cached, locked, logged and recovered. The manual describes the design goal this way:
"The MySQL pluggable storage engine architecture enables a database professional to select a specialized storage engine for a particular application need while being completely shielded from the need to manage any specific application coding requirements." — MySQL 8.4 Reference Manual, "Overview of MySQL Storage Engine Architecture"
For years the default engine was MyISAM: small, simple and fast for read-mostly web pages. InnoDB (originally from Innobase Oy) was the add-on that brought transactions. The switch is recorded in MySQL's own design worklog:
"As of MySQL 5.5, the default storage engine should change from MyISAM to InnoDB." — MySQL Worklog WL#5349, "Change default storage engine to InnoDB"
History of the default engine (MySQL)
1 before 5.5 MyISAM is the default; InnoDB is an optional transactional engine
2 5.5 WL#5349: InnoDB becomes the default for user tables (system tables stay MyISAM)
3 5.6 InnoDB gains FULLTEXT indexes, MyISAM's last unique feature
4 8.0 Transactional data dictionary on InnoDB; .frm files removed; mysql.* in mysql.ibd;
AUTO_INCREMENT counter persisted; innodb_autoinc_lock_mode default becomes 2
5 8.4 LTS New InnoDB defaults: change buffering none, adaptive hash index OFF,
innodb_io_capacity 10000, log buffer 64 MiB, O_DIRECT on Linux if supportedThe 8.4 manual's own summary of MyISAM is one sentence that carries the whole trade-off:
"Table-level locking limits the performance in read/write workloads, so it is often used in read-only or read-mostly workloads in Web and data warehousing configurations." — MySQL 8.4 Reference Manual, "Alternative Storage Engines"
The fundamental trade-off
| Simpler engine (MyISAM, MEMORY, CSV, ARCHIVE) | Richer engine (InnoDB, MyRocks, NDB) |
|---|---|
| No log, so a write is one file write | Every change also goes to a log, and often a second page copy |
| One lock per table: no deadlocks, no row-lock memory | Row locks: concurrency, plus deadlocks and lock waits to handle |
| Nothing to roll back, so nothing to recover | Undo, redo and doublewrite make crash recovery automatic |
| Small on disk, small in memory | Buffer pool, undo history and redo capacity to size and watch |
| A crash may leave a table you must repair | A crash costs a restart and a few seconds of redo replay |
One analogy for the whole page
Think of a warehouse. InnoDB is a warehouse with a front desk ledger. Every move is first written in the ledger (redo log). The floor staff keep the busiest shelves near the door (buffer pool). Before moving a box, they photograph where it was (undo log), so they can put it back or show an auditor what the shelf looked like at 9:00 (MVCC). Shelves are arranged in item-number order (clustered index). MyISAM is a warehouse with no ledger and one key to the whole building. Only one person may rearrange anything at a time (table lock). If the lights go out mid-move, nobody knows which boxes were half moved, and someone has to walk the aisles and fix it (REPAIR TABLE).
Three common misunderstandings up front
- "MyISAM is faster." It used to be, for single-user reads of small tables. Under concurrent writes its table lock serialises everyone. Since 8.0 even MySQL's own system tables are InnoDB.
- "
START TRANSACTIONmakes any table transactional." The server accepts the statement for every engine. MyISAM applies each statement immediately, andROLLBACKonly returns warning 1196 (ER_WARNING_NOT_COMPLETE_ROLLBACK). - "The engine is just a table option." Transactions, foreign keys, lock granularity, crash behaviour, backup method and replication safety all change with it. A schema with mixed engines gives you transactions that are atomic over some tables and not over others.
The concept catalogue
Pluggable storage engines and the handler API Important
In plain words: MySQL is two programs in one. The top half understands SQL. The bottom half (the engine) stores bytes. They talk through a fixed C++ interface called the handler API.
Common misunderstanding: "The engine only affects disk format." The optimizer asks the engine for row estimates and index statistics, the transaction coordinator asks it to prepare and commit, and the lock manager delegates row locking to it. Two engines behind identical SQL behave differently in every one of those areas.
Definition: Each engine implements a subclass of the server's handler class (InnoDB's is ha_innobase) with calls such as open table, read row by index, write row, update row, delete row, start/commit/rollback transaction. The server picks the engine per table from the data dictionary. SHOW ENGINES lists what this server has compiled in or loaded, and default_storage_engine (8.4 default: InnoDB) decides what CREATE TABLE uses without an ENGINE clause.
1 client ──▶ UPDATE accounts SET balance = balance - 100 WHERE id = 7
2 server ──▶ parse, check privileges, optimize (asks engine for index stats)
3 server ──▶ handler->index_read(PRIMARY, id=7) (engine: find row, lock it)
4 server ──▶ handler->update_row(old_row, new_row) (engine: undo, redo, page change)
5 server ──▶ at COMMIT: two-phase commit across engine and binary log
6 engine ──▶ InnoDB makes it durable; MyISAM already wrote it at step 4Real scenario: an old schema where sessions is MEMORY, logs is ARCHIVE, orders is InnoDB and users is still MyISAM. One DB::transaction touching orders and users is atomic for orders only.
Fix / how to use it: pin the engine explicitly and check it in CI.
SHOW ENGINES; -- Support = DEFAULT marks the default engine
SELECT @@default_storage_engine, @@default_tmp_storage_engine; -- InnoDB, InnoDB
SELECT TABLE_SCHEMA, TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA NOT IN ('mysql','sys','performance_schema','information_schema')
AND ENGINE <> 'InnoDB';Error 1286 ER_UNKNOWN_STORAGE_ENGINE ("Unknown storage engine '%s'") appears when a dump names an engine this server does not have (for example ENGINE=RocksDB restored into Oracle MySQL). The Go and Laravel versions of the engine check are the snippets in Go and Laravel.
Clustered index and secondary indexes Must-know
In plain words: an InnoDB table is a B-tree sorted by primary key, and the full rows sit in its leaves. Every other index stores the primary key as its "pointer" to the row.
Common misunderstanding: "A secondary index points to the row's disk location." In InnoDB it stores the primary-key value, so a lookup by a secondary index walks two trees, and a long primary key makes every secondary index bigger. (PostgreSQL is the opposite: every index, the primary key included, points at a physical tuple id.)
Definition: InnoDB uses the PRIMARY KEY as the clustered index. Without one, it uses the first UNIQUE index whose columns are all NOT NULL. Without that either:
"If a table has no PRIMARY KEY or suitable UNIQUE index, InnoDB generates a hidden clustered index named GEN_CLUST_INDEX on a synthetic column that contains row ID values." — MySQL 8.4 Reference Manual, "Clustered and Secondary Indexes"
That synthetic column is the 6-byte DB_ROW_ID. Each clustered-index record also carries a 6-byte DB_TRX_ID (last writer) and a 7-byte DB_ROLL_PTR (pointer to the undo record). Those two fields are what MVCC uses. A secondary-index entry holds the indexed columns plus the PK columns.
Lookup by a secondary index (InnoDB)
1 SELECT * FROM orders WHERE customer_email = 'a@b.c';
2 descend idx_email B-tree -> leaf entry ('a@b.c', PK=981244)
3 descend PRIMARY B-tree -> leaf page holding the full row 981244
4 (covering index: if all selected columns are in idx_email + PK, step 3 is skipped)Real scenarios:
- A
CHAR(36)UUIDv4 primary key on a 200-million-roweventstable: each of five secondary indexes carries 36 extra bytes per entry, and random inserts split pages all over the tree. - A table with no PK at all: rows go into
GEN_CLUST_INDEX, and the row-ID counter is shared across all such tables in the instance. Group Replication refuses such tables, and row-based replicas fall back to scanning for every row change. - Range scans by PK (
WHERE id BETWEEN …,ORDER BY id) read consecutive leaf pages: the main performance gift of clustering.
| Product | Where the row lives | What a secondary index points to |
|---|---|---|
| MySQL InnoDB | Leaf of the PK B-tree (clustered) | PK value |
| MySQL MyISAM | .MYD heap file, insertion order | File offset in .MYD |
| PostgreSQL | Heap pages, any order | Physical tuple id (ctid) |
| SQL Server | Clustered index if one is declared, otherwise a heap | Clustering key, or RID for a heap |
| Oracle | Heap by default; index-organized table (IOT) on request | ROWID (heap) or logical rowid (IOT) |
| SQLite | B-tree keyed by rowid; WITHOUT ROWID clusters by the PK | rowid or PK |
| MyRocks | LSM tree keyed by PK | PK value |
Fix: declare a short, monotonic PK on every InnoDB table. See Choosing the PK for the clustered index for SQL, Go and Laravel.
Buffer pool and LRU midpoint insertion Must-know
In plain words: the buffer pool is InnoDB's RAM cache for 16 KB pages of data and indexes. Reads and writes happen there; disks are touched only on a miss or when dirty pages are flushed.
Common misunderstanding: "A full table scan will push my hot data out." InnoDB's LRU is split so that a one-off scan lands in the "old" part first and normally ages out without disturbing the "young" part, as long as innodb_old_blocks_time is not 0.
Definition: the pool is a list of pages with a midpoint. New pages are inserted at the head of the old sublist, which is 3/8 of the list by default (innodb_old_blocks_pct=37). A page moves to the young head only if it is touched again after innodb_old_blocks_time ms (default 1000). Each instance (innodb_buffer_pool_instances) has its own LRU, free list, flush list and mutex. Size: innodb_buffer_pool_size, default 128 MiB (134217728), resizable online in innodb_buffer_pool_chunk_size steps (default 128 MiB). The manual's guideline: "On dedicated servers, up to 80% of physical memory is often assigned to the buffer pool." --innodb-dedicated-server picks 50% of RAM between 1 and 4 GB and 75% above 4 GB.
Buffer pool LRU (one instance)
head ─────────── young (new) sublist 5/8 ──────────▶│◀──── old sublist 3/8 ───── tail
▲
1 page read from .ibd for a query ─────────┘ inserted at midpoint
2 touched again > 1000 ms later ──▶ moved to young head
3 mysqldump scans 50 GB once ──▶ pages enter at midpoint, never re-touched,
age out of the tail; hot set survives
4 page dirty (modified) ──▶ also on the flush list, ordered by oldest LSNReal scenarios:
- A 64 GB server left at the 128 MiB default: every product page view reads from disk. Moving to 40 GB drops read IOPS by orders of magnitude.
- A nightly report scans a 300 GB table; with the midpoint, the morning checkout traffic still hits cache.
- After a restart the cache is cold;
innodb_buffer_pool_dump_at_shutdown/innodb_buffer_pool_load_at_startup(both default ON) reload the page list.
| Engine | Data cache | Index cache |
|---|---|---|
| InnoDB | Buffer pool | Buffer pool |
| MyISAM | None (OS page cache) | Key cache (key_buffer_size, default 8 MiB) |
| MEMORY | The table is the memory | Same |
| MyRocks | RocksDB block cache | Same |
| PostgreSQL | shared_buffers + OS page cache (double caching) | Same |
Fix / how to use it: size it, then measure the miss ratio. Full SQL, Go and Laravel are in Diagnosing the buffer pool hit rate.
SELECT POOL_ID, POOL_SIZE, FREE_BUFFERS, DATABASE_PAGES, MODIFIED_DATABASE_PAGES, HIT_RATE
FROM information_schema.INNODB_BUFFER_POOL_STATS;
SET GLOBAL innodb_buffer_pool_size = 40 * 1024 * 1024 * 1024; -- online, in chunk stepsChange buffer Good to know
In plain words: when you insert a row and a secondary-index page it touches is not in memory, InnoDB can note the change in a side structure and apply it later, instead of reading that page from disk right now.
Common misunderstanding: "The change buffer is always working for me." In MySQL 8.4 innodb_change_buffering defaults to none (it was all in 8.0). Inserts into unique indexes are not buffered either, because uniqueness must be checked against the real page.
Definition: a B-tree stored in the system tablespace (ibdata1) and cached in the buffer pool, capped at innodb_change_buffer_max_size (25% of the pool by default, max 50). Buffered changes merge when the page is next read, during idle time, or during slow shutdown. The manual warns that merging "may take several hours when there are many affected rows and numerous secondary indexes to update".
Real scenario: a bulk-loaded audit table with six non-unique secondary indexes on a server whose working set is far larger than RAM. Enabling innodb_change_buffering=all can cut random reads. If the working set fits in the pool, leave it at none.
Adaptive hash index Good to know
In plain words: InnoDB can watch which index lookups repeat and build an in-memory hash table on top of the hot B-tree pages, turning a tree walk into one hash probe.
Common misunderstanding: "AHI is free speed." It is maintained under latches. Under heavy concurrent joins those latches become a bottleneck; SHOW ENGINE INNODB STATUS then shows many waits on btr0sea.c in the SEMAPHORES section. That is why 8.4 ships with innodb_adaptive_hash_index=OFF (it was ON in 8.0), partitioned into innodb_adaptive_hash_index_parts=8 when on.
Fix: benchmark both ways; enable it only for read-heavy, memory-resident point lookups.
Log buffer and redo log Must-know
In plain words: before InnoDB changes a page in memory, it writes a short note describing that change into the log buffer. At commit, the note goes to the redo log on disk. If the server dies, those notes are replayed to rebuild every page change that had not reached the data files yet.
Common misunderstanding: "Commit writes my row to the table file." Commit only writes (and, with the default setting, flushes) the redo log. The 16 KB data page is written later by background page cleaners. That is why commits are fast and why the redo log must never be deleted.
Definition: redo records are grouped into mini-transactions and stamped with an ever-increasing LSN (log sequence number). They go first into the log buffer (innodb_log_buffer_size, 64 MiB default in 8.4), then into redo log files. In 8.4 the size is one knob, innodb_redo_log_capacity (default 100 MiB), spread over 32 files #ib_redoN in the #innodb_redo directory. innodb_log_file_size and innodb_log_files_in_group are deprecated and only used if capacity is unset. When to flush is controlled by innodb_flush_log_at_trx_commit:
| Value | At each commit | Flushed to disk | What a crash can lose |
|---|---|---|---|
1 (default) | Write to OS and fsync | Every commit | Nothing committed (if the disk honours fsync) |
2 | Write to OS | About once per innodb_flush_log_at_timeout (1 s) | mysqld crash: nothing. OS crash / power loss: up to ~1 s |
0 | Nothing | Write + flush about once per second | Up to ~1 s, even on a plain mysqld crash |
"The default setting of 1 is required for full ACID compliance." — MySQL 8.4 Reference Manual,
innodb_flush_log_at_trx_commit
The manual adds that crash recovery "works regardless of the innodb_flush_log_at_trx_commit setting": the setting changes how much committed work you can lose, never whether the database comes back consistent.
Redo log as a ring of 32 files (capacity 100 MiB default)
1 LSN 5000 checkpoint LSN ─ everything older is already in the data files
2 LSN 5000..8200 redo still needed for recovery ("checkpoint age")
3 LSN 8200 current LSN ─ new redo appended here
4 if checkpoint age nears capacity ─▶ page cleaners flush harder ─▶ checkpoint advances
5 if redo is too small for the write rate ─▶ "furious flushing", write stallsReal scenarios: a payments service keeps 1. A metrics ingest job that can replay its source accepts 2. A replica that can be rebuilt sometimes runs 2 for apply speed. A data migration on a throwaway box may use 0. See Durability vs throughput.
Undo log, rollback segments, purge and history list length Must-know
In plain words: before InnoDB overwrites a row in place, it saves the old version in the undo log. ROLLBACK uses it to put the row back, and older read snapshots use it to see the row as it was.
Common misunderstanding: "A long read-only SELECT cannot hurt writers." It holds a read view. While it is open, purge cannot discard the undo records it might need, so the history list length grows, undo tablespaces swell, and every reader has to walk longer version chains.
Definition: undo records live in rollback segments inside undo tablespaces. Two are created at initialisation (undo_001, undo_002); add more with CREATE UNDO TABLESPACE … ADD DATAFILE 'x.ibu'. Insert-undo can be discarded at commit. Update-undo must stay until no read view needs it. The background purge threads (innodb_purge_threads: 1 if ≤16 logical CPUs, else 4) then remove delete-marked rows and old undo pages. The queue of committed-but-unpurged undo is the history list; its length appears in SHOW ENGINE INNODB STATUS as History list length. innodb_max_purge_lag (default 0, off) can throttle DML when purge falls behind, and innodb_undo_log_truncate (default ON) shrinks undo tablespaces above innodb_max_undo_log_size (1 GiB).
T1 (report, REPEATABLE READ) T2 (writer)
1 START TRANSACTION; SELECT … FROM orders; -- read view created; order 1 is 'pending'
2 UPDATE orders SET status='paid' WHERE id=1; -- old row -> undo
3 COMMIT; -- undo kept: T1 may need it
4 SELECT status FROM orders WHERE id=1; -- still 'pending': old version rebuilt from undo (consistent read)
5 … T1 left open for 6 hours … -- 40 million updates later: history list length 40,000,000
6 COMMIT; -- purge can finally catch up; undo truncation followsReal scenarios: a BI tool that opens a transaction and idles over lunch; a mysqldump --single-transaction of a 2 TB schema; a forgotten BEGIN in a REPL session. All three show up as one old entry in INNODB_TRX and a rising history list length.
| Product | Where old versions live | Who cleans them up |
|---|---|---|
| MySQL InnoDB | Undo tablespaces (rollback segments) | Purge threads |
| PostgreSQL | In the heap, next to live tuples | VACUUM / autovacuum |
| Oracle | Undo tablespace | Undo retention |
| MyRocks | Older key versions in the LSM tree | Compaction, once no snapshot needs them |
| MyISAM, MEMORY | No old versions (no MVCC) | n/a |
Fix:
SELECT trx_id, trx_started, TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS age_s,
trx_mysql_thread_id, trx_rows_modified, trx_query
FROM information_schema.INNODB_TRX ORDER BY trx_started LIMIT 5;
SELECT NAME, COUNT FROM information_schema.INNODB_METRICS WHERE NAME = 'trx_rseg_history_len';
-- KILL <trx_mysql_thread_id>; once you know who owns itDoublewrite buffer and torn pages Important
In plain words: a 16 KB InnoDB page is written by the OS in smaller pieces. If power fails halfway, the page on disk is half old and half new (a torn page), and the redo log cannot fix a page whose own contents are garbage. So InnoDB first writes every page to a separate doublewrite area, then to its real place.
Common misunderstanding: "Doublewrite doubles my write I/O." The doublewrite copy is written in large sequential batches with one fsync, so the cost is far below 2×.
Definition:
"If there is an operating system, storage subsystem, or unexpected mysqld process exit in the middle of a page write, InnoDB can find a good copy of the page from the doublewrite buffer during crash recovery." — MySQL 8.4 Reference Manual, "Doublewrite Buffer"
In 8.4 the area lives in dedicated doublewrite files (innodb_doublewrite_dir, innodb_doublewrite_files default 2), next to the data directory by default. innodb_doublewrite is ON (= DETECT_AND_RECOVER); DETECT_ONLY writes only metadata; OFF disables it. Turning it off is only safe on storage with atomic 16 KB writes.
Flushing one dirty page
1 page cleaner picks dirty page P (LSN 7100) from the flush list
2 redo up to LSN 7100 must already be on disk (write-ahead rule)
3 write P (and its batch) sequentially into the doublewrite file; fsync
4 write P to its home position in orders.ibd; fsync
5 power fails during step 4 ─▶ P in orders.ibd is torn
6 recovery: checksum of P fails ─▶ copy from doublewrite ─▶ then apply redoPostgreSQL solves the same problem differently, with full_page_writes: the first change to a page after each checkpoint logs the whole page image into the WAL.
Checkpoints and fuzzy checkpointing Important
In plain words: a checkpoint is a bookmark in the redo log saying "every change before this point is safely in the data files". Recovery starts from the latest bookmark, so the further behind it is, the longer recovery takes.
Common misunderstanding: "A checkpoint freezes the server while it writes the whole cache." InnoDB never does a full sharp checkpoint during normal operation:
"InnoDB implements a checkpoint mechanism known as fuzzy checkpointing." — MySQL 8.4 Reference Manual, "InnoDB Checkpoints"
Definition: page cleaner threads flush dirty pages from the flush list in small batches. The rate is adaptive, driven by innodb_io_capacity (10000 in 8.4, was 200), innodb_io_capacity_max, innodb_max_dirty_pages_pct (90) and how full the redo log is. The checkpoint LSN advances to the oldest still-dirty page. A larger innodb_redo_log_capacity lets InnoDB absorb bursts and merge more changes per page write, at the price of longer recovery.
Real scenario: a flash sale doubles the write rate; with 100 MiB of redo the checkpoint age hits the limit, page cleaners flush aggressively and commit latency spikes. Raising redo capacity to a few GB (an hour of peak redo is a common target) smooths it out.
Tablespaces, files and the data dictionary Important
In plain words: a tablespace is a file (or set of files) that holds InnoDB pages. Each table normally gets its own .ibd file; a few shared files hold the rest.
Common misunderstanding: "Dropping a big table frees disk space." Only if it lived in a file-per-table tablespace. Space freed inside ibdata1 or a general tablespace is reused by InnoDB but never returned to the OS. Also: "I can copy .frm + .ibd to move a table." There are no .frm files since 8.0; use transportable tablespaces (FLUSH TABLES … FOR EXPORT, ALTER TABLE … IMPORT TABLESPACE).
Definition:
| Tablespace | File(s) | Holds | Notes |
|---|---|---|---|
| System tablespace | ibdata1 (innodb_data_file_path) | Change buffer; tables only if innodb_file_per_table=OFF | Cannot shrink; only grows |
| File-per-table | schema/table.ibd | One table and its indexes | Default (innodb_file_per_table=ON); space returned on DROP/TRUNCATE |
| General | CREATE TABLESPACE ts1 ADD DATAFILE 'ts1.ibd' | Many tables | Less metadata memory; supports all row formats |
| Undo | undo_001, undo_002, *.ibu | Undo logs | Truncated automatically |
| Global temporary | ibtmp1 | Rollback segments for user temp tables | Recreated at every start |
| Session temporary | #innodb_temp/temp_N.ibt | User and optimizer on-disk temp tables | Pool of 10 at start |
| Data dictionary | mysql.ibd | Data dictionary and mysql.* system tables | InnoDB since 8.0 |
| Redo / doublewrite | #innodb_redo/#ib_redoN, #ib_16384_0.dblwr | Not tablespaces, but part of the same directory | Never delete |
Since MySQL 8.0 the server keeps metadata in a transactional data dictionary instead of .frm, .par, .TRG, .TRN, .isl and db.opt files, which made DDL atomic (crash-safe). The 8.0 "What is new" page puts it this way: "mysql system tables and data dictionary tables are now created in a single InnoDB tablespace file named mysql.ibd". Each .ibd also carries a serialized copy of its own metadata (SDI), readable with ibd2sdi.
Row formats, page size and off-page storage Important
In plain words: the row format decides how a row's bytes are packed into a page, and what happens to long TEXT/BLOB/VARCHAR values that do not fit.
Common misunderstanding: "ROW_FORMAT=COMPRESSED is the modern way to save space." It works, but it costs CPU and buffer pool memory (compressed and uncompressed copies of pages). Many teams use transparent page compression (COMPRESSION='zlib' or 'lz4') or filesystem compression instead, or move cold data to MyRocks.
Definition: the default page size is 16 KB (innodb_page_size, fixed at initialisation; 4/8/16/32/64 KB). A row must fit in about half a page (~8000 bytes for 16 KB) excluding off-page columns, else error 1118 ER_TOO_BIG_ROWSIZE. Default format: innodb_default_row_format=DYNAMIC.
| Row format | Compact headers | Long columns | Index key prefix | Compression | Tablespaces |
|---|---|---|---|---|---|
| REDUNDANT | No | First 768 bytes in-page, rest on overflow pages | 767 bytes | No | system, file-per-table, general |
| COMPACT | Yes (~20% smaller than REDUNDANT) | First 768 bytes in-page | 767 bytes | No | system, file-per-table, general |
| DYNAMIC (default) | Yes | Fully off-page with a 20-byte pointer when too long; ≤40-byte TEXT/BLOB stays inline | 3072 bytes | No | system, file-per-table, general |
| COMPRESSED | Yes | As DYNAMIC; KEY_BLOCK_SIZE sets the compressed page size | 3072 bytes | zlib, per page | file-per-table, general only |
innodb_strict_mode (default ON) turns invalid ROW_FORMAT/KEY_BLOCK_SIZE combinations and over-long rows into errors instead of warnings plus a silently different table.
Real scenario: a products table with 30 VARCHAR(255) utf8mb4 columns fails with 1118 on CREATE TABLE. Under DYNAMIC, the fix is to turn the rarely used ones into TEXT (stored off-page) or normalise them out, not to switch strict mode off.
Row-level vs table-level locking Must-know
In plain words: InnoDB locks the index records a statement touches, so two sessions updating different rows never wait for each other. MyISAM and MEMORY lock the entire table for each write.
Common misunderstanding: "InnoDB locks only the rows I change." Under REPEATABLE READ, locking reads, UPDATE and DELETE with a range condition take next-key locks (record + gap before it) on every index record they scan, so a missing index can lock far more than you expect. Details are in Locks & Concurrency and Deadlocks.
Definition: InnoDB has shared/exclusive record locks, gap locks, next-key locks, insert-intention locks, table-level intention locks and AUTO-INC locks. It never escalates row locks to table locks. Waits end after innodb_lock_wait_timeout (50 s) with 1205 ER_LOCK_WAIT_TIMEOUT (only the statement rolls back), and cycles are detected (innodb_deadlock_detect=ON) and broken with 1213 ER_LOCK_DEADLOCK (SQLSTATE 40001, the whole transaction rolls back). MyISAM takes one table lock per statement. The manual: "MySQL uses table-level locking for MyISAM, MEMORY, and MERGE tables, permitting only one session to update those tables at a time." Those engines cannot deadlock, because they request all locks at the start of a statement.
S1 S2
1 UPDATE stock SET qty=qty-1 WHERE sku='A'; UPDATE stock SET qty=qty-1 WHERE sku='B';
-- InnoDB: both run at once (different rows)
-- MyISAM: S2 shows "Waiting for table level lock" until S1's statement ends
2 SELECT SUM(qty) FROM stock; -- 40 s report on MyISAM
3 UPDATE stock … WHERE sku='C';
-- MyISAM: the writer waits 40 s, and every new reader queues behind the waiting writer
-- InnoDB: the report reads a snapshot; the writer is not blockedReal scenario: a forum on MyISAM where one slow SELECT … ORDER BY RAND() on posts stalls every new post for seconds; converting posts to InnoDB removes the stall without touching the query.
AUTO_INCREMENT handling Good to know
In plain words: InnoDB hands out AUTO_INCREMENT values from an in-memory counter. How strictly it serialises concurrent inserts is set by innodb_autoinc_lock_mode.
Common misunderstanding: "IDs are gapless." Rolled-back inserts, INSERT IGNORE, and bulk inserts in mode 2 all leave gaps. Never use the ID as an invoice number that must be continuous.
Definition: mode 0 (traditional) holds a table-level AUTO-INC lock to the end of every insert statement. Mode 1 (consecutive) does so only for bulk inserts whose row count is unknown. Mode 2 (interleaved, the default since 8.0) takes no table-level AUTO-INC lock, which is fastest, but "not safe when using statement-based replication". Row-based binlog (the default) is safe with all modes. Since 8.0 the counter's maximum is written to the redo log at every change and saved to the data dictionary at each checkpoint, so it persists across restarts. Before 8.0 InnoDB re-computed it with SELECT MAX(id) at startup and could reuse IDs of deleted top rows.
Foreign keys Important
In plain words: InnoDB checks that a child row's parent exists and can cascade deletes or updates. MyISAM accepts the FOREIGN KEY syntax and stores nothing.
Common misunderstanding: "My migration declared the FK, so the data is consistent." On MyISAM (and on MyRocks, which does not support FKs) the declaration silently does nothing.
Definition: InnoDB enforces FKs with shared locks on the parent and requires an index on the referencing columns (it creates one if missing). Violations raise 1452 ER_NO_REFERENCED_ROW_2 (child insert) or 1451 (parent delete). The last violation is shown in SHOW ENGINE INNODB STATUS under LATEST FOREIGN KEY ERROR. Cascaded actions performed by InnoDB do not fire triggers.
SELECT TABLE_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME
FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE();Crash recovery Must-know
In plain words: after a crash InnoDB needs no operator. You restart mysqld; it finds the last checkpoint, replays the redo log forward, repairs torn pages from doublewrite, then rolls back whatever was uncommitted.
Common misunderstanding: "Deleting the redo log files fixes a slow startup." It destroys committed work and can corrupt the tablespace. The manual says removing redo logs "should only be considered after a clean shutdown".
Definition: recovery steps are tablespace discovery, redo application (before connections are accepted), then rollback of incomplete transactions (in the background), then purge and change-buffer merge. The AUTO_INCREMENT maximum and index corruption flags are recovered from redo as well. If startup fails, innodb_force_recovery (1–6) starts the server read-mostly so you can dump data. Above 3 it can lose data permanently.
Restart after kill -9 (InnoDB)
1 [InnoDB] tablespace discovery
2 [InnoDB] Starting crash recovery from checkpoint LSN=…
3 [InnoDB] Apply batch completed (redo replay, doublewrite fixes torn pages)
4 [Server] ready for connections (clients can connect)
5 [InnoDB] Rolling back trx with id … (uncommitted work undone in background)| Engine | After kill -9 or power loss |
|---|---|
| InnoDB | Automatic: committed work kept (with flush_log_at_trx_commit=1), uncommitted rolled back |
| MyISAM | Statements already returned are in the OS cache or on disk; a statement cut mid-way stays half done; table may be marked crashed |
| MEMORY | Table is empty after restart |
| MyRocks | Automatic: RocksDB WAL replay |
| PostgreSQL | Automatic: WAL replay from the last checkpoint |
MyISAM: files, formats and the key cache Must-know
In plain words: a MyISAM table is two plain files. t.MYD holds the rows one after another; t.MYI holds the B-tree indexes, which point to row offsets in .MYD. There is no log and no undo.
Common misunderstanding: "MyISAM caches my data." Its key cache holds only index blocks; the manual: "For data blocks, MySQL uses no special cache. Instead it relies on the native operating system file system cache."
Definition: row formats are fixed (static), dynamic, and compressed (made by myisampack, read-only). The table definition lives in the 8.4 data dictionary; the files are .MYD and .MYI. Each .MYI header has an open counter that is incremented on the first write and decremented on close. A non-zero counter at check time means "clients are using or haven't closed the table properly". Limits: 64 indexes per table, 1000-byte keys, 256 TB. The key cache (key_buffer_size, default 8 MiB) uses its own LRU with an optional midpoint strategy; you can define named key caches and preload indexes (CACHE INDEX, LOAD INDEX INTO CACHE). MyISAM keeps an exact row count in the table header, so SELECT COUNT(*) FROM t with no WHERE is instant. InnoDB must scan an index for the same query, because the answer depends on the reader's snapshot.
In MySQL 8.4, "the MyISAM storage engine provides no partitioning support", and partitioned MyISAM tables from older versions cannot be used.
MyISAM table locks and concurrent inserts Important
In plain words: readers share the table, a writer takes it alone. One exception: if the data file has no holes from deleted rows, INSERTs that append at the end can run while SELECTs read.
Common misunderstanding: "Concurrent inserts mean concurrent writes." Only appends overlap with reads; two inserts still run one after another, and any UPDATE/DELETE waits for all readers.
Definition: concurrent_insert = AUTO (1, default: only when there are no holes), NEVER (0), ALWAYS (2: append even with holes). LOCK TABLES … READ LOCAL allows concurrent inserts while held. INSERT … SELECT from a MyISAM table takes a read lock on the source when the binlog is on.
MyISAM crashes and repair Must-know
In plain words: MyISAM writes each statement's changes to the files before the statement returns, but it never makes a multi-statement change atomic, and a crash in the middle of a statement can leave index and data out of sync.
Common misunderstanding: "If the server comes back, my MyISAM tables are fine." They are only probably fine; check them.
"Even though the MyISAM table format is very reliable (all changes to a table made by an SQL statement are written before the statement returns), you can still get corrupted tables if any of the following events occur" — MySQL 8.4 Reference Manual, "Corrupted MyISAM Tables"
The listed events are: mysqld killed mid-write, an unexpected machine shutdown, hardware failure, an external program such as myisamchk modifying a table the server is using, and bugs. Symptoms: Incorrect key file for table: '...'. Try to repair it, 1194 ER_CRASHED_ON_USAGE ("Table '%s' is marked as crashed and should be repaired"), or queries that silently miss rows.
Fix:
CHECK TABLE legacy_hits; -- status: OK / warning / error
REPAIR TABLE legacy_hits; -- server-side repair (rebuilds .MYI from .MYD)
-- With mysqld stopped (or the table flushed and locked):
-- myisamchk --check /var/lib/mysql/shop/legacy_hits.MYI
-- myisamchk --recover /var/lib/mysql/shop/legacy_hits.MYI
-- mysqlcheck --repair --databases shop (client that issues REPAIR TABLE)
-- my.cnf: myisam_recover_options = BACKUP,FORCE (default OFF; auto-check on open)myisam_recover_options=BACKUP keeps a tbl_name-datetime.BAK copy of the data file before an automatic repair. FORCE repairs even if rows would be lost.
myisampack and FULLTEXT history Good to know
In plain words: myisampack compresses a MyISAM table into a read-only file that is much smaller and still indexable. FULLTEXT search was MyISAM's last unique feature until InnoDB got it in MySQL 5.6.
Common misunderstanding: "We stay on MyISAM for full-text search." Since 5.6 InnoDB has FULLTEXT indexes; an InnoDB developer closed the old feature request with "This functionality is part of 5.6." The 8.4 manual: "Full-text indexes can be used only with InnoDB or MyISAM tables". For serious search, see Full-Text Search.
Definition: myisampack tbl then myisamchk -rq tbl rebuilds indexes; myisamchk --unpack reverses it. InnoDB's equivalents are ROW_FORMAT=COMPRESSED, page compression, or ARCHIVE/MyRocks for cold data.
The other engines: MEMORY, CSV, ARCHIVE, BLACKHOLE, MERGE, FEDERATED Good to know
MEMORY
In plain words: a table whose rows are only in RAM. The definition survives a restart, the rows do not.
Common misunderstanding: "MEMORY is the fast engine for hot data." It has table locks, no transactions, fixed-length rows (a VARCHAR(255) uses 255 × charset bytes), and a size limit per table (max_heap_table_size, default 16 MiB). The manual says "Its use cases are decreasing", because InnoDB with a large buffer pool keeps hot data in memory and durable. Since 8.0, in-memory internal temporary tables use the TempTable engine (internal_tmp_mem_storage_engine=TempTable) and on-disk ones use InnoDB, not MEMORY. MEMORY supports HASH (default) and BTREE indexes.
CSV: data in a .CSV text file plus a .CSM metadata file; no indexes, all columns NOT NULL. Useful to hand a file to a spreadsheet or load one with ALTER TABLE … ENGINE=InnoDB after copying it in.
ARCHIVE: zlib-compressed .ARZ file; supports INSERT, REPLACE and SELECT but not DELETE or UPDATE; only an AUTO_INCREMENT column may be indexed; row-level locking per the manual's feature table.
BLACKHOLE: accepts rows and discards them, but statement-based binlog still records the writes. Used as a relay that filters the binlog for downstream replicas.
MERGE (MRG_MYISAM): a view-like union of identical MyISAM tables. FEDERATED: a table whose rows live on a remote MySQL server (disabled by default). Neither belongs in new designs.
NDB (MySQL NDB Cluster) Good to know
In plain words: NDB is a separate distributed database (data nodes ndbd/ndbmtd, management node ndb_mgmd) that MySQL servers use as a storage engine, ENGINE=NDBCLUSTER.
Common misunderstanding: "NDB is just InnoDB clustered." It is a different engine with its own limits (READ COMMITTED only, different FK and memory model), tuned for in-memory, partitioned, synchronous-replica workloads such as telecom subscriber databases. It is not a drop-in target for an InnoDB application. For general HA on MySQL, use InnoDB with Group Replication (InnoDB Cluster).
MyRocks (RocksDB in MySQL) Important
In plain words: MyRocks replaces InnoDB's update-in-place B-tree with RocksDB's log-structured merge tree: writes are appended, sorted in memory, flushed as immutable files and compacted later.
Common misunderstanding: "MyRocks is a drop-in faster InnoDB." It trades read cost and features for write and space efficiency. Percona lists among InnoDB features it does not support: SAVEPOINT, foreign keys, spatial and full-text indexes, gap locks, and Group Replication. Galera also works only with InnoDB.
Definition: Facebook's description: RocksDB "uses much less space, and has a much smaller write volume (write amplification) with small read penalty compared to a B+ tree database implementation such as InnoDB." It ships in Percona Server for MySQL and MariaDB, not in Oracle MySQL. Data is clustered by PK in column families; compression is per LSM level; bloom filters cut read cost. The LSM theory is on Storage Engines.
Real scenario: a social-network write log on SSD where InnoDB used 2× the space and wore out flash; MyRocks halves space and write volume, accepting slower range reads.
| InnoDB | MyRocks | |
|---|---|---|
| Structure | B+tree, update in place | LSM tree, append + compaction |
| Write amplification | Higher (page rewrites + doublewrite) | Lower |
| Space | Pages ~half to fully used; fragmentation | Dense; strong compression |
| Point reads | One tree walk | Memtable + levels (bloom filters help) |
| FK, FULLTEXT, gap locks | Yes | No |
| Available in | Every MySQL distribution | Percona Server, MariaDB |
Mechanics: how a write really travels
InnoDB architecture: in-memory vs on-disk structures Must-know
MySQL server layer (parser, optimizer, binlog, handler API)
│ ha_innobase
┌────────────────────────────── InnoDB IN-MEMORY STRUCTURES ──────────────────────────────┐
│ Buffer pool (innodb_buffer_pool_size, N instances) │
│ ├─ data + index pages (16 KB) ├─ LRU: young 5/8 │ old 3/8 (midpoint) │
│ ├─ flush list (dirty pages by oldest LSN) ├─ change buffer (if enabled) │
│ └─ adaptive hash index (if enabled) │
│ Log buffer (innodb_log_buffer_size, 64 MiB) ── redo records stamped with LSN │
└──────────────┬───────────────────────────────┬──────────────────────────────┬────────────┘
log writer/flusher threads page cleaner threads purge threads
│ (commit, 1/s) │ (adaptive, io_capacity) │
┌──────────────▼─────────────── InnoDB ON-DISK STRUCTURES ──────▼──────────────▼───────────┐
│ #innodb_redo/#ib_redoN (32 files, innodb_redo_log_capacity) checkpoint LSN in header │
│ #ib_16384_0.dblwr … doublewrite files ──▶ then pages to their home tablespace │
│ ibdata1 (system tablespace: change buffer) mysql.ibd (data dictionary, mysql.*) │
│ shop/orders.ibd, shop/users.ibd (file-per-table) ts1.ibd (general tablespace) │
│ undo_001, undo_002 (undo tablespaces, rollback segments) │
│ ibtmp1 (global temp), #innodb_temp/temp_N.ibt (session temp) │
└──────────────────────────────────────────────────────────────────────────────────────────┘
binary log (server layer): binlog.000123 ── kept in step with redo by two-phase commitThe life of an UPDATE in InnoDB Must-know
UPDATE accounts SET balance = balance - 100 WHERE id = 7; then COMMIT, with default 8.4 settings, binary log on, sync_binlog=1, innodb_flush_log_at_trx_commit=1.
1 server: parse/optimize; handler->index_read(PRIMARY, 7)
2 InnoDB: page with id=7 in buffer pool? no ─▶ read 16 KB from accounts.ibd, insert at LRU midpoint
3 InnoDB: take X record lock on id=7 (REPEATABLE READ; a range would take next-key locks)
4 InnoDB: write undo record (old balance) into an undo page in the buffer pool ─ undo is itself redo-logged
5 InnoDB: change the row in place; set DB_TRX_ID = this trx, DB_ROLL_PTR -> undo record
6 InnoDB: append redo records (undo page change + data page change) to the log buffer; LSN 9_000_120
7 InnoDB: data page is now dirty ─▶ added to the flush list; secondary indexes on balance? none, so done
8 COMMIT ─▶ two-phase commit:
8a InnoDB prepare: redo written and fsync'ed up to the prepare record (group commit batches many trx)
8b server: transaction's events written to binlog; fsync (sync_binlog=1)
8c InnoDB commit: commit marker in redo (no extra fsync needed for durability)
9 client receives OK. The data page is still only in memory; the .ibd file still has the old balance
10 later: page cleaner flushes the dirty page ─▶ doublewrite file (sequential, fsync) ─▶ accounts.ibd
11 later: checkpoint LSN advances past 9_000_120; that part of the redo ring can be reused
12 later: when no read view needs the old version, a purge thread discards the undo record;
History list length drops by one
crash between 9 and 10 ─▶ redo replays step 5 on restart; crash before 8b ─▶ trx rolled backThe binlog step matters for replication. The manual says InnoDB's two-phase commit with XA "is always enabled" in 8.4 and "ensures that the binary log and InnoDB data files are synchronized", and, under "For durability and consistency in a replication setup", recommends sync_binlog=1 plus innodb_flush_log_at_trx_commit=1.
The life of a write in MyISAM, and what a crash does Must-know
UPDATE hits SET n = n + 1 WHERE page_id = 7; on a MyISAM table.
1 server: acquire a WRITE table lock on hits (all readers and writers queue; no row locks exist)
2 MyISAM: first write since open? ─▶ increment open counter in hits.MYI header
3 MyISAM: find row via index blocks in the key cache (key_buffer_size), offset into hits.MYD
4 MyISAM: write new row bytes to hits.MYD with write() ─ into the OS page cache, no fsync, no log
5 MyISAM: update index blocks (key cache), write them to hits.MYI before the statement returns
6 server: release table lock; client receives OK; the statement is already "committed" forever
7 COMMIT / ROLLBACK afterwards: no-op (ROLLBACK -> warning 1196)
Crash scenarios
a mysqld killed during 4–5 ─▶ .MYD and .MYI disagree; table "marked as crashed" (1194)
or "Incorrect key file"; REPAIR TABLE / myisamchk -r
b multi-row UPDATE killed mid-way ─▶ the first half of the rows is updated, the rest is not;
no tool can tell you which
c OS crash or power loss after 6 ─▶ anything still in the OS page cache is gone; nothing replays it
d clean restart after a mysqld kill ─▶ open counter != 0 ─▶ "clients are using or haven't closed
the table properly"; with myisam_recover_options set,
the server checks/repairs on first openDurability, the binary log and replication Important
| Setting | Default (8.4) | What it protects |
|---|---|---|
innodb_flush_log_at_trx_commit | 1 | InnoDB committed data survives an OS crash |
sync_binlog | 1 | Binlog survives an OS crash; replicas and PITR never see a missing transaction |
innodb_doublewrite | ON | Torn 16 KB page writes |
innodb_flush_method | O_DIRECT on Linux if supported (was fsync in 8.0) | Avoids double caching in the OS page cache; data files bypass it, fsync still issued |
innodb_use_fdatasync | ON | Uses fdatasync() where supported for fewer metadata flushes |
| Replica applier metadata | InnoDB table mysql.slave_relay_log_info | Crash-safe replica position, updated atomically with the applied transaction |
The manual adds a caution worth repeating: "Many operating systems and some disk hardware fool the flush-to-disk operation." Durability ends at the weakest cache that lies about fsync. A MyISAM table on a replica breaks crash-safe replication: its changes cannot be committed atomically with the applier position, so after a crash the replica can apply a statement twice or skip it.
Tuning table
Every value below is the MySQL 8.4 default from the manual's variable reference.
| Knob | Default (8.4) | Effect | When to change |
|---|---|---|---|
innodb_buffer_pool_size | 128 MiB | Cache for data + index pages | Always on a server: 50–75% of RAM (dedicated), leave room for connections and OS |
innodb_buffer_pool_instances | 1 if pool ≤ 1 GiB, else min(pool/chunk/2, CPUs/4) | Splits pool mutex contention | Rarely; keep each instance ≥ 1 GB |
innodb_buffer_pool_chunk_size | 128 MiB | Unit for online resize | Huge pools with slow resize |
innodb_old_blocks_pct / innodb_old_blocks_time | 37 / 1000 ms | Scan resistance of the LRU | Large scans still evicting hot data |
innodb_redo_log_capacity | 100 MiB | Redo space; checkpoint distance | Write-heavy: size for ~1 h of peak redo; watch Innodb_redo_log_current_lsn deltas |
innodb_log_file_size | 48 MiB (deprecated) | Old per-file redo size | Remove; use innodb_redo_log_capacity |
innodb_log_buffer_size | 64 MiB | Redo held in RAM before write | Huge transactions with BLOBs |
innodb_flush_log_at_trx_commit | 1 | Commit durability | 2 only where ~1 s loss on OS crash is acceptable |
innodb_flush_log_at_timeout | 1 s | Flush interval for settings 0/2 | Rarely |
innodb_flush_method | O_DIRECT (Linux, if supported) | How data files are opened/flushed | Keep; O_DIRECT_NO_FSYNC only on vetted filesystems |
innodb_io_capacity / _max | 10000 / 2× | Background flush rate | Lower on slow disks (HDD ~200), raise on fast NVMe if dirty pages pile up |
innodb_max_dirty_pages_pct | 90 | Dirty page ceiling | Faster shutdown/failover: lower it |
innodb_flush_neighbors | 0 | Flush adjacent pages together | 1 on spinning disks only |
innodb_change_buffering | none (was all) | Delays secondary-index I/O | I/O-bound bulk DML with many non-unique indexes |
innodb_change_buffer_max_size | 25 (% of pool) | Cap of the change buffer | Heavy insert workloads with change buffering on |
innodb_adaptive_hash_index | OFF (was ON) | Hash shortcuts on hot pages | Benchmark: read-only point lookups that fit in RAM |
innodb_doublewrite | ON | Torn-page protection | Only off with atomic-write storage |
innodb_file_per_table | ON | One .ibd per table | Keep ON |
innodb_default_row_format | DYNAMIC | Row layout of new tables | Keep |
innodb_page_size | 16 KB | Page size, fixed at init | Almost never; set before --initialize |
innodb_strict_mode | ON | Errors instead of warnings on bad table options | Keep ON |
innodb_autoinc_lock_mode | 2 | AUTO-INC concurrency | 1 only if you still use statement-based binlog |
innodb_purge_threads | 1 (≤16 CPUs) else 4 | Purge parallelism | History list keeps growing with spread-out DML |
innodb_max_purge_lag | 0 (off) | Throttle DML when purge lags | Runaway history list on write bursts |
innodb_undo_log_truncate / innodb_max_undo_log_size | ON / 1 GiB | Undo tablespace shrinking | Rarely |
innodb_lock_wait_timeout | 50 s | Row-lock wait limit (error 1205) | OLTP APIs: 3–10 s so requests fail fast |
innodb_deadlock_detect | ON | Cycle detection (error 1213) | Off only at extreme concurrency with a low lock wait timeout |
innodb_dedicated_server | OFF | Auto-size pool and redo | ON for a VM that runs only MySQL |
key_buffer_size | 8 MiB | MyISAM index cache | Small; lower after converting to InnoDB |
concurrent_insert | AUTO | MyISAM append during reads | Rarely |
myisam_recover_options | OFF | Auto-check MyISAM tables on open | BACKUP,FORCE while MyISAM tables still exist |
max_heap_table_size | 16 MiB | Max size of a MEMORY table | Before creating large MEMORY tables |
Error codes you will meet
| Code / symbol | SQLSTATE | Message (verbatim) | Engine context | Retry? |
|---|---|---|---|---|
1213 ER_LOCK_DEADLOCK | 40001 | Deadlock found when trying to get lock; try restarting transaction | InnoDB row locks | Yes, the whole transaction |
1205 ER_LOCK_WAIT_TIMEOUT | HY000 | Lock wait timeout exceeded; try restarting transaction | InnoDB; only the statement is rolled back | Yes, carefully |
1196 ER_WARNING_NOT_COMPLETE_ROLLBACK | HY000 | Some non-transactional changed tables couldn't be rolled back | ROLLBACK touched MyISAM/MEMORY | No: data is already changed |
1194 ER_CRASHED_ON_USAGE | HY000 | Table '%s' is marked as crashed and should be repaired | MyISAM after a crash | After REPAIR TABLE |
1118 ER_TOO_BIG_ROWSIZE | 42000 | Row size too large. … | InnoDB row > ~half a page | No: change the schema |
1286 ER_UNKNOWN_STORAGE_ENGINE | 42000 | Unknown storage engine '%s' | Engine not available | No |
1452 ER_NO_REFERENCED_ROW_2 | 23000 | Cannot add or update a child row: a foreign key constraint fails | InnoDB FK | No |
1062 ER_DUP_ENTRY | 23000 | Duplicate entry '%s' for key %d | Any engine with unique keys | No (idempotency) |
Looking inside: introspection commands Important
SHOW ENGINES; -- what this server supports; Transactions/XA/Savepoints
SHOW TABLE STATUS FROM shop LIKE 'orders'\G -- Engine, Row_format, Rows (estimate for InnoDB), Data_length, Auto_increment
SELECT TABLE_NAME, ENGINE, ROW_FORMAT, TABLE_ROWS, DATA_LENGTH, INDEX_LENGTH, DATA_FREE
FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'shop';
SELECT * FROM information_schema.INNODB_TRX; -- running transactions, lock waits, age
SELECT * FROM performance_schema.data_locks; -- row locks (8.0+; replaces INNODB_LOCKS)
SELECT * FROM performance_schema.data_lock_waits;
SELECT * FROM information_schema.INNODB_BUFFER_POOL_STATS;
SELECT NAME, SUBSYSTEM, COUNT FROM information_schema.INNODB_METRICS WHERE STATUS = 'enabled';
SELECT * FROM information_schema.INNODB_TABLESPACES WHERE NAME LIKE 'shop/%';
SELECT FILE_NAME, START_LSN, END_LSN FROM performance_schema.innodb_redo_log_files;
SHOW ENGINE INNODB STATUS\G -- the Standard Monitor, one text blobReading SHOW ENGINE INNODB STATUS (the output is capped at 1 MB):
| Section | What to look at | Red flag |
|---|---|---|
| Header | Per second averages calculated from the last N seconds | N < 20: averages are noisy, rerun |
| BACKGROUND THREAD | srv_master_thread loops | Mostly srv_active, never idle |
| SEMAPHORES | OS waits, waits on btr0sea.c | Many long waits: AHI or I/O contention |
| LATEST FOREIGN KEY ERROR | The failing statement and constraint | Recurring app bug |
| LATEST DETECTED DEADLOCK | Both transactions, locks held/waited, victim | Same pair repeating: fix access order (Deadlocks) |
| TRANSACTIONS | History list length, ---TRANSACTION … ACTIVE n sec, LOCK WAIT | History list in the millions; transactions active for hours |
| FILE I/O | Pending reads/writes per I/O thread | Pending ops always > 0: disk saturated |
| INSERT BUFFER AND ADAPTIVE HASH INDEX | Change buffer size/merges, hash searches/s | Huge change buffer that never merges |
| LOG | Log sequence number, Log flushed up to, Last checkpoint at | LSN − checkpoint close to redo capacity |
| BUFFER POOL AND MEMORY | Buffer pool hit rate 1000 / 1000, free buffers, Modified db pages | Hit rate below ~990/1000 on OLTP; free buffers 0 with many reads/s |
| ROW OPERATIONS | Inserts/updates/deletes/reads per second | Sudden shift = workload change |
Comparison matrix
| InnoDB | MyISAM | MEMORY | MyRocks | PostgreSQL heap | |
|---|---|---|---|---|---|
| Transactions | Yes (XA, savepoints) | No | No | Yes (no savepoints) | Yes |
| Locking | Row + gap/next-key | Table (+ concurrent insert) | Table | Row, no gap locks | Row (tuple header) + predicate locks for SERIALIZABLE |
| Crash safety | Redo + doublewrite + undo | No; repair needed | Data lost on restart | WAL | WAL + full_page_writes |
| Foreign keys | Yes | No (ignored) | No | No | Yes |
| MVCC | Yes, undo-based | No | No | Yes, LSM versions | Yes, versions in heap |
| Old-version cleanup | Purge threads | n/a | n/a | Compaction | VACUUM / autovacuum |
| Row storage | Clustered B+tree by PK | Heap .MYD + .MYI | Hash/B-tree in RAM | LSM clustered by PK | Unordered heap + separate indexes |
| Secondary index points to | PK value | File offset | Row pointer | PK value | Tuple id (ctid) |
| Compression | COMPRESSED row format, page compression | myisampack (read-only) | No | Yes, per LSM level | TOAST for large values |
| Full-text | Yes (since 5.6) | Yes | No | No | tsvector + GIN |
| Hot physical backup | Percona XtraBackup, MySQL Enterprise Backup, clone plugin | Lock or copy idle files | Not backed up by file copy | Vendor tools | pg_basebackup |
| Group Replication / Galera | Required | No | No | No | n/a |
| Best use | Default for all OLTP | Legacy, read-only packed data | Tiny scratch tables | Write-heavy, space-bound SSD data | PostgreSQL OLTP |
"In PostgreSQL, an UPDATE or DELETE of a row does not immediately remove the old version of the row." — PostgreSQL Documentation, "Routine Vacuuming"
That one sentence is the core difference from InnoDB: InnoDB updates the row in place and moves the old version to undo, so the table itself does not bloat with dead rows. PostgreSQL leaves old versions in the heap, and VACUUM must reclaim them. InnoDB's cost shows up elsewhere: a growing history list, and the PK copied into every secondary index.
What other products do.
| Product | Engine model |
|---|---|
| MySQL (Oracle) | Pluggable: InnoDB default; MyISAM, MEMORY, CSV, ARCHIVE, BLACKHOLE, MERGE, FEDERATED, NDB available |
| Percona Server for MySQL | InnoDB (formerly the XtraDB fork) + MyRocks |
| MariaDB | InnoDB, Aria (crash-safe MyISAM successor used for its system tables), MyRocks, ColumnStore, Spider, S3 and more |
| PostgreSQL | One heap engine; the table access method API allows others |
| SQL Server | Row store with optional clustered index; in-memory OLTP; columnstore |
| Oracle Database | Heap tables, index-organized tables, undo-based consistent reads ("Oracle-style consistent nonlocking reads" is how the MySQL manual describes InnoDB's reads) |
| SQLite | One B-tree format; WITHOUT ROWID tables cluster by PK |
| MongoDB | WiredTiger (B-tree with MVCC and compression) as the default engine |
| CockroachDB | Pebble, an LSM key-value store, under a distributed SQL layer |
| TiDB | MySQL protocol on top of TiKV, which stores data in RocksDB |
| Redis | In-memory structures with optional AOF/RDB persistence; not a relational engine |
Go
Before
The table is ENGINE=MyISAM. The code opens a transaction, runs the debit and "rolls back" on failure. The driver reports success, and the debit stays.
// Package main creates a MyISAM table and then relies on a transaction that
// the engine silently ignores.
package main
import (
"context"
"database/sql"
"errors"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
ctx := context.Background()
db, err := sql.Open("mysql", "app:secret@tcp(127.0.0.1:3306)/shop")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// MyISAM was chosen "because it is fast". It has no transactions.
_, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS accounts (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
balance BIGINT NOT NULL
) ENGINE=MyISAM`)
if err != nil {
log.Fatal(err)
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
log.Fatal(err)
}
if _, err = tx.ExecContext(ctx, `UPDATE accounts SET balance = balance - 100 WHERE id = 1`); err != nil {
log.Fatal(err)
}
// Something goes wrong before the second leg of the transfer...
err = errors.New("credit leg failed")
if err != nil {
// Rollback returns no error, yet the debit above is already permanent:
// MyISAM applied it at statement time and has nothing to undo.
_ = tx.Rollback()
log.Printf("rolled back: %v", err)
}
}After
ENGINE=InnoDB, a transaction wrapped in a function with defer tx.Rollback(), and two inspection queries: the engine of every table from information_schema.TABLES, and SHOW ENGINE INNODB STATUS, printed unparsed.
// Package main uses InnoDB, a real transaction, and asks the server which
// engine every table in the current schema actually uses.
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
ctx := context.Background()
db, err := sql.Open("mysql", "app:secret@tcp(127.0.0.1:3306)/shop")
if err != nil {
log.Fatal(err)
}
defer db.Close()
_, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS accounts (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
balance BIGINT NOT NULL
) ENGINE=InnoDB`)
if err != nil {
log.Fatal(err)
}
if err := transfer(ctx, db, 1, 2, 100); err != nil {
log.Printf("transfer failed, nothing was applied: %v", err)
}
if err := printEngines(ctx, db); err != nil {
log.Fatal(err)
}
// The engine's own view of itself: one big text report, printed as is.
var typ, name, status string
if err := db.QueryRowContext(ctx, `SHOW ENGINE INNODB STATUS`).Scan(&typ, &name, &status); err != nil {
log.Fatal(err)
}
fmt.Println(status)
}
// transfer moves amount between two accounts atomically.
func transfer(ctx context.Context, db *sql.DB, from, to, amount int64) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() // no-op after a successful Commit
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance = balance - ? WHERE id = ?`, amount, from); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance = balance + ? WHERE id = ?`, amount, to); err != nil {
return err
}
return tx.Commit()
}
// printEngines lists every base table in the current schema with its engine.
func printEngines(ctx context.Context, db *sql.DB) error {
rows, err := db.QueryContext(ctx, `SELECT TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var table string
var engine sql.NullString
if err := rows.Scan(&table, &engine); err != nil {
return err
}
fmt.Printf("%-30s %s\n", table, engine.String)
}
return rows.Err()
}The Go angle
database/sql does not know which engine is behind the connection. BeginTx sends START TRANSACTION and Rollback sends ROLLBACK; both succeed against MyISAM, because the server accepts the syntax and the engine has nothing to undo. Warning 1196 is a warning, and go-sql-driver/mysql does not turn warnings into errors, so the only defence is checking the engine (the second snippet) and failing fast. The driver is github.com/go-sql-driver/mysql, "A MySQL-Driver for Go's database/sql package". Its *mysql.MySQLError has a Number field; match 1213 for deadlock retries and 1205 for lock wait timeouts. Keep multiStatements at its default false.
Laravel
Before
A migration sets $table->engine = 'MyISAM' and a service wraps two updates in DB::transaction. Laravel does everything right (BEGIN, exception, ROLLBACK), and the engine ignores all three.
<?php
// database/migrations/2026_01_01_000000_create_accounts_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('accounts', function (Blueprint $table) {
// Chosen long ago for "speed". MyISAM has no transactions.
$table->engine = 'MyISAM';
$table->id();
$table->bigInteger('balance');
$table->timestamps();
});
}
};<?php
// app/Services/TransferService.php
namespace App\Services;
use App\Models\Account;
use Illuminate\Support\Facades\DB;
final class TransferService
{
public function transfer(int $from, int $to, int $amount): void
{
DB::transaction(function () use ($from, $to, $amount) {
Account::whereKey($from)->decrement('balance', $amount);
// If this throws, Laravel issues ROLLBACK and rethrows, but the
// debit above is already permanent: MyISAM cannot undo it.
$credited = Account::whereKey($to)->increment('balance', $amount);
if ($credited === 0) {
throw new \RuntimeException("Account {$to} does not exist");
}
});
}
}After
$table->engine('InnoDB') with explicit charset and collation, a short auto-increment primary key, and an Artisan command that lists tables by engine from information_schema and exits with a failure code if anything is not InnoDB, so CI can run it.
<?php
// database/migrations/2026_01_01_000000_create_accounts_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('accounts', function (Blueprint $table) {
$table->engine('InnoDB');
$table->charset('utf8mb4');
$table->collation('utf8mb4_0900_ai_ci');
// A short, monotonic primary key keeps the clustered index compact
// and keeps every secondary index small.
$table->id();
$table->bigInteger('balance');
$table->timestamps();
});
}
};<?php
// app/Console/Commands/ListTableEngines.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class ListTableEngines extends Command
{
protected $signature = 'db:engines';
protected $description = 'List base tables of the current schema with their storage engine';
public function handle(): int
{
$rows = DB::select(
'SELECT TABLE_NAME AS name, ENGINE AS engine
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = ?
ORDER BY TABLE_NAME',
['BASE TABLE'],
);
$this->table(
['Table', 'Engine'],
array_map(fn (object $r) => [$r->name, $r->engine], $rows),
);
// Fail CI when something other than InnoDB sneaks in.
$offenders = array_filter($rows, fn (object $r) => $r->engine !== 'InnoDB');
return $offenders === [] ? self::SUCCESS : self::FAILURE;
}
}
// Note: innodb_strict_mode is ON by default in 8.4. An invalid ROW_FORMAT or
// KEY_BLOCK_SIZE then fails the migration with an error instead of a warning.
// Do not switch it off to make a migration pass; fix the table options.The Laravel angle
The Laravel 13 migrations page says: "The engine property may be used to specify the table's storage engine when using MariaDB or MySQL", with the method form $table->engine('InnoDB'); charset and collation are documented beside it. The mysql connection in config/database.php has its own engine key; leaving it null defers to the server default (InnoDB). DB::transaction($callback, $attempts) re-runs the closure on deadlocks when $attempts > 1; that retry only exists because InnoDB can deadlock, and it means nothing on MyISAM. See ACID & Transactions.
In production systems
- MySQL 8.4
SHOW ENGINES. On any stock server InnoDB reportsSupport: DEFAULTand "Supports transactions, row-level locking, and foreign keys"; MyISAM reportsTransactions: NO. - The
mysqlsystem schema. The 8.4 manual: "Data dictionary tables and system tables use the InnoDB storage engine unless otherwise indicated", all inmysql.ibd. The server's own metadata became crash-safe the day it moved to InnoDB. - MySQL Group Replication lists as its first requirement: "Data must be stored in the InnoDB transactional storage engine." InnoDB Cluster, and therefore most managed MySQL HA, inherits that rule.
- Percona XtraBackup works only because InnoDB has a redo log:
"Percona XtraBackup is based on InnoDB’s crash-recovery functionality." — Percona XtraBackup 8.4 documentation, "How Percona XtraBackup works"
It copies the live .ibd files (internally inconsistent), keeps copying the redo log, and at prepare time runs crash recovery on the copy. Non-InnoDB tables are copied at the end under LOCK INSTANCE FOR BACKUP / backup locks, which is why every MyISAM table makes backups more invasive.
Solving the classic problems
1. Converting a legacy MyISAM table safely Must-know
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
ALTER TABLE t ENGINE=InnoDB | One statement, table copy | Simple | Copying ALTER: writes blocked for the whole copy; needs 2× space |
Shadow table + INSERT … SELECT … ORDER BY pk + RENAME TABLE | Manual, in batches | Testable side by side | You must stop or replay writes during the switch |
gh-ost / pt-online-schema-change | Tool builds a shadow InnoDB table and syncs changes | Writes keep flowing | pt-online-schema-change uses triggers; gh-ost reads the binlog (needs ROW format) |
Logical dump/restore (mysqldump → sed engine → load) | Offline | Cleans fragmentation | Downtime proportional to size |
Checklist before the switch:
- Inventory: which tables, sizes, and which are written to.
- Primary key: every table needs one (otherwise you get
GEN_CLUST_INDEX). Add it before or during the conversion. - Row size: wide rows that fit MyISAM can fail with
1118; move longVARCHARs toTEXT. - Behavioural differences:
COUNT(*)withoutWHEREbecomes a scan;AUTO_INCREMENTon a secondary column of a composite key (MyISAM's per-group sequences) is not supported by InnoDB; FULLTEXT stopwords and minimum token size differ (innodb_ft_min_token_sizevsft_min_word_len). - Application code: it now gets deadlocks (1213) and lock waits (1205); add retries. Code that relied on "every statement is instantly permanent" inside a transaction now needs
COMMIT. - Memory: after conversion, lower
key_buffer_sizeand give the RAM toinnodb_buffer_pool_size(the manual's own advice). - Verify: row count and an order-independent content hash before and after. (
CHECKSUM TABLEis not usable here: its value depends on the row format, which changes with the engine.)
-- 1. inventory
SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_ROWS, ROUND((DATA_LENGTH+INDEX_LENGTH)/1024/1024) AS mb,
UPDATE_TIME
FROM information_schema.TABLES
WHERE ENGINE = 'MyISAM'
AND TABLE_SCHEMA NOT IN ('mysql','sys','performance_schema','information_schema')
ORDER BY mb DESC;
-- 2. tables without a primary key
SELECT t.TABLE_SCHEMA, t.TABLE_NAME
FROM information_schema.TABLES t
LEFT JOIN information_schema.TABLE_CONSTRAINTS c
ON c.TABLE_SCHEMA = t.TABLE_SCHEMA AND c.TABLE_NAME = t.TABLE_NAME AND c.CONSTRAINT_TYPE = 'PRIMARY KEY'
WHERE t.ENGINE = 'MyISAM' AND c.CONSTRAINT_NAME IS NULL;
-- 3. small table: in place (reads allowed, writes blocked during the copy)
SELECT COUNT(*), BIT_XOR(CRC32(CONCAT_WS('#', id, page_id, n))) FROM legacy_hits; -- before
ALTER TABLE legacy_hits ENGINE=InnoDB, ALGORITHM=COPY, LOCK=SHARED;
SELECT COUNT(*), BIT_XOR(CRC32(CONCAT_WS('#', id, page_id, n))) FROM legacy_hits; -- after: must match
-- 4. later "null rebuild" of an InnoDB table to defragment: online
ALTER TABLE legacy_hits ENGINE=InnoDB, ALGORITHM=INPLACE, LOCK=NONE;Note the difference: changing the engine from MyISAM is a copying ALTER. Online DDL with ALGORITHM=INPLACE, LOCK=NONE applies to InnoDB tables, and ENGINE=InnoDB on a table that is already InnoDB is the documented "null rebuild".
// convertSmallMyISAMTables converts MyISAM tables below maxMB in the current schema.
// Larger tables go through gh-ost or pt-online-schema-change instead.
func convertSmallMyISAMTables(ctx context.Context, db *sql.DB, maxMB int) error {
rows, err := db.QueryContext(ctx, `SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND ENGINE = 'MyISAM'
AND (DATA_LENGTH + INDEX_LENGTH) < ? * 1024 * 1024`, maxMB)
if err != nil {
return err
}
var tables []string
for rows.Next() {
var t string
if err := rows.Scan(&t); err != nil {
rows.Close()
return err
}
tables = append(tables, t)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, t := range tables {
// Identifiers cannot be bound as parameters; names come from information_schema.
stmt := "ALTER TABLE `" + strings.ReplaceAll(t, "`", "``") + "` ENGINE=InnoDB, ALGORITHM=COPY, LOCK=SHARED"
if _, err := db.ExecContext(ctx, stmt); err != nil {
return fmt.Errorf("convert %s: %w", t, err)
}
}
return nil
}<?php
// database/migrations/2026_02_01_000000_convert_legacy_hits_to_innodb.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
// Small table only. Big ones: run gh-ost or pt-online-schema-change outside migrations.
DB::statement('ALTER TABLE legacy_hits ADD PRIMARY KEY (id)');
DB::statement('ALTER TABLE legacy_hits ENGINE=InnoDB, ALGORITHM=COPY, LOCK=SHARED');
}
public function down(): void
{
// Intentionally irreversible: going back to MyISAM loses transactions and FKs.
}
};2. Choosing the primary key for the clustered index Must-know
| PK choice | Insert pattern | Secondary index cost | Verdict |
|---|---|---|---|
BIGINT UNSIGNED AUTO_INCREMENT | Appends at the right edge; pages fill ~15/16 | 8 bytes per entry | Default choice |
BINARY(16) from UUID_TO_BIN(UUID(), 1) (time-ordered swap) | Mostly appending | 16 bytes | When IDs must be generated outside the DB |
UUIDv7 / ULID as BINARY(16) | Time-ordered appends | 16 bytes | Same, generated in the app |
CHAR(36) random UUIDv4 | Random page splits, half-empty pages, poor cache locality | 36+ bytes | Avoid as clustered key |
Natural composite key (tenant_id, order_no) | Appends per tenant | Wide | Good when most queries filter by tenant: rows of one tenant are clustered |
| No PK | Hidden GEN_CLUST_INDEX, 6-byte row id | Hidden id not usable by queries | Never |
CREATE TABLE orders (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
public_id BINARY(16) NOT NULL, -- exposed to clients, from UUID_TO_BIN(UUID(), 1)
customer_id BIGINT UNSIGNED NOT NULL,
total_cents BIGINT NOT NULL,
created_at DATETIME(6) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_public (public_id),
KEY idx_customer_created (customer_id, created_at) -- stores (customer_id, created_at, id)
) ENGINE=InnoDB;// Go: generate a time-ordered UUID in the app (github.com/google/uuid v1.6+) and store its 16 bytes.
id, err := uuid.NewV7()
if err != nil {
return err
}
_, err = db.ExecContext(ctx,
`INSERT INTO orders (public_id, customer_id, total_cents, created_at) VALUES (?, ?, ?, NOW(6))`,
id[:], customerID, totalCents)<?php
// Laravel: keep the auto-increment PK; add an ordered UUID as a separate unique column.
Schema::create('orders', function (Blueprint $table) {
$table->engine('InnoDB');
$table->id(); // BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
$table->binary('public_id', length: 16, fixed: true)->unique();
$table->foreignId('customer_id')->constrained();
$table->bigInteger('total_cents');
$table->timestamps();
$table->index(['customer_id', 'created_at']);
});The full argument (bigint vs UUID vs ULID) is on Schema Design and ID Generation.
3. Diagnosing the buffer pool hit rate Important
Innodb_buffer_pool_read_requests counts logical page reads; Innodb_buffer_pool_reads counts the ones that had to go to disk. Miss ratio = reads / read_requests. On a warmed-up OLTP server it is usually far below 1%. A high miss ratio with free pages at 0 means the working set does not fit; with plenty of free pages it means the data is simply cold.
| Symptom | Likely cause | Action |
|---|---|---|
Miss ratio > 1–2%, Free buffers ≈ 0 | Working set > pool | Grow innodb_buffer_pool_size; drop unused indexes; archive cold rows |
| Misses spike nightly | Backup or report scan | Run on a replica; check innodb_old_blocks_time is not 0 |
| Misses after every restart | Cold cache | Keep buffer pool dump/load ON |
Pages read ahead high, evicted without access high | Wasted read-ahead | Review innodb_read_ahead_threshold; access pattern is random |
| Hit rate fine, still slow | Not a cache problem | Locks, redo stalls, or plans: see Query Planning |
SELECT
MAX(CASE WHEN VARIABLE_NAME = 'Innodb_buffer_pool_reads' THEN VARIABLE_VALUE END) AS disk_reads,
MAX(CASE WHEN VARIABLE_NAME = 'Innodb_buffer_pool_read_requests' THEN VARIABLE_VALUE END) AS logical_reads
FROM performance_schema.global_status
WHERE VARIABLE_NAME IN ('Innodb_buffer_pool_reads', 'Innodb_buffer_pool_read_requests');
SELECT POOL_ID, HIT_RATE, PAGES_MADE_YOUNG, PAGES_NOT_MADE_YOUNG, NUMBER_PAGES_READ_AHEAD,
NUMBER_READ_AHEAD_EVICTED
FROM information_schema.INNODB_BUFFER_POOL_STATS; -- HIT_RATE is per 1000 since last print
-- which tables occupy the pool right now (expensive on large pools: run on a replica)
SELECT TABLE_NAME, COUNT(*) AS pages, ROUND(COUNT(*)*16/1024) AS mb
FROM information_schema.INNODB_BUFFER_PAGE_LRU
GROUP BY TABLE_NAME ORDER BY pages DESC LIMIT 10;// bufferPoolMissRatio samples the two counters twice and returns the miss ratio of the interval.
func bufferPoolMissRatio(ctx context.Context, db *sql.DB, interval time.Duration) (float64, error) {
sample := func() (reads, requests float64, err error) {
rows, err := db.QueryContext(ctx, `SELECT VARIABLE_NAME, VARIABLE_VALUE
FROM performance_schema.global_status
WHERE VARIABLE_NAME IN ('Innodb_buffer_pool_reads', 'Innodb_buffer_pool_read_requests')`)
if err != nil {
return 0, 0, err
}
defer rows.Close()
for rows.Next() {
var name string
var v float64
if err := rows.Scan(&name, &v); err != nil {
return 0, 0, err
}
if name == "Innodb_buffer_pool_reads" {
reads = v
} else {
requests = v
}
}
return reads, requests, rows.Err()
}
r1, q1, err := sample()
if err != nil {
return 0, err
}
time.Sleep(interval)
r2, q2, err := sample()
if err != nil {
return 0, err
}
if q2 == q1 {
return 0, nil
}
return (r2 - r1) / (q2 - q1), nil
}<?php
// app/Console/Commands/BufferPoolHitRate.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class BufferPoolHitRate extends Command
{
protected $signature = 'db:buffer-pool {--seconds=10}';
protected $description = 'Report the InnoDB buffer pool miss ratio over an interval';
public function handle(): int
{
$sample = fn (): array => collect(DB::select(
"SELECT VARIABLE_NAME AS name, VARIABLE_VALUE AS value
FROM performance_schema.global_status
WHERE VARIABLE_NAME IN ('Innodb_buffer_pool_reads', 'Innodb_buffer_pool_read_requests')"
))->pluck('value', 'name')->map(fn ($v) => (float) $v)->all();
$a = $sample();
sleep((int) $this->option('seconds'));
$b = $sample();
$requests = $b['Innodb_buffer_pool_read_requests'] - $a['Innodb_buffer_pool_read_requests'];
$reads = $b['Innodb_buffer_pool_reads'] - $a['Innodb_buffer_pool_reads'];
$miss = $requests > 0 ? $reads / $requests : 0.0;
$this->info(sprintf('logical reads: %d, disk reads: %d, miss ratio: %.4f%%', $requests, $reads, $miss * 100));
return $miss < 0.01 ? self::SUCCESS : self::FAILURE;
}
}4. Durability vs throughput, per flush setting Important
innodb_flush_log_at_trx_commit | sync_binlog | Lost on mysqld crash | Lost on OS crash / power loss | Typical use |
|---|---|---|---|---|
| 1 | 1 | Nothing | Nothing (honest disks) | Primary with money, orders, anything you cannot replay |
| 1 | 0 or N>1 | Nothing in InnoDB | Binlog tail: replicas/PITR may miss transactions InnoDB kept | Avoid on a primary |
| 2 | 1 | Nothing | Up to ~1 s of InnoDB commits; binlog may contain transactions InnoDB lost | Rebuildable replicas |
| 2 | 0 | Nothing | ~1 s, and binlog/InnoDB may disagree | Bulk loads you can redo |
| 0 | 0 | Up to ~1 s | Up to ~1 s | Throwaway migrations, tests |
Throughput comes from fewer fsyncs. With 1/1, group commit already batches many concurrent transactions into one flush, so the gap is largest for a single-threaded writer issuing tiny transactions. The first fix is usually batching (INSERT … VALUES (…), (…) or one transaction per 1000 rows), not weaker durability.
-- per-session batching instead of weakening durability globally
START TRANSACTION;
INSERT INTO events (user_id, kind, at) VALUES (1,'view',NOW(6)), (2,'view',NOW(6)), (3,'click',NOW(6));
-- … up to ~1000 rows …
COMMIT; -- one redo fsync, one binlog fsync
-- a replica that can be re-cloned:
SET PERSIST innodb_flush_log_at_trx_commit = 2;// insertBatch writes many rows in one transaction: one commit, one fsync pair.
func insertBatch(ctx context.Context, db *sql.DB, evs []Event) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
stmt, err := tx.PrepareContext(ctx, `INSERT INTO events (user_id, kind, at) VALUES (?, ?, ?)`)
if err != nil {
return err
}
defer stmt.Close()
for _, e := range evs {
if _, err := stmt.ExecContext(ctx, e.UserID, e.Kind, e.At); err != nil {
return err
}
}
return tx.Commit()
}<?php
// Laravel: chunked inserts, one transaction per chunk.
collect($events)->chunk(1000)->each(function ($chunk) {
DB::transaction(fn () => DB::table('events')->insert($chunk->values()->all()));
});5. Hot counter rows Important
The problem: UPDATE stats SET views = views + 1 WHERE id = 1 from 500 concurrent requests. On InnoDB every transaction takes the X lock on the same row and holds it until commit, so they run one at a time, each paying a commit. On MyISAM it is worse: the whole table is locked for every increment, blocking all readers of stats.
T1 T2 T3
1 UPDATE stats … WHERE id=1; -- X lock
2 UPDATE stats … WHERE id=1; -- waits
3 UPDATE … -- waits
4 COMMIT; -- redo fsync
5 -- granted; COMMIT
6 -- granted; COMMIT
throughput ≈ 1 / (lock hold time + commit latency), no matter how many CPUs| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Short transactions | Increment as the last statement, commit immediately | No schema change | Still one row, one lock |
| Sharded counter | N slot rows per counter; increment a random slot; SUM() to read | Contention ÷ N | Reads aggregate N rows |
| Buffer in Redis | INCR in Redis; flush to MySQL every few seconds | Very high rate | Loss window = flush interval; see Redis |
| Append-only events + rollup | Insert an event row; a job aggregates | No hot row at all | Counter is eventually consistent |
CREATE TABLE counter_slots (
counter_id BIGINT UNSIGNED NOT NULL,
slot TINYINT UNSIGNED NOT NULL,
n BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (counter_id, slot) -- clustered: all slots of one counter on one page
) ENGINE=InnoDB;
INSERT INTO counter_slots (counter_id, slot, n) VALUES (1, FLOOR(RAND() * 16), 1)
ON DUPLICATE KEY UPDATE n = n + 1;
SELECT SUM(n) FROM counter_slots WHERE counter_id = 1;// incrementCounter spreads increments over 16 slot rows to avoid one hot row lock.
func incrementCounter(ctx context.Context, db *sql.DB, counterID int64) error {
slot := rand.IntN(16) // math/rand/v2
_, err := db.ExecContext(ctx, `INSERT INTO counter_slots (counter_id, slot, n) VALUES (?, ?, 1)
ON DUPLICATE KEY UPDATE n = n + 1`, counterID, slot)
return err
}<?php
// Laravel: same sharded counter with the query builder.
DB::statement(
'INSERT INTO counter_slots (counter_id, slot, n) VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE n = n + 1',
[$counterId, random_int(0, 15)],
);
$views = (int) DB::table('counter_slots')->where('counter_id', $counterId)->sum('n');Choosing an engine
| Workload | Engine | Extra technique | Reason |
|---|---|---|---|
| Any OLTP: users, orders, payments, carts | InnoDB | Short monotonic PK, flush_log_at_trx_commit=1, sync_binlog=1 | Transactions, row locks, crash recovery, FKs, hot backup |
| Read-mostly catalog | InnoDB | Large buffer pool; covering indexes | MyISAM no longer wins once data is cached |
| Append-only logs, audit, events | InnoDB (partitioned by time) or MyRocks | Drop old partitions instead of DELETE | InnoDB is fine; MyRocks if space/write volume hurt |
| Write-heavy, huge, SSD-bound | MyRocks (Percona/MariaDB) | Accept no FKs, no gap locks | Lower write amplification, better compression |
| Cold history read once a year | InnoDB COMPRESSED, ARCHIVE, or export to object storage / columnar | Partition + compress | Space; ARCHIVE cannot UPDATE/DELETE |
| Session/scratch data | InnoDB, or Redis outside MySQL | TEMPORARY tables use InnoDB anyway | MEMORY loses data and locks tables |
| Spreadsheet exchange | CSV, then copy into InnoDB | LOAD DATA is usually better | CSV has no indexes |
| Binlog relay filtering | BLACKHOLE | Statement-based binlog on the relay | Stores nothing |
| Five-nines key lookups, telecom | NDB Cluster | Different modelling rules | Shared-nothing synchronous engine |
| Legacy app still on MyISAM | Convert to InnoDB | Checklist above | Every advantage of MyISAM is gone in 8.4 |
| Analytics over billions of rows | Not a MySQL row engine | HeatWave, ClickHouse, a columnar store | See OLTP vs OLAP |
In architecture: from a single process to a distributed system
The storage engine looks like a per-table detail, but backups, replication, failover and even sharding tools assume InnoDB. Each step below adds a component that only works because of the redo log, undo log or transactional data dictionary.
Monolith: one application, one MySQL
Simple: a Laravel shop on one MySQL 8.4 server. Every table is InnoDB (the db:engines command from the Laravel snippet fails CI otherwise). innodb_buffer_pool_size is 60–70% of RAM, durability settings at defaults, nightly Percona XtraBackup plus binlogs for point-in-time recovery (Backup, PITR & DR).
Complex: the same shop inherited a MyISAM search_index table with FULLTEXT and a MEMORY rate_limits table. A checkout transaction writes orders (InnoDB) and bumps search_index (MyISAM). An exception after the MyISAM write leaves the search index pointing at an order that was rolled back. The fix is converting both tables, moving rate limits to Redis, and adding deadlock retries (DB::transaction($fn, 3)).
Modular monolith: several schemas on one instance
Modules catalog, orders and billing each own a schema on one MySQL server. They share one buffer pool, one redo log, one undo history and one purge system. A batch import in catalog can evict orders pages and fill the redo log, and a long report in billing holds back purge for everyone (the history list is instance-wide). Cross-schema transactions work (one InnoDB, one commit), which tempts modules into hidden coupling. Keep the rule "a module writes only its own schema", and watch INNODB_TRX for long transactions per module user.
Microservices: each service owns its MySQL
order-service and payment-service each have their own MySQL. Engine choice is local, but platform tooling (XtraBackup, orchestrators, CDC) assumes InnoDB everywhere. Atomicity ends at the service boundary, and the pattern that restores it depends on InnoDB:
1 order-service: BEGIN; INSERT INTO orders …; INSERT INTO outbox (event='OrderPlaced', …); COMMIT;
-- one InnoDB transaction: both rows or neither (impossible on MyISAM)
2 relay/CDC: reads outbox (polling) or the ROW binlog (Debezium) ─▶ publishes OrderPlaced
3 payment-service: consumes, inserts into inbox (dedupe) + payments in one InnoDB transaction
4 payment-service: outbox ─▶ PaymentCaptured ─▶ order-service marks order paidSee Transactional Outbox and Saga. With a MyISAM outbox table, step 1 could publish an event for an order that never committed.
Distributed data: replicas, Group Replication, Vitess, TiDB
- Async replicas: crash-safe only if the replica's data and its applier position are both InnoDB, which is how 8.4 stores the applier metadata (
mysql.slave_relay_log_info). A MyISAM table on a replica can drift after a replica crash. Details: Replication & Failover. - Group Replication / InnoDB Cluster: "Data must be stored in the InnoDB transactional storage engine." Tables also need a primary key: "Every table that is to be replicated by the group must have a defined primary key, or primary key equivalent", because conflicts are detected per row.
- Galera (MariaDB Galera Cluster, Percona XtraDB Cluster): InnoDB only.
- Vitess: "Vitess is an open-source database clustering system for horizontal scaling of MySQL." Each shard is an ordinary MySQL (InnoDB); the shard key becomes part of your PK design.
- TiDB: speaks the MySQL protocol, but the engine is gone. Data lives in TiKV, and per its docs "There is a RocksDB database within each Store", replicated with Raft.
- NDB Cluster: the distributed engine inside MySQL; a different product to model for.
Scaling path
| Load | What changes in the storage layer |
|---|---|
| 1× | One InnoDB server; set buffer pool, redo capacity, innodb_dedicated_server or explicit sizes; convert every MyISAM table; PKs everywhere |
| 10× | Read replicas; size redo for peak; batch writes; fix hot rows (sharded counters); watch history list length and long transactions; innodb_lock_wait_timeout low for APIs |
| 100× | Shard (Vitess, app-level) or move to distributed SQL (TiDB); time-partition big tables; MyRocks for write-heavy cold data; OLAP to a columnar store |
Lab: the same table in two engines, then kill -9
Outputs in comments are what you should expect on MySQL 8.4; timings and IDs will differ. Crash results for MyISAM are not deterministic: the manual says a killed write can corrupt a table, not that it always does.
Setup (Docker, two terminals A and B):
-- shell: docker run -d --name ms -e MYSQL_ROOT_PASSWORD=pw -p 3306:3306 mysql:8.4
-- shell: docker exec -it ms mysql -uroot -ppw (terminal A and terminal B)
CREATE DATABASE lab; USE lab;
CREATE TABLE acc_innodb (id INT PRIMARY KEY, balance INT NOT NULL) ENGINE=InnoDB;
CREATE TABLE acc_myisam (id INT PRIMARY KEY, balance INT NOT NULL) ENGINE=MyISAM;
INSERT INTO acc_innodb VALUES (1,100),(2,100);
INSERT INTO acc_myisam VALUES (1,100),(2,100);
SHOW TABLE STATUS WHERE Name LIKE 'acc_%'\G -- Engine: InnoDB / MyISAM, Row_format: Dynamic / FixedExperiment 1: ROLLBACK.
-- A
START TRANSACTION;
UPDATE acc_innodb SET balance = balance - 50 WHERE id = 1;
UPDATE acc_myisam SET balance = balance - 50 WHERE id = 1;
ROLLBACK; -- Query OK, 0 rows affected, 1 warning
SHOW WARNINGS; -- 1196 | Some non-transactional changed tables couldn't be rolled back
SELECT (SELECT balance FROM acc_innodb WHERE id=1) AS innodb,
(SELECT balance FROM acc_myisam WHERE id=1) AS myisam; -- 100 | 50Experiment 2: kill -9 in the middle of a transaction.
-- A
START TRANSACTION;
UPDATE acc_innodb SET balance = 0 WHERE id = 2;
UPDATE acc_myisam SET balance = 0 WHERE id = 2;
-- do NOT commit; in a shell: docker kill --signal=KILL ms && docker start ms
-- reconnect
SELECT (SELECT balance FROM lab.acc_innodb WHERE id=2) AS innodb,
(SELECT balance FROM lab.acc_myisam WHERE id=2) AS myisam; -- 100 | 0
-- docker logs ms | grep -i -E 'crash recovery|rolling back|Apply batch'InnoDB rolled the uncommitted update back during crash recovery. MyISAM had already applied it.
Experiment 3: killing a long MyISAM statement.
-- A: build a big MyISAM table
CREATE TABLE big_myisam (id INT AUTO_INCREMENT PRIMARY KEY, pad CHAR(200), KEY(pad)) ENGINE=MyISAM;
INSERT INTO big_myisam (pad) SELECT REPEAT('x',200) FROM information_schema.COLUMNS a, information_schema.COLUMNS b LIMIT 2000000;
UPDATE big_myisam SET pad = REPEAT('y',200); -- while this runs: docker kill --signal=KILL ms; docker start ms
-- after restart
SELECT pad, COUNT(*) FROM lab.big_myisam GROUP BY pad; -- typically both 'x…' and 'y…' rows: half-applied statement
CHECK TABLE lab.big_myisam; -- may report "warning | 1 client is using or hasn't closed the table properly"
-- or "error | Table is marked as crashed"
REPAIR TABLE lab.big_myisam; -- status OK; the half-applied UPDATE stays half appliedRepeat with ENGINE=InnoDB: after restart all rows are still x…, and the error log shows the rollback of the large transaction.
Experiment 4: table lock vs row lock.
-- A (MyISAM): a slow reader holds the table read lock for the statement
SELECT SLEEP(10) FROM acc_myisam; -- 2 rows: ~20 s, table read lock held throughout
-- B within 20 s
UPDATE acc_myisam SET balance = 1 WHERE id = 2; -- waits
SHOW PROCESSLIST; -- State: Waiting for table level lock
-- Repeat with acc_innodb: B's UPDATE returns immediately (A reads a snapshot, row 2 is not locked)Experiment 5: reading SHOW ENGINE INNODB STATUS with a lock wait.
-- A
START TRANSACTION; UPDATE acc_innodb SET balance = balance + 1 WHERE id = 1;
-- B
START TRANSACTION; UPDATE acc_innodb SET balance = balance + 1 WHERE id = 1; -- waits
-- A (third window or A itself)
SHOW ENGINE INNODB STATUS\G
-- TRANSACTIONS
-- Trx id counter …
-- History list length 12
-- ---TRANSACTION 2071, ACTIVE 8 sec starting index read
-- LOCK WAIT 2 lock struct(s), … 1 row lock(s)
-- ------- TRX HAS BEEN WAITING 8 SEC FOR THIS LOCK TO BE GRANTED:
-- RECORD LOCKS space id … index PRIMARY of table `lab`.`acc_innodb` trx id 2071 lock_mode X locks rec but not gap waiting
SELECT trx_id, trx_state, trx_started, trx_mysql_thread_id, trx_query FROM information_schema.INNODB_TRX;
-- B gets 1205 after innodb_lock_wait_timeout (50 s) unless A commitsExperiment 6: watch the history list grow.
-- A: open an old read view
START TRANSACTION WITH CONSISTENT SNAPSHOT; SELECT COUNT(*) FROM acc_innodb;
-- B: churn
UPDATE acc_innodb SET balance = balance + 1; -- run 10 000 times (e.g. a shell loop)
SELECT COUNT FROM information_schema.INNODB_METRICS WHERE NAME = 'trx_rseg_history_len'; -- keeps rising
-- A: COMMIT; then re-run the metric query a few seconds later: it falls as purge catches upCommon misconceptions
| Belief | Reality |
|---|---|
| MyISAM is faster than InnoDB | Only for single-user reads of small, uncached data; under concurrent writes its table lock serialises everything, and InnoDB's buffer pool caches data, not just indexes |
START TRANSACTION/ROLLBACK work on every table | MyISAM, MEMORY, CSV and ARCHIVE ignore them; ROLLBACK only raises warning 1196 |
Commit writes the row to the .ibd file | Commit flushes the redo log; the data page is written later by page cleaners |
innodb_flush_log_at_trx_commit=2 can corrupt InnoDB | It can lose up to ~1 s of commits on an OS crash; recovery still leaves a consistent database |
| Deleting the redo log fixes a server that will not start | It discards committed changes and can corrupt tablespaces; use innodb_force_recovery and dump |
GEN_CLUST_INDEX is as good as a real PK | It is hidden, unusable by queries, shares one global counter, and breaks Group Replication and efficient row-based replication |
| A UUIDv4 string PK costs only its own index | It is copied into every secondary index and scatters inserts across the clustered index |
| Dropping a table always frees disk space | Only for file-per-table; ibdata1 and general tablespaces never shrink |
| A long read-only transaction is harmless | It blocks purge; history list length, undo size and read cost all grow |
| The doublewrite buffer doubles write I/O | It writes sequential batches with one fsync; the overhead is much smaller |
| MEMORY tables are the fast path for hot data | Table locks, no durability, size limits; InnoDB with a big buffer pool is usually faster under concurrency |
| MyISAM is required for FULLTEXT | InnoDB has had FULLTEXT since 5.6 |
| Declaring a FOREIGN KEY on MyISAM enforces it | MyISAM parses and ignores it; MyRocks does not support FKs either |
ALTER TABLE … ENGINE=InnoDB is an online operation | Converting from MyISAM copies the table and blocks writes; use gh-ost/pt-online-schema-change for big tables |
| The change buffer and adaptive hash index are always on | In 8.4 both default to off (innodb_change_buffering=none, innodb_adaptive_hash_index=OFF) |
| MyRocks is a faster InnoDB | It trades read speed and features (FKs, gap locks, savepoints, Group Replication) for write and space efficiency |
Cheat sheet
| Topic | What to remember |
|---|---|
| Default engine | InnoDB since MySQL 5.5; default_storage_engine=InnoDB; system tables InnoDB since 8.0 |
| Must-set knob | innodb_buffer_pool_size = 50–75% of RAM on a dedicated server (default 128 MiB) |
| Durability pair | innodb_flush_log_at_trx_commit=1 + sync_binlog=1 |
| Redo size | innodb_redo_log_capacity (100 MiB default); size for about an hour of peak redo |
| Primary key | Short and monotonic (BIGINT AUTO_INCREMENT or time-ordered BINARY(16)); every secondary index stores it |
| No PK | Hidden GEN_CLUST_INDEX; fix it |
| Old versions | Undo tablespaces; purge threads clean them; watch History list length |
| Torn pages | Doublewrite buffer; keep innodb_doublewrite=ON |
| Files | ibdata1 (change buffer), table.ibd, mysql.ibd, undo_00N, ibtmp1, #innodb_redo/, #innodb_temp/ |
| Row format | DYNAMIC default; rows ≤ ~8000 bytes in a 16 KB page or error 1118; innodb_strict_mode=ON |
| MyISAM | .MYD + .MYI, table locks, key cache for indexes only, no crash safety, REPAIR TABLE / myisamchk |
| Engine inventory | SELECT … FROM information_schema.TABLES WHERE ENGINE <> 'InnoDB' in CI |
| Health check | SHOW ENGINE INNODB STATUS: TRANSACTIONS, LOG, BUFFER POOL AND MEMORY, LATEST DETECTED DEADLOCK |
| Hit rate | Innodb_buffer_pool_reads / Innodb_buffer_pool_read_requests ≪ 1% |
| Errors | 1213 deadlock (retry trx), 1205 lock wait (statement), 1196 non-transactional rollback, 1194 crashed table, 1118 row too big |
| Conversion | Inventory → add PK → ALTER … ENGINE=InnoDB (copy) or gh-ost → retries in app → shrink key_buffer_size |
| HA | Group Replication, Galera and XtraBackup all assume InnoDB |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does the handler API do, and why does it let MySQL mix engines? Good to know
Answer
Answer: It is the C++ interface between the SQL layer and each storage engine, so every table can use a different engine while parser, optimizer and binlog stay shared. See Pluggable storage engines.
2 — Why does InnoDB store rows in a clustered index, and what does a secondary index point to? Must-know
Answer
Answer: Rows live in the leaves of the primary key B+tree; a secondary index stores the primary key value, so a lookup walks two trees. Without a PK InnoDB invents GEN_CLUST_INDEX. See Clustered index.
3 — How does the buffer pool's midpoint insertion protect it from a table scan? Good to know
Answer
Answer: New pages enter at the 3/8 point (old sublist) and only move to the young sublist if touched again after innodb_old_blocks_time, so one scan does not evict the hot set. See Buffer pool.
4 — What exactly does innodb_flush_log_at_trx_commit=1 guarantee, and what does 2 risk? Important
Answer
Answer: 1 fsyncs the redo log at every commit (full ACID durability); 2 writes to the OS cache and fsyncs about once per second, so an OS or power failure can lose roughly a second of commits. See Redo log.
5 — What are undo records used for, and what does a long transaction do to the history list length? Important
Answer
Answer: They rebuild old row versions for MVCC reads and roll back; purge cannot remove them while an old read view exists, so history list length grows and reads slow. See Undo log.
6 — Which problem does the doublewrite buffer solve that redo cannot? Important
Answer
Answer: A torn 16 KB page: redo records are applied to a page that must be intact, so InnoDB keeps a good copy in the doublewrite files to restore it first. See Doublewrite.
7 — In the life of an UPDATE, when does the client get OK, and is the data page on disk by then? Important
Answer
Answer: After the two-phase commit (redo prepare, binlog, commit marker) is durable; the dirty data page is flushed later, and crash recovery replays redo if needed. See Crash recovery.
8 — Why can a MyISAM table be marked as crashed after kill -9, and how do you fix it? Important
Answer
Answer: MyISAM has no log and writes data and index files separately, so an interrupted write can leave them inconsistent; use REPAIR TABLE or myisamchk. Better, convert to InnoDB. See MyISAM repair.
9 — When is MyRocks a better fit than InnoDB, and what do you give up? Good to know
Answer
Answer: Write-heavy, space-bound SSD data, thanks to LSM compaction and compression; you lose gap locks, savepoints and foreign keys. See MyRocks.
10 — How do you convert a large MyISAM table to InnoDB with the least risk? Important
Answer
Answer: Inventory engines, add a primary key, then ALTER TABLE ... ENGINE=InnoDB or use gh-ost, adjust retry logic for deadlocks, and shrink key_buffer_size. See Convert a table.
Glossary
| Term | Meaning |
|---|---|
| pluggable storage engine | MySQL design where each table's storage is delegated to a loadable engine |
| handler API | The C++ handler interface between the MySQL server and an engine (ha_innobase for InnoDB) |
| default_storage_engine | Server variable naming the engine used when CREATE TABLE has no ENGINE clause (InnoDB) |
| InnoDB | MySQL's default transactional engine: clustered B+trees, row locks, MVCC, redo/undo, crash recovery |
| XtraDB | Percona's former InnoDB fork, used in older Percona Server and Galera-based products |
| MyISAM | Legacy non-transactional engine: .MYD + .MYI, table locks, no crash safety |
| Aria | MariaDB's crash-safe successor to MyISAM |
| MEMORY | Engine keeping rows in RAM (formerly HEAP); data lost on restart |
| TempTable | Engine for in-memory internal temporary tables since 8.0 |
| CSV | Engine storing rows in a comma-separated .CSV text file, no indexes |
| ARCHIVE | Compressed insert-only engine (.ARZ), index only on AUTO_INCREMENT |
| BLACKHOLE | Engine that discards writes but still logs them to the binlog |
| MERGE | MRG_MYISAM: union of identical MyISAM tables |
| FEDERATED | Engine whose rows live on a remote MySQL server |
| NDB | NDBCLUSTER, the distributed engine of MySQL NDB Cluster |
| MyRocks | RocksDB-based engine in Percona Server and MariaDB |
| RocksDB | Embedded LSM key-value store from Facebook, used by MyRocks and TiKV |
| LSM | Log-structured merge tree: append to memtable, flush sorted files, compact |
| WiredTiger | MongoDB's default B-tree/MVCC storage engine |
| clustered index | The index whose leaves hold the full rows; in InnoDB, the PK B-tree |
| index-organized table | Oracle's name for a table stored as its PK index, like InnoDB's clustered index |
| secondary index | Any other InnoDB index; each entry stores the indexed columns plus the PK |
| GEN_CLUST_INDEX | Hidden clustered index InnoDB creates on a 6-byte row id when there is no PK or suitable unique key |
| DB_ROW_ID | 6-byte hidden row id used by GEN_CLUST_INDEX |
| DB_TRX_ID | 6-byte hidden field: id of the last transaction that changed the row |
| DB_ROLL_PTR | 7-byte hidden field pointing to the row's undo record |
| page / 16 KB | InnoDB's unit of I/O and caching; default innodb_page_size 16 KB |
| innodb_page_size | Page size chosen at initialisation: 4, 8, 16 (default), 32 or 64 KB |
| buffer pool | InnoDB's RAM cache of data and index pages |
| innodb_buffer_pool_size | Size of the buffer pool; default 128 MiB |
| innodb_buffer_pool_instances | Number of independently latched buffer pool regions |
| innodb_buffer_pool_chunk_size | Unit by which the pool is resized online (128 MiB) |
| midpoint insertion | LRU strategy: new pages enter at the head of the old sublist (3/8), not the top |
| innodb_old_blocks_pct | Share of the LRU reserved for the old sublist (37) |
| innodb_old_blocks_time | Milliseconds a page must stay in the old sublist before a touch makes it young (1000) |
| read-ahead | Prefetching pages InnoDB expects to need; counted in buffer pool stats |
| flush list | List of dirty pages ordered by the LSN of their first change |
| page cleaner | Background threads that flush dirty pages |
| change buffer | Structure that defers changes to uncached secondary-index pages |
| innodb_change_buffering | Which operations are change-buffered; none by default in 8.4 |
| adaptive hash index | Hash index InnoDB builds automatically over hot B-tree pages |
| innodb_adaptive_hash_index | Switch for the adaptive hash index; OFF by default in 8.4 |
| log buffer | RAM area holding redo records before they are written |
| innodb_log_buffer_size | Size of the log buffer (64 MiB in 8.4) |
| redo log | On-disk physical log of page changes, replayed during crash recovery |
| #innodb_redo | Directory holding the 32 redo files #ib_redoN |
| innodb_redo_log_capacity | Total redo log size (100 MiB default) |
| innodb_log_file_size | Deprecated per-file redo size, used only if capacity is unset |
| LSN | Log sequence number: ever-increasing position in the redo stream |
| innodb_flush_log_at_trx_commit | 1 = write+flush per commit, 2 = write per commit/flush per second, 0 = both per second |
| innodb_flush_log_at_timeout | Seconds between flushes for settings 0 and 2 (1) |
| innodb_flush_method | How data/log files are opened and flushed; O_DIRECT on Linux by default in 8.4 |
| O_DIRECT | Open flag bypassing the OS page cache for data files |
| undo log | Records of previous row versions, for rollback and consistent reads |
| rollback segment | Container of undo logs inside an undo tablespace (128 per tablespace) |
| undo tablespace | Files holding undo logs (undo_001, undo_002, *.ibu) |
| innodb_undo_log_truncate | Automatic shrinking of oversized undo tablespaces (ON) |
| purge | Background removal of delete-marked rows and unneeded undo records |
| purge thread | Thread doing purge; count set by innodb_purge_threads |
| innodb_purge_threads | Maximum purge threads: 1 if ≤16 CPUs, else 4 |
| innodb_max_purge_lag | History length above which DML is delayed (0 = off) |
| history list length | Number of committed undo logs not yet purged |
| MVCC | Multi-version concurrency control: readers see a snapshot built from undo |
| consistent read | Nonlocking read of a snapshot, rebuilt from undo where needed |
| doublewrite buffer | Area where flushed pages are written first so torn pages can be repaired |
| innodb_doublewrite | Doublewrite switch: ON/DETECT_AND_RECOVER, DETECT_ONLY, OFF |
| torn page | A page only partly written when a crash hit |
| checkpoint | Redo position before which all changes are in the data files |
| fuzzy checkpoint | Checkpointing by flushing small batches continuously instead of all at once |
| innodb_io_capacity | Background I/O budget for flushing (10000 in 8.4) |
| innodb_max_dirty_pages_pct | Target ceiling for dirty pages in the pool (90) |
| crash recovery | Automatic redo replay plus rollback of uncommitted work on restart |
| tablespace | Logical storage container of InnoDB pages, backed by one or more files |
| system tablespace | ibdata1; holds the change buffer (and tables if file-per-table is off) |
| ibdata1 | Default file of the system tablespace; never shrinks |
| file-per-table | One tablespace (.ibd) per table; the default |
| innodb_file_per_table | Switch for file-per-table tablespaces (ON) |
| .ibd | Data file of a file-per-table or general tablespace |
| general tablespace | Shared tablespace created with CREATE TABLESPACE |
| temporary tablespace | ibtmp1 (global) and #innodb_temp/*.ibt (session) |
| ibtmp1 | Global temporary tablespace with rollback segments for temp tables |
| mysql.ibd | Tablespace of the data dictionary and mysql.* system tables |
| data dictionary | Transactional metadata store introduced in 8.0, replacing metadata files |
| .frm | Pre-8.0 table definition file; removed in 8.0 |
| row format | Physical layout of rows: REDUNDANT, COMPACT, DYNAMIC, COMPRESSED |
| REDUNDANT | Oldest row format; 768-byte prefix of long columns in-page |
| COMPACT | ~20% smaller headers than REDUNDANT; 768-byte prefix in-page |
| DYNAMIC | Default; long columns fully off-page with a 20-byte pointer |
| COMPRESSED | DYNAMIC plus zlib page compression; needs file-per-table or general tablespace |
| innodb_default_row_format | Row format for new tables (DYNAMIC) |
| KEY_BLOCK_SIZE | Compressed page size for ROW_FORMAT=COMPRESSED |
| off-page | Long column values stored outside the B-tree leaf |
| overflow page | Page holding an off-page column value |
| innodb_strict_mode | Errors instead of warnings for invalid table options (ON) |
| row-level locking | Locking individual index records (InnoDB, NDB, MyRocks) |
| table-level locking | Locking the whole table per statement (MyISAM, MEMORY, MERGE) |
| gap lock | InnoDB lock on the gap between index records, blocking inserts |
| next-key lock | Record lock plus gap lock on the gap before it |
| innodb_lock_wait_timeout | Seconds a row-lock wait lasts before error 1205 (50) |
| AUTO_INCREMENT | Column attribute generating increasing ids; counter persisted since 8.0 |
| innodb_autoinc_lock_mode | 0 traditional, 1 consecutive, 2 interleaved (default since 8.0) |
| foreign key | Referential constraint; enforced by InnoDB and NDB only |
| key cache | MyISAM's index block cache, sized by key_buffer_size |
| key_buffer_size | Size of the MyISAM key cache (8 MiB) |
| .MYD | MyISAM data file |
| .MYI | MyISAM index file with the open counter in its header |
| concurrent_insert | MyISAM setting allowing appends while reading (AUTO) |
| myisamchk | Offline MyISAM check/repair utility |
| mysqlcheck | Client that runs CHECK/REPAIR/OPTIMIZE TABLE on a live server |
| CHECK TABLE | SQL statement that checks a table for errors |
| REPAIR TABLE | SQL statement that repairs a MyISAM/ARCHIVE/CSV table |
| myisam_recover_options | Automatic check/repair of MyISAM tables on open (OFF) |
| myisampack | Tool producing compressed, read-only MyISAM tables |
| FULLTEXT | Full-text index type; MyISAM always, InnoDB since 5.6 |
| information_schema.TABLES | Dictionary view with ENGINE, ROW_FORMAT, sizes per table |
| SHOW ENGINES | Lists available engines and their transaction/XA/savepoint support |
| SHOW TABLE STATUS | Per-table engine, row format, row estimate, sizes, Auto_increment |
| SHOW ENGINE INNODB STATUS | InnoDB Standard Monitor report |
| LATEST DETECTED DEADLOCK | Monitor section with the last deadlock's transactions and victim |
| INNODB_TRX | information_schema table of running InnoDB transactions |
| INNODB_METRICS | information_schema table of InnoDB counters |
| INNODB_BUFFER_POOL_STATS | information_schema table of per-instance buffer pool statistics |
| Innodb_buffer_pool_reads | Status counter: logical reads that missed the pool and went to disk |
| Innodb_buffer_pool_read_requests | Status counter: logical page read requests |
| ENGINE=InnoDB | Table option selecting InnoDB; also the conversion ALTER TABLE … ENGINE=InnoDB |
| online DDL | InnoDB's INSTANT/INPLACE ALTER modes that allow concurrent DML |
| ALGORITHM=INPLACE | ALTER clause requesting a no-copy rebuild |
| gh-ost | GitHub's binlog-based online schema change tool |
| pt-online-schema-change | Percona Toolkit's trigger-based online schema change tool |
| binlog | Server-level binary log of changes, used by replication and PITR |
| sync_binlog | How often the binlog is fsync'ed (1 = every commit group) |
| two-phase commit | Prepare in InnoDB, write binlog, commit in InnoDB, keeping both consistent |
| Group Replication | MySQL's Paxos-based multi-primary/single-primary replication; InnoDB only |
| Galera | Synchronous replication used by MariaDB Galera Cluster and Percona XtraDB Cluster; InnoDB only |
| Vitess | Sharding and clustering layer over many MySQL instances |
| TiDB | Distributed SQL database with the MySQL protocol, storing data in TiKV/RocksDB |
| Percona XtraBackup | Hot physical backup tool that relies on InnoDB crash recovery |
| LOCK INSTANCE FOR BACKUP | 8.x backup lock blocking DDL but not DML during backups |
| PostgreSQL heap | PostgreSQL's unordered table storage; indexes point to tuple ids |
| VACUUM | PostgreSQL process reclaiming dead tuple versions from the heap |
| MySQL 5.5 | Release in which InnoDB became the default engine (WL#5349) |
| ER_LOCK_DEADLOCK | Error 1213, SQLSTATE 40001: transaction chosen as deadlock victim |
| ER_LOCK_WAIT_TIMEOUT | Error 1205: row-lock wait exceeded innodb_lock_wait_timeout |
| ER_WARNING_NOT_COMPLETE_ROLLBACK | Warning 1196: non-transactional tables could not be rolled back |
| ER_CRASHED_ON_USAGE | Error 1194: table marked as crashed and should be repaired |
| ER_TOO_BIG_ROWSIZE | Error 1118: row size too large for the page |
| ER_UNKNOWN_STORAGE_ENGINE | Error 1286: engine not available on this server |
| innodb_dedicated_server | Auto-sizes buffer pool and redo capacity for a MySQL-only host |
| innodb_deadlock_detect | Turns InnoDB's deadlock detector on (default) or off |
References
- MySQL 8.4 Reference Manual: Alternative Storage Engines, Overview of MySQL Storage Engine Architecture
- MySQL Worklog WL#5349: Change default storage engine to InnoDB
- MySQL 8.4: Introduction to InnoDB, InnoDB Architecture, In-Memory Structures, On-Disk Structures
- MySQL 8.4: Buffer Pool, Change Buffer, Adaptive Hash Index, Log Buffer, Buffer Pool Resizing
- MySQL 8.4: Redo Log, Undo Logs, Undo Tablespaces, Purge Configuration, Multi-Versioning
- MySQL 8.4: Doublewrite Buffer, Checkpoints, InnoDB Recovery
- MySQL 8.4: System Tablespace, File-Per-Table Tablespaces, General Tablespaces, Temporary Tablespaces
- MySQL 8.4: Row Formats, InnoDB Limits, Clustered and Secondary Indexes, AUTO_INCREMENT Handling, InnoDB Locking, Internal Locking Methods
- MySQL 8.4: InnoDB Startup Options and System Variables, Server System Variables, Dedicated Server, What Is New in MySQL 8.4
- MySQL 8.4: Standard Monitor Output, INNODB_METRICS, Buffer Pool I_S Tables, INNODB_TRX
- MySQL 8.4: Data Dictionary, Removal of File-based Metadata Storage, System Schema; MySQL 8.0 What Is New in MySQL 8.0
- MySQL 8.4: MyISAM, MyISAM Table Storage Formats, Corrupted MyISAM Tables, Tables Not Closed Properly, MyISAM Key Cache, Concurrent Inserts, MyISAM Startup Options, myisamchk, myisampack
- MySQL 8.4: MEMORY, CSV, ARCHIVE, BLACKHOLE, MERGE, FEDERATED, NDB Cluster, Full-Text Search
- MySQL 8.4: Converting Tables from MyISAM to InnoDB, Online DDL, Online DDL Operations
- MySQL 8.4: The Binary Log, Handling an Unexpected Halt of a Replica, Group Replication Requirements, Server Error Message Reference
- MySQL Bug #13979 InnoDB engine doesn't support FULLTEXT
- Percona: How Percona XtraBackup works, MyRocks introduction, MyRocks limitations
- MariaDB: About MyRocks for MariaDB; Facebook mysql-5.6 wiki (MyRocks)
- Vitess: What is Vitess; PingCAP TiDB Architecture, TiKV Overview
- PostgreSQL: Routine Vacuuming, Database Page Layout
- Laravel 13: Migrations, Database: Getting Started; go-sql-driver/mysql