Skip to content

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 forGo to
A one-screen summary you can memoriseEverything in one minute
What "pluggable storage engine" and the handler API meanPluggable engines
How InnoDB lays out rows (clustered index, GEN_CLUST_INDEX)Clustered index
Buffer pool, LRU midpoint insertion, change buffer, adaptive hash indexBuffer pool
Redo log, log buffer, innodb_flush_log_at_trx_commitRedo log
Undo log, purge, history list lengthUndo log
Doublewrite buffer, torn pages, checkpointsDoublewrite
ibdata1, .ibd, tablespaces, the 8.0 data dictionaryTablespaces
Row formats (REDUNDANT, COMPACT, DYNAMIC, COMPRESSED), off-page storageRow formats
How MyISAM stores data, key cache, table locks, repairMyISAM
MEMORY, CSV, ARCHIVE, BLACKHOLE, NDB, MyRocksThe other engines
The life of an UPDATE in InnoDB, and of a write in MyISAMMechanics
Every knob with its default and when to change itTuning table
Feature matrix InnoDB × MyISAM × MEMORY × MyRocks × PostgreSQLComparison matrix
Converting MyISAM, picking a PK, hit rate, flush settings, hot rowsSolving the classic problems
Which engine for which workloadChoosing an engine
Monolith → microservices → Group Replication/Vitess/TiDBIn architecture
A hands-on crash testLab

Everything in one minute ​

The engines.

EngineOne lineTransactionsLockingSurvives a crash?Use it for
InnoDBDefault since MySQL 5.5. Rows live inside the primary-key B-tree. Has redo and undo logsYesRowYes: redo + doublewrite + undoEverything, unless you have a proven reason not to
MyISAMTwo files per table (.MYD data, .MYI index), no logNoTableNo: may need REPAIR TABLELegacy only; read-only packed data
MEMORYRows in RAM, formerly HEAPNoTableData is lost on restart (the table definition stays)Small scratch or lookup tables
CSVA plain .CSV text file, no indexesNoTablen/aImport/export with spreadsheets and scripts
ARCHIVECompressed, insert-only, indexed only on AUTO_INCREMENTNoRown/aRarely read history
BLACKHOLEAccepts writes, stores nothing, still writes the binlogNon/an/aBinlog relay/filter tricks
NDBThe engine of MySQL NDB Cluster: distributed, shared-nothingYesRowYes (cluster)Telecom-style HA key lookups
MyRocksRocksDB (LSM tree) inside MySQL; ships with Percona Server and MariaDB, not Oracle MySQLYesRow, no gap locksYes (WAL)Write-heavy, space-sensitive data on SSD

InnoDB's moving parts.

StructureLives inJob in one line
Buffer poolRAMCaches 16 KB data and index pages; the main memory knob
Change bufferRAM + system tablespaceDelays writes to secondary-index pages that are not cached (off by default in 8.4)
Adaptive hash indexRAMHash shortcut over hot B-tree pages (off by default in 8.4)
Log bufferRAMHolds redo records until they are written to the redo log
Redo log#innodb_redo/ filesPhysical record of every page change; replayed after a crash
Undo logUndo tablespaces (undo_001, undo_002)Old row versions for rollback and MVCC reads
Doublewrite buffer#ib_*.dblwr filesA second copy of each flushed page, so a torn page can be repaired
Tablespacesibdata1, *.ibd, mysql.ibd, ibtmp1, #innodb_temp/Where pages finally live on disk

InnoDB vs MyISAM in six lines.

QuestionInnoDBMyISAM
ROLLBACK after two updatesBoth undoneNothing undone; warning 1196
Two sessions update different rowsBoth proceedSecond waits for the table lock
kill -9 in the middle of a writeRestart replays redo, rolls back uncommitted workTable may be marked as crashed; partial changes stay
Foreign keysEnforcedParsed and ignored
Row order on diskPrimary-key order (clustered)Insertion order (heap file)
CacheBuffer pool caches data and indexKey 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 supported

The 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 writeEvery change also goes to a log, and often a second page copy
One lock per table: no deadlocks, no row-lock memoryRow locks: concurrency, plus deadlocks and lock waits to handle
Nothing to roll back, so nothing to recoverUndo, redo and doublewrite make crash recovery automatic
Small on disk, small in memoryBuffer pool, undo history and redo capacity to size and watch
A crash may leave a table you must repairA 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 ​

  1. "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.
  2. "START TRANSACTION makes any table transactional." The server accepts the statement for every engine. MyISAM applies each statement immediately, and ROLLBACK only returns warning 1196 (ER_WARNING_NOT_COMPLETE_ROLLBACK).
  3. "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 4

Real 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.

sql
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-row events table: 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.
ProductWhere the row livesWhat a secondary index points to
MySQL InnoDBLeaf of the PK B-tree (clustered)PK value
MySQL MyISAM.MYD heap file, insertion orderFile offset in .MYD
PostgreSQLHeap pages, any orderPhysical tuple id (ctid)
SQL ServerClustered index if one is declared, otherwise a heapClustering key, or RID for a heap
OracleHeap by default; index-organized table (IOT) on requestROWID (heap) or logical rowid (IOT)
SQLiteB-tree keyed by rowid; WITHOUT ROWID clusters by the PKrowid or PK
MyRocksLSM tree keyed by PKPK 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 LSN

Real 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.
EngineData cacheIndex cache
InnoDBBuffer poolBuffer pool
MyISAMNone (OS page cache)Key cache (key_buffer_size, default 8 MiB)
MEMORYThe table is the memorySame
MyRocksRocksDB block cacheSame
PostgreSQLshared_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.

sql
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 steps

Change 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:

ValueAt each commitFlushed to diskWhat a crash can lose
1 (default)Write to OS and fsyncEvery commitNothing committed (if the disk honours fsync)
2Write to OSAbout once per innodb_flush_log_at_timeout (1 s)mysqld crash: nothing. OS crash / power loss: up to ~1 s
0NothingWrite + flush about once per secondUp 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 stalls

Real 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 follows

Real 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.

ProductWhere old versions liveWho cleans them up
MySQL InnoDBUndo tablespaces (rollback segments)Purge threads
PostgreSQLIn the heap, next to live tuplesVACUUM / autovacuum
OracleUndo tablespaceUndo retention
MyRocksOlder key versions in the LSM treeCompaction, once no snapshot needs them
MyISAM, MEMORYNo old versions (no MVCC)n/a

Fix:

sql
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 it

Doublewrite 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 redo

PostgreSQL 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:

TablespaceFile(s)HoldsNotes
System tablespaceibdata1 (innodb_data_file_path)Change buffer; tables only if innodb_file_per_table=OFFCannot shrink; only grows
File-per-tableschema/table.ibdOne table and its indexesDefault (innodb_file_per_table=ON); space returned on DROP/TRUNCATE
GeneralCREATE TABLESPACE ts1 ADD DATAFILE 'ts1.ibd'Many tablesLess metadata memory; supports all row formats
Undoundo_001, undo_002, *.ibuUndo logsTruncated automatically
Global temporaryibtmp1Rollback segments for user temp tablesRecreated at every start
Session temporary#innodb_temp/temp_N.ibtUser and optimizer on-disk temp tablesPool of 10 at start
Data dictionarymysql.ibdData dictionary and mysql.* system tablesInnoDB since 8.0
Redo / doublewrite#innodb_redo/#ib_redoN, #ib_16384_0.dblwrNot tablespaces, but part of the same directoryNever 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 formatCompact headersLong columnsIndex key prefixCompressionTablespaces
REDUNDANTNoFirst 768 bytes in-page, rest on overflow pages767 bytesNosystem, file-per-table, general
COMPACTYes (~20% smaller than REDUNDANT)First 768 bytes in-page767 bytesNosystem, file-per-table, general
DYNAMIC (default)YesFully off-page with a 20-byte pointer when too long; ≤40-byte TEXT/BLOB stays inline3072 bytesNosystem, file-per-table, general
COMPRESSEDYesAs DYNAMIC; KEY_BLOCK_SIZE sets the compressed page size3072 byteszlib, per pagefile-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 blocked

Real 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.

sql
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)
EngineAfter kill -9 or power loss
InnoDBAutomatic: committed work kept (with flush_log_at_trx_commit=1), uncommitted rolled back
MyISAMStatements already returned are in the OS cache or on disk; a statement cut mid-way stays half done; table may be marked crashed
MEMORYTable is empty after restart
MyRocksAutomatic: RocksDB WAL replay
PostgreSQLAutomatic: 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:

sql
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.

InnoDBMyRocks
StructureB+tree, update in placeLSM tree, append + compaction
Write amplificationHigher (page rewrites + doublewrite)Lower
SpacePages ~half to fully used; fragmentationDense; strong compression
Point readsOne tree walkMemtable + levels (bloom filters help)
FK, FULLTEXT, gap locksYesNo
Available inEvery MySQL distributionPercona 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)IN MEMORY (InnoDB)Buffer pool (innodb_buffer_pool_size)data + index pages 16 KB, LRU young 5/8 | old 3/8flush list, change buffer, adaptive hash indexLog bufferredo records stamped with LSNinnodb_log_buffer_sizeON DISK (InnoDB)flush (cleaner)flush (cleaner)log writer / flusherDoublewrite filesTablespaces (.ibd)Redo log #innodb_redo#ib_16384_0.dblwrtorn-page safety copyfile-per-table, general,system (ibdata1), mysql.ibd32 files, circular,checkpoint LSN in header
                         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 commit

The life of an UPDATE in InnoDB Must-know ​

Foreground (the statement and COMMIT)1 Buffer poolload page,X row lock2 Undoold value toundo page3 Redochange row,append to log buf4 Prepareredo fsync,binlog fsync5 Commitcommit markerin redo6 OKclient seessuccess7 Flushdirty page todoublewrite, .ibd8 Checkpointcheckpoint LSNadvances, redo reused9 Purgeold undo discarded,history list shrinksBackground (after the client already has OK)

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 back

The 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 open

Durability, the binary log and replication Important ​

SettingDefault (8.4)What it protects
innodb_flush_log_at_trx_commit1InnoDB committed data survives an OS crash
sync_binlog1Binlog survives an OS crash; replicas and PITR never see a missing transaction
innodb_doublewriteONTorn 16 KB page writes
innodb_flush_methodO_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_fdatasyncONUses fdatasync() where supported for fewer metadata flushes
Replica applier metadataInnoDB table mysql.slave_relay_log_infoCrash-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.

KnobDefault (8.4)EffectWhen to change
innodb_buffer_pool_size128 MiBCache for data + index pagesAlways on a server: 50–75% of RAM (dedicated), leave room for connections and OS
innodb_buffer_pool_instances1 if pool ≤ 1 GiB, else min(pool/chunk/2, CPUs/4)Splits pool mutex contentionRarely; keep each instance ≥ 1 GB
innodb_buffer_pool_chunk_size128 MiBUnit for online resizeHuge pools with slow resize
innodb_old_blocks_pct / innodb_old_blocks_time37 / 1000 msScan resistance of the LRULarge scans still evicting hot data
innodb_redo_log_capacity100 MiBRedo space; checkpoint distanceWrite-heavy: size for ~1 h of peak redo; watch Innodb_redo_log_current_lsn deltas
innodb_log_file_size48 MiB (deprecated)Old per-file redo sizeRemove; use innodb_redo_log_capacity
innodb_log_buffer_size64 MiBRedo held in RAM before writeHuge transactions with BLOBs
innodb_flush_log_at_trx_commit1Commit durability2 only where ~1 s loss on OS crash is acceptable
innodb_flush_log_at_timeout1 sFlush interval for settings 0/2Rarely
innodb_flush_methodO_DIRECT (Linux, if supported)How data files are opened/flushedKeep; O_DIRECT_NO_FSYNC only on vetted filesystems
innodb_io_capacity / _max10000 / 2×Background flush rateLower on slow disks (HDD ~200), raise on fast NVMe if dirty pages pile up
innodb_max_dirty_pages_pct90Dirty page ceilingFaster shutdown/failover: lower it
innodb_flush_neighbors0Flush adjacent pages together1 on spinning disks only
innodb_change_bufferingnone (was all)Delays secondary-index I/OI/O-bound bulk DML with many non-unique indexes
innodb_change_buffer_max_size25 (% of pool)Cap of the change bufferHeavy insert workloads with change buffering on
innodb_adaptive_hash_indexOFF (was ON)Hash shortcuts on hot pagesBenchmark: read-only point lookups that fit in RAM
innodb_doublewriteONTorn-page protectionOnly off with atomic-write storage
innodb_file_per_tableONOne .ibd per tableKeep ON
innodb_default_row_formatDYNAMICRow layout of new tablesKeep
innodb_page_size16 KBPage size, fixed at initAlmost never; set before --initialize
innodb_strict_modeONErrors instead of warnings on bad table optionsKeep ON
innodb_autoinc_lock_mode2AUTO-INC concurrency1 only if you still use statement-based binlog
innodb_purge_threads1 (≤16 CPUs) else 4Purge parallelismHistory list keeps growing with spread-out DML
innodb_max_purge_lag0 (off)Throttle DML when purge lagsRunaway history list on write bursts
innodb_undo_log_truncate / innodb_max_undo_log_sizeON / 1 GiBUndo tablespace shrinkingRarely
innodb_lock_wait_timeout50 sRow-lock wait limit (error 1205)OLTP APIs: 3–10 s so requests fail fast
innodb_deadlock_detectONCycle detection (error 1213)Off only at extreme concurrency with a low lock wait timeout
innodb_dedicated_serverOFFAuto-size pool and redoON for a VM that runs only MySQL
key_buffer_size8 MiBMyISAM index cacheSmall; lower after converting to InnoDB
concurrent_insertAUTOMyISAM append during readsRarely
myisam_recover_optionsOFFAuto-check MyISAM tables on openBACKUP,FORCE while MyISAM tables still exist
max_heap_table_size16 MiBMax size of a MEMORY tableBefore creating large MEMORY tables

Error codes you will meet ​

Code / symbolSQLSTATEMessage (verbatim)Engine contextRetry?
1213 ER_LOCK_DEADLOCK40001Deadlock found when trying to get lock; try restarting transactionInnoDB row locksYes, the whole transaction
1205 ER_LOCK_WAIT_TIMEOUTHY000Lock wait timeout exceeded; try restarting transactionInnoDB; only the statement is rolled backYes, carefully
1196 ER_WARNING_NOT_COMPLETE_ROLLBACKHY000Some non-transactional changed tables couldn't be rolled backROLLBACK touched MyISAM/MEMORYNo: data is already changed
1194 ER_CRASHED_ON_USAGEHY000Table '%s' is marked as crashed and should be repairedMyISAM after a crashAfter REPAIR TABLE
1118 ER_TOO_BIG_ROWSIZE42000Row size too large. …InnoDB row > ~half a pageNo: change the schema
1286 ER_UNKNOWN_STORAGE_ENGINE42000Unknown storage engine '%s'Engine not availableNo
1452 ER_NO_REFERENCED_ROW_223000Cannot add or update a child row: a foreign key constraint failsInnoDB FKNo
1062 ER_DUP_ENTRY23000Duplicate entry '%s' for key %dAny engine with unique keysNo (idempotency)

Looking inside: introspection commands Important ​

sql
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 blob

Reading SHOW ENGINE INNODB STATUS (the output is capped at 1 MB):

SectionWhat to look atRed flag
HeaderPer second averages calculated from the last N secondsN < 20: averages are noisy, rerun
BACKGROUND THREADsrv_master_thread loopsMostly srv_active, never idle
SEMAPHORESOS waits, waits on btr0sea.cMany long waits: AHI or I/O contention
LATEST FOREIGN KEY ERRORThe failing statement and constraintRecurring app bug
LATEST DETECTED DEADLOCKBoth transactions, locks held/waited, victimSame pair repeating: fix access order (Deadlocks)
TRANSACTIONSHistory list length, ---TRANSACTION … ACTIVE n sec, LOCK WAITHistory list in the millions; transactions active for hours
FILE I/OPending reads/writes per I/O threadPending ops always > 0: disk saturated
INSERT BUFFER AND ADAPTIVE HASH INDEXChange buffer size/merges, hash searches/sHuge change buffer that never merges
LOGLog sequence number, Log flushed up to, Last checkpoint atLSN − checkpoint close to redo capacity
BUFFER POOL AND MEMORYBuffer pool hit rate 1000 / 1000, free buffers, Modified db pagesHit rate below ~990/1000 on OLTP; free buffers 0 with many reads/s
ROW OPERATIONSInserts/updates/deletes/reads per secondSudden shift = workload change

Comparison matrix ​

PropertyInnoDBMyISAMMEMORYMyRocksTransactionsYes, XA, savepointsNoNoYes, no savepointsLockingRow + gap /next-keyTable lock(concurrent insert)Table lockRow, no gaplocksCrash safetyRedo + undo +doublewriteNone, REPAIRTABLE neededData lost onrestartWAL (RocksDB)StoragestructureClustered B+treeby PK.MYD heap +.MYI indexHash / B-treein RAMLSM tree,compaction
InnoDBMyISAMMEMORYMyRocksPostgreSQL heap
TransactionsYes (XA, savepoints)NoNoYes (no savepoints)Yes
LockingRow + gap/next-keyTable (+ concurrent insert)TableRow, no gap locksRow (tuple header) + predicate locks for SERIALIZABLE
Crash safetyRedo + doublewrite + undoNo; repair neededData lost on restartWALWAL + full_page_writes
Foreign keysYesNo (ignored)NoNoYes
MVCCYes, undo-basedNoNoYes, LSM versionsYes, versions in heap
Old-version cleanupPurge threadsn/an/aCompactionVACUUM / autovacuum
Row storageClustered B+tree by PKHeap .MYD + .MYIHash/B-tree in RAMLSM clustered by PKUnordered heap + separate indexes
Secondary index points toPK valueFile offsetRow pointerPK valueTuple id (ctid)
CompressionCOMPRESSED row format, page compressionmyisampack (read-only)NoYes, per LSM levelTOAST for large values
Full-textYes (since 5.6)YesNoNotsvector + GIN
Hot physical backupPercona XtraBackup, MySQL Enterprise Backup, clone pluginLock or copy idle filesNot backed up by file copyVendor toolspg_basebackup
Group Replication / GaleraRequiredNoNoNon/a
Best useDefault for all OLTPLegacy, read-only packed dataTiny scratch tablesWrite-heavy, space-bound SSD dataPostgreSQL 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.

ProductEngine model
MySQL (Oracle)Pluggable: InnoDB default; MyISAM, MEMORY, CSV, ARCHIVE, BLACKHOLE, MERGE, FEDERATED, NDB available
Percona Server for MySQLInnoDB (formerly the XtraDB fork) + MyRocks
MariaDBInnoDB, Aria (crash-safe MyISAM successor used for its system tables), MyRocks, ColumnStore, Spider, S3 and more
PostgreSQLOne heap engine; the table access method API allows others
SQL ServerRow store with optional clustered index; in-memory OLTP; columnstore
Oracle DatabaseHeap tables, index-organized tables, undo-based consistent reads ("Oracle-style consistent nonlocking reads" is how the MySQL manual describes InnoDB's reads)
SQLiteOne B-tree format; WITHOUT ROWID tables cluster by PK
MongoDBWiredTiger (B-tree with MVCC and compression) as the default engine
CockroachDBPebble, an LSM key-value store, under a distributed SQL layer
TiDBMySQL protocol on top of TiKV, which stores data in RocksDB
RedisIn-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.

go
// 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.

go
// 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
<?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
<?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
<?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
<?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 reports Support: DEFAULT and "Supports transactions, row-level locking, and foreign keys"; MyISAM reports Transactions: NO.
  • The mysql system schema. The 8.4 manual: "Data dictionary tables and system tables use the InnoDB storage engine unless otherwise indicated", all in mysql.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 ​

SolutionHowAdvantageCost / limitation
ALTER TABLE t ENGINE=InnoDBOne statement, table copySimpleCopying ALTER: writes blocked for the whole copy; needs 2× space
Shadow table + INSERT … SELECT … ORDER BY pk + RENAME TABLEManual, in batchesTestable side by sideYou must stop or replay writes during the switch
gh-ost / pt-online-schema-changeTool builds a shadow InnoDB table and syncs changesWrites keep flowingpt-online-schema-change uses triggers; gh-ost reads the binlog (needs ROW format)
Logical dump/restore (mysqldump → sed engine → load)OfflineCleans fragmentationDowntime proportional to size

Checklist before the switch:

  1. Inventory: which tables, sizes, and which are written to.
  2. Primary key: every table needs one (otherwise you get GEN_CLUST_INDEX). Add it before or during the conversion.
  3. Row size: wide rows that fit MyISAM can fail with 1118; move long VARCHARs to TEXT.
  4. Behavioural differences: COUNT(*) without WHERE becomes a scan; AUTO_INCREMENT on 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_size vs ft_min_word_len).
  5. 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.
  6. Memory: after conversion, lower key_buffer_size and give the RAM to innodb_buffer_pool_size (the manual's own advice).
  7. Verify: row count and an order-independent content hash before and after. (CHECKSUM TABLE is not usable here: its value depends on the row format, which changes with the engine.)
sql
-- 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".

go
// 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
<?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 choiceInsert patternSecondary index costVerdict
BIGINT UNSIGNED AUTO_INCREMENTAppends at the right edge; pages fill ~15/168 bytes per entryDefault choice
BINARY(16) from UUID_TO_BIN(UUID(), 1) (time-ordered swap)Mostly appending16 bytesWhen IDs must be generated outside the DB
UUIDv7 / ULID as BINARY(16)Time-ordered appends16 bytesSame, generated in the app
CHAR(36) random UUIDv4Random page splits, half-empty pages, poor cache locality36+ bytesAvoid as clustered key
Natural composite key (tenant_id, order_no)Appends per tenantWideGood when most queries filter by tenant: rows of one tenant are clustered
No PKHidden GEN_CLUST_INDEX, 6-byte row idHidden id not usable by queriesNever
sql
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
// 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
<?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.

SymptomLikely causeAction
Miss ratio > 1–2%, Free buffers ≈ 0Working set > poolGrow innodb_buffer_pool_size; drop unused indexes; archive cold rows
Misses spike nightlyBackup or report scanRun on a replica; check innodb_old_blocks_time is not 0
Misses after every restartCold cacheKeep buffer pool dump/load ON
Pages read ahead high, evicted without access highWasted read-aheadReview innodb_read_ahead_threshold; access pattern is random
Hit rate fine, still slowNot a cache problemLocks, redo stalls, or plans: see Query Planning
sql
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;
go
// 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
<?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_commitsync_binlogLost on mysqld crashLost on OS crash / power lossTypical use
11NothingNothing (honest disks)Primary with money, orders, anything you cannot replay
10 or N>1Nothing in InnoDBBinlog tail: replicas/PITR may miss transactions InnoDB keptAvoid on a primary
21NothingUp to ~1 s of InnoDB commits; binlog may contain transactions InnoDB lostRebuildable replicas
20Nothing~1 s, and binlog/InnoDB may disagreeBulk loads you can redo
00Up to ~1 sUp to ~1 sThrowaway 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.

sql
-- 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;
go
// 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
<?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
SolutionHowAdvantageCost / limitation
Short transactionsIncrement as the last statement, commit immediatelyNo schema changeStill one row, one lock
Sharded counterN slot rows per counter; increment a random slot; SUM() to readContention ÷ NReads aggregate N rows
Buffer in RedisINCR in Redis; flush to MySQL every few secondsVery high rateLoss window = flush interval; see Redis
Append-only events + rollupInsert an event row; a job aggregatesNo hot row at allCounter is eventually consistent
sql
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;
go
// 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
<?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 ​

WorkloadEngineExtra techniqueReason
Any OLTP: users, orders, payments, cartsInnoDBShort monotonic PK, flush_log_at_trx_commit=1, sync_binlog=1Transactions, row locks, crash recovery, FKs, hot backup
Read-mostly catalogInnoDBLarge buffer pool; covering indexesMyISAM no longer wins once data is cached
Append-only logs, audit, eventsInnoDB (partitioned by time) or MyRocksDrop old partitions instead of DELETEInnoDB is fine; MyRocks if space/write volume hurt
Write-heavy, huge, SSD-boundMyRocks (Percona/MariaDB)Accept no FKs, no gap locksLower write amplification, better compression
Cold history read once a yearInnoDB COMPRESSED, ARCHIVE, or export to object storage / columnarPartition + compressSpace; ARCHIVE cannot UPDATE/DELETE
Session/scratch dataInnoDB, or Redis outside MySQLTEMPORARY tables use InnoDB anywayMEMORY loses data and locks tables
Spreadsheet exchangeCSV, then copy into InnoDBLOAD DATA is usually betterCSV has no indexes
Binlog relay filteringBLACKHOLEStatement-based binlog on the relayStores nothing
Five-nines key lookups, telecomNDB ClusterDifferent modelling rulesShared-nothing synchronous engine
Legacy app still on MyISAMConvert to InnoDBChecklist aboveEvery advantage of MyISAM is gone in 8.4
Analytics over billions of rowsNot a MySQL row engineHeatWave, ClickHouse, a columnar storeSee 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 paid

See 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 ​

LoadWhat 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):

sql
-- 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 / Fixed

Experiment 1: ROLLBACK.

sql
-- 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 | 50

Experiment 2: kill -9 in the middle of a transaction.

sql
-- 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.

sql
-- 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 applied

Repeat 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.

sql
-- 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.

sql
-- 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 commits

Experiment 6: watch the history list grow.

sql
-- 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 up

Common misconceptions ​

BeliefReality
MyISAM is faster than InnoDBOnly 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 tableMyISAM, MEMORY, CSV and ARCHIVE ignore them; ROLLBACK only raises warning 1196
Commit writes the row to the .ibd fileCommit flushes the redo log; the data page is written later by page cleaners
innodb_flush_log_at_trx_commit=2 can corrupt InnoDBIt 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 startIt discards committed changes and can corrupt tablespaces; use innodb_force_recovery and dump
GEN_CLUST_INDEX is as good as a real PKIt 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 indexIt is copied into every secondary index and scatters inserts across the clustered index
Dropping a table always frees disk spaceOnly for file-per-table; ibdata1 and general tablespaces never shrink
A long read-only transaction is harmlessIt blocks purge; history list length, undo size and read cost all grow
The doublewrite buffer doubles write I/OIt writes sequential batches with one fsync; the overhead is much smaller
MEMORY tables are the fast path for hot dataTable locks, no durability, size limits; InnoDB with a big buffer pool is usually faster under concurrency
MyISAM is required for FULLTEXTInnoDB has had FULLTEXT since 5.6
Declaring a FOREIGN KEY on MyISAM enforces itMyISAM parses and ignores it; MyRocks does not support FKs either
ALTER TABLE … ENGINE=InnoDB is an online operationConverting 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 onIn 8.4 both default to off (innodb_change_buffering=none, innodb_adaptive_hash_index=OFF)
MyRocks is a faster InnoDBIt trades read speed and features (FKs, gap locks, savepoints, Group Replication) for write and space efficiency

Cheat sheet ​

TopicWhat to remember
Default engineInnoDB since MySQL 5.5; default_storage_engine=InnoDB; system tables InnoDB since 8.0
Must-set knobinnodb_buffer_pool_size = 50–75% of RAM on a dedicated server (default 128 MiB)
Durability pairinnodb_flush_log_at_trx_commit=1 + sync_binlog=1
Redo sizeinnodb_redo_log_capacity (100 MiB default); size for about an hour of peak redo
Primary keyShort and monotonic (BIGINT AUTO_INCREMENT or time-ordered BINARY(16)); every secondary index stores it
No PKHidden GEN_CLUST_INDEX; fix it
Old versionsUndo tablespaces; purge threads clean them; watch History list length
Torn pagesDoublewrite buffer; keep innodb_doublewrite=ON
Filesibdata1 (change buffer), table.ibd, mysql.ibd, undo_00N, ibtmp1, #innodb_redo/, #innodb_temp/
Row formatDYNAMIC 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 inventorySELECT … FROM information_schema.TABLES WHERE ENGINE <> 'InnoDB' in CI
Health checkSHOW ENGINE INNODB STATUS: TRANSACTIONS, LOG, BUFFER POOL AND MEMORY, LATEST DETECTED DEADLOCK
Hit rateInnodb_buffer_pool_reads / Innodb_buffer_pool_read_requests ≪ 1%
Errors1213 deadlock (retry trx), 1205 lock wait (statement), 1196 non-transactional rollback, 1194 crashed table, 1118 row too big
ConversionInventory → add PK → ALTER … ENGINE=InnoDB (copy) or gh-ost → retries in app → shrink key_buffer_size
HAGroup Replication, Galera and XtraBackup all assume InnoDB

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
pluggable storage engineMySQL design where each table's storage is delegated to a loadable engine
handler APIThe C++ handler interface between the MySQL server and an engine (ha_innobase for InnoDB)
default_storage_engineServer variable naming the engine used when CREATE TABLE has no ENGINE clause (InnoDB)
InnoDBMySQL's default transactional engine: clustered B+trees, row locks, MVCC, redo/undo, crash recovery
XtraDBPercona's former InnoDB fork, used in older Percona Server and Galera-based products
MyISAMLegacy non-transactional engine: .MYD + .MYI, table locks, no crash safety
AriaMariaDB's crash-safe successor to MyISAM
MEMORYEngine keeping rows in RAM (formerly HEAP); data lost on restart
TempTableEngine for in-memory internal temporary tables since 8.0
CSVEngine storing rows in a comma-separated .CSV text file, no indexes
ARCHIVECompressed insert-only engine (.ARZ), index only on AUTO_INCREMENT
BLACKHOLEEngine that discards writes but still logs them to the binlog
MERGEMRG_MYISAM: union of identical MyISAM tables
FEDERATEDEngine whose rows live on a remote MySQL server
NDBNDBCLUSTER, the distributed engine of MySQL NDB Cluster
MyRocksRocksDB-based engine in Percona Server and MariaDB
RocksDBEmbedded LSM key-value store from Facebook, used by MyRocks and TiKV
LSMLog-structured merge tree: append to memtable, flush sorted files, compact
WiredTigerMongoDB's default B-tree/MVCC storage engine
clustered indexThe index whose leaves hold the full rows; in InnoDB, the PK B-tree
index-organized tableOracle's name for a table stored as its PK index, like InnoDB's clustered index
secondary indexAny other InnoDB index; each entry stores the indexed columns plus the PK
GEN_CLUST_INDEXHidden clustered index InnoDB creates on a 6-byte row id when there is no PK or suitable unique key
DB_ROW_ID6-byte hidden row id used by GEN_CLUST_INDEX
DB_TRX_ID6-byte hidden field: id of the last transaction that changed the row
DB_ROLL_PTR7-byte hidden field pointing to the row's undo record
page / 16 KBInnoDB's unit of I/O and caching; default innodb_page_size 16 KB
innodb_page_sizePage size chosen at initialisation: 4, 8, 16 (default), 32 or 64 KB
buffer poolInnoDB's RAM cache of data and index pages
innodb_buffer_pool_sizeSize of the buffer pool; default 128 MiB
innodb_buffer_pool_instancesNumber of independently latched buffer pool regions
innodb_buffer_pool_chunk_sizeUnit by which the pool is resized online (128 MiB)
midpoint insertionLRU strategy: new pages enter at the head of the old sublist (3/8), not the top
innodb_old_blocks_pctShare of the LRU reserved for the old sublist (37)
innodb_old_blocks_timeMilliseconds a page must stay in the old sublist before a touch makes it young (1000)
read-aheadPrefetching pages InnoDB expects to need; counted in buffer pool stats
flush listList of dirty pages ordered by the LSN of their first change
page cleanerBackground threads that flush dirty pages
change bufferStructure that defers changes to uncached secondary-index pages
innodb_change_bufferingWhich operations are change-buffered; none by default in 8.4
adaptive hash indexHash index InnoDB builds automatically over hot B-tree pages
innodb_adaptive_hash_indexSwitch for the adaptive hash index; OFF by default in 8.4
log bufferRAM area holding redo records before they are written
innodb_log_buffer_sizeSize of the log buffer (64 MiB in 8.4)
redo logOn-disk physical log of page changes, replayed during crash recovery
#innodb_redoDirectory holding the 32 redo files #ib_redoN
innodb_redo_log_capacityTotal redo log size (100 MiB default)
innodb_log_file_sizeDeprecated per-file redo size, used only if capacity is unset
LSNLog sequence number: ever-increasing position in the redo stream
innodb_flush_log_at_trx_commit1 = write+flush per commit, 2 = write per commit/flush per second, 0 = both per second
innodb_flush_log_at_timeoutSeconds between flushes for settings 0 and 2 (1)
innodb_flush_methodHow data/log files are opened and flushed; O_DIRECT on Linux by default in 8.4
O_DIRECTOpen flag bypassing the OS page cache for data files
undo logRecords of previous row versions, for rollback and consistent reads
rollback segmentContainer of undo logs inside an undo tablespace (128 per tablespace)
undo tablespaceFiles holding undo logs (undo_001, undo_002, *.ibu)
innodb_undo_log_truncateAutomatic shrinking of oversized undo tablespaces (ON)
purgeBackground removal of delete-marked rows and unneeded undo records
purge threadThread doing purge; count set by innodb_purge_threads
innodb_purge_threadsMaximum purge threads: 1 if ≤16 CPUs, else 4
innodb_max_purge_lagHistory length above which DML is delayed (0 = off)
history list lengthNumber of committed undo logs not yet purged
MVCCMulti-version concurrency control: readers see a snapshot built from undo
consistent readNonlocking read of a snapshot, rebuilt from undo where needed
doublewrite bufferArea where flushed pages are written first so torn pages can be repaired
innodb_doublewriteDoublewrite switch: ON/DETECT_AND_RECOVER, DETECT_ONLY, OFF
torn pageA page only partly written when a crash hit
checkpointRedo position before which all changes are in the data files
fuzzy checkpointCheckpointing by flushing small batches continuously instead of all at once
innodb_io_capacityBackground I/O budget for flushing (10000 in 8.4)
innodb_max_dirty_pages_pctTarget ceiling for dirty pages in the pool (90)
crash recoveryAutomatic redo replay plus rollback of uncommitted work on restart
tablespaceLogical storage container of InnoDB pages, backed by one or more files
system tablespaceibdata1; holds the change buffer (and tables if file-per-table is off)
ibdata1Default file of the system tablespace; never shrinks
file-per-tableOne tablespace (.ibd) per table; the default
innodb_file_per_tableSwitch for file-per-table tablespaces (ON)
.ibdData file of a file-per-table or general tablespace
general tablespaceShared tablespace created with CREATE TABLESPACE
temporary tablespaceibtmp1 (global) and #innodb_temp/*.ibt (session)
ibtmp1Global temporary tablespace with rollback segments for temp tables
mysql.ibdTablespace of the data dictionary and mysql.* system tables
data dictionaryTransactional metadata store introduced in 8.0, replacing metadata files
.frmPre-8.0 table definition file; removed in 8.0
row formatPhysical layout of rows: REDUNDANT, COMPACT, DYNAMIC, COMPRESSED
REDUNDANTOldest row format; 768-byte prefix of long columns in-page
COMPACT~20% smaller headers than REDUNDANT; 768-byte prefix in-page
DYNAMICDefault; long columns fully off-page with a 20-byte pointer
COMPRESSEDDYNAMIC plus zlib page compression; needs file-per-table or general tablespace
innodb_default_row_formatRow format for new tables (DYNAMIC)
KEY_BLOCK_SIZECompressed page size for ROW_FORMAT=COMPRESSED
off-pageLong column values stored outside the B-tree leaf
overflow pagePage holding an off-page column value
innodb_strict_modeErrors instead of warnings for invalid table options (ON)
row-level lockingLocking individual index records (InnoDB, NDB, MyRocks)
table-level lockingLocking the whole table per statement (MyISAM, MEMORY, MERGE)
gap lockInnoDB lock on the gap between index records, blocking inserts
next-key lockRecord lock plus gap lock on the gap before it
innodb_lock_wait_timeoutSeconds a row-lock wait lasts before error 1205 (50)
AUTO_INCREMENTColumn attribute generating increasing ids; counter persisted since 8.0
innodb_autoinc_lock_mode0 traditional, 1 consecutive, 2 interleaved (default since 8.0)
foreign keyReferential constraint; enforced by InnoDB and NDB only
key cacheMyISAM's index block cache, sized by key_buffer_size
key_buffer_sizeSize of the MyISAM key cache (8 MiB)
.MYDMyISAM data file
.MYIMyISAM index file with the open counter in its header
concurrent_insertMyISAM setting allowing appends while reading (AUTO)
myisamchkOffline MyISAM check/repair utility
mysqlcheckClient that runs CHECK/REPAIR/OPTIMIZE TABLE on a live server
CHECK TABLESQL statement that checks a table for errors
REPAIR TABLESQL statement that repairs a MyISAM/ARCHIVE/CSV table
myisam_recover_optionsAutomatic check/repair of MyISAM tables on open (OFF)
myisampackTool producing compressed, read-only MyISAM tables
FULLTEXTFull-text index type; MyISAM always, InnoDB since 5.6
information_schema.TABLESDictionary view with ENGINE, ROW_FORMAT, sizes per table
SHOW ENGINESLists available engines and their transaction/XA/savepoint support
SHOW TABLE STATUSPer-table engine, row format, row estimate, sizes, Auto_increment
SHOW ENGINE INNODB STATUSInnoDB Standard Monitor report
LATEST DETECTED DEADLOCKMonitor section with the last deadlock's transactions and victim
INNODB_TRXinformation_schema table of running InnoDB transactions
INNODB_METRICSinformation_schema table of InnoDB counters
INNODB_BUFFER_POOL_STATSinformation_schema table of per-instance buffer pool statistics
Innodb_buffer_pool_readsStatus counter: logical reads that missed the pool and went to disk
Innodb_buffer_pool_read_requestsStatus counter: logical page read requests
ENGINE=InnoDBTable option selecting InnoDB; also the conversion ALTER TABLE … ENGINE=InnoDB
online DDLInnoDB's INSTANT/INPLACE ALTER modes that allow concurrent DML
ALGORITHM=INPLACEALTER clause requesting a no-copy rebuild
gh-ostGitHub's binlog-based online schema change tool
pt-online-schema-changePercona Toolkit's trigger-based online schema change tool
binlogServer-level binary log of changes, used by replication and PITR
sync_binlogHow often the binlog is fsync'ed (1 = every commit group)
two-phase commitPrepare in InnoDB, write binlog, commit in InnoDB, keeping both consistent
Group ReplicationMySQL's Paxos-based multi-primary/single-primary replication; InnoDB only
GaleraSynchronous replication used by MariaDB Galera Cluster and Percona XtraDB Cluster; InnoDB only
VitessSharding and clustering layer over many MySQL instances
TiDBDistributed SQL database with the MySQL protocol, storing data in TiKV/RocksDB
Percona XtraBackupHot physical backup tool that relies on InnoDB crash recovery
LOCK INSTANCE FOR BACKUP8.x backup lock blocking DDL but not DML during backups
PostgreSQL heapPostgreSQL's unordered table storage; indexes point to tuple ids
VACUUMPostgreSQL process reclaiming dead tuple versions from the heap
MySQL 5.5Release in which InnoDB became the default engine (WL#5349)
ER_LOCK_DEADLOCKError 1213, SQLSTATE 40001: transaction chosen as deadlock victim
ER_LOCK_WAIT_TIMEOUTError 1205: row-lock wait exceeded innodb_lock_wait_timeout
ER_WARNING_NOT_COMPLETE_ROLLBACKWarning 1196: non-transactional tables could not be rolled back
ER_CRASHED_ON_USAGEError 1194: table marked as crashed and should be repaired
ER_TOO_BIG_ROWSIZEError 1118: row size too large for the page
ER_UNKNOWN_STORAGE_ENGINEError 1286: engine not available on this server
innodb_dedicated_serverAuto-sizes buffer pool and redo capacity for a MySQL-only host
innodb_deadlock_detectTurns InnoDB's deadlock detector on (default) or off

References ​

Built by Morteza Negahi