Home›Learn›MySQL 3: what happens on every write
MySQL · Chapter 3

What happens on every write

Why three logs, and who waits when two transactions want the same row?

Four ideas explain most of what InnoDB does in production. The buffer pool keeps hot pages in memory, three logs make commits durable, replicable and reversible, locks decide who waits, and the optimizer decides how a query reads.

Explained clearly

The buffer pool: why InnoDB keeps your data in memory

Listen, 3 min 44 s

Watch it first, then read the details:

1

The problem

Your table lives on disk. Memory is about a thousand times faster than an SSD, and your app keeps reading the same rows: active users, today's orders, the top of every index. Going to disk for the same bytes every time is waste.

2

What the buffer pool is

A big area of RAM where InnoDB keeps 16 KB pages from your tables and indexes. Every read and every write goes through it. A page read once stays for the next query.

Writes change the page in memory and add a small record to the redo log. That record is enough to rebuild the change after a crash, so the full page can go to disk later, in the background.

3

Now follow one request

For your app: if the hot data fits, most queries never touch the disk. If it stops fitting, the same queries get slower with no code change.

4

What to watch in production

  • Size. innodb_buffer_pool_size defaults to 128 MB, which is tiny. On a server that runs only MySQL it is usually set to 50 to 75 percent of RAM, leaving room for connections and the OS. innodb_dedicated_server = ON sizes it for you.
  • Disk reads. Innodb_buffer_pool_reads counts pages that had to come from disk. Innodb_buffer_pool_read_requests counts all page reads. If the first one climbs fast during normal traffic, the hot data no longer fits.
  • Waiting for a free page. Innodb_buffer_pool_wait_free above zero means queries waited for a clean page to free up: writes are coming in faster than the page cleaners can flush.
  • Big scans. A report that scans a whole table pulls cold pages in. New pages enter the middle of the LRU list, not the head, so one scan does not push out the hot pages. That is innodb_old_blocks_pct and innodb_old_blocks_time.
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';
SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_wait_free';
SELECT POOL_SIZE, FREE_BUFFERS, DATABASE_PAGES, MODIFIED_DATABASE_PAGES
FROM information_schema.INNODB_BUFFER_POOL_STATS;

The same idea elsewhere: PostgreSQL calls it shared_buffers and also leans on the OS page cache, so it is usually set lower, around 25 percent of RAM. MongoDB calls it the WiredTiger cache, by default 50 percent of (RAM minus 1 GB) or 256 MB, whichever is larger.

Explained clearly

Redo, undo and the binlog: why InnoDB keeps three logs

Listen, 3 min 3 s
1

The problem

InnoDB needs three different things from a log. Survive a crash. Let readers see old versions and roll back a transaction. Let replicas copy every change. One log cannot do all three well.

2

What it is

Redo log: physical changes to pages, for crash recovery. A fixed-size circular log (#ib_redoN, sized by innodb_redo_log_capacity).

Undo log: the old version of each changed row, for rollback and for readers who started earlier. Purge threads remove it when no one needs it.

Binary log: logical events, for replicas and point-in-time recovery. Kept as files until they expire.

3

Follow one request

  1. UPDATE copies the old row into the undo log, changes the row in the buffer pool page, and writes a redo record.
  2. COMMIT prepares in the redo log, writes and flushes the binlog, then marks the commit. With innodb_flush_log_at_trx_commit = 1 and sync_binlog = 1 that is two flushes.
  3. A replica pulls the binlog event into its relay log and applies it.
  4. Purge removes the undo record once no open transaction can still see the old version.

For your app: the two flushes are the price of never losing a commit. Group commit lets many concurrent transactions share them, which is why throughput holds up under load.

4

What to watch in production

  • History list length. One long transaction stops purge, and undo grows. Find the oldest open transaction first.
  • Redo capacity. Too small, and InnoDB must flush pages early to free redo space, which shows up as write stalls.
  • Binlog disk use. binlog_expire_logs_seconds decides how long binlogs stay. A replica that is far behind needs them.
SELECT count FROM information_schema.INNODB_METRICS WHERE name = 'trx_rseg_history_len';
SELECT trx_id, trx_started, trx_mysql_thread_id
FROM information_schema.INNODB_TRX ORDER BY trx_started LIMIT 5;
SHOW BINARY LOGS;

The same idea elsewhere: PostgreSQL has one WAL for both crash recovery and replication, and keeps old row versions in the table instead of an undo log. MongoDB has the journal for crashes and the oplog for replicas.

Explained clearly

Locks: who waits when two transactions want the same row

Listen, 3 min 0 s

Watch it first, then read the details:

1

The problem

Two customers buy the last ticket at the same moment. Two transactions change the same row. One has to wait, or the count goes wrong.

2

What it is

InnoDB locks index records. UPDATE, DELETE and SELECT ... FOR UPDATE take an exclusive lock on every index entry they scan, and hold it until COMMIT or ROLLBACK. Under the default REPEATABLE READ, locking a range also locks the gaps between entries, so no new matching row can be inserted until you finish.

3

Follow one request

  1. T1: UPDATE tickets SET sold = 1 WHERE id = 42 locks primary key entry 42.
  2. T2 runs the same update and waits for that lock.
  3. T1 commits. The lock is released and T2 continues.
  4. If T2 waits longer than innodb_lock_wait_timeout (50 s), it gets error 1205.
  5. If T1 and T2 wait on each other, InnoDB detects the deadlock at once and rolls one back (error 1213). The app retries.

For your app: keep transactions short, and never call a slow service while one is open.

4

What to watch in production

  • Unindexed updates. With no usable index, InnoDB scans and locks every row it reads. One update can block writes to the whole table.
  • Gap locks. An insert can wait even though no existing row is locked.
  • Metadata locks. ALTER TABLE waits behind any open transaction that touched the table, and every new query on that table queues behind the ALTER.
SELECT waiting_pid, waiting_query, blocking_pid, blocking_query, wait_age
FROM sys.innodb_lock_waits;
SELECT trx_mysql_thread_id, trx_started, trx_rows_locked
FROM information_schema.INNODB_TRX ORDER BY trx_started;
SHOW ENGINE INNODB STATUS;   -- LATEST DETECTED DEADLOCK

The same idea elsewhere: PostgreSQL marks a locked row in the row itself and has no gap locks. In a MongoDB transaction, two writers on the same document do not queue: one fails with a write conflict and retries.

The optimizer's selectivity decision

Problem. I add an index. The query ignores it. I run EXPLAIN first. It says full scan. That feels wrong. It is often right.

Mechanism. An index lookup reads pages one at a time, in key order. Those pages sit scattered across the .ibd file. Each one is a random read. A full scan reads the same file front to back, in one pass. One sequential pass can beat thousands of random reads. The planner compares those two costs. It picks the cheaper one. It skips the index when the query must return a large share of the table.

The planner estimates row counts from statistics. A bulk load can leave those statistics stale. The planner then guesses wrong. ANALYZE TABLE refreshes the statistics. Run it after a bulk load. Then read EXPLAIN again.

A secondary index does not hold the row. It holds the primary key value. Each match needs a second read into the clustered index. That read fetches the row from users.ibd. This is the bookmark lookup. One match costs two reads. A thousand matches cost two thousand reads.

Secondary index lookup: two reads per match

Secondary index'Asha' → primary key 42
→
Clustered index42 → the row, inside users.ibd
→
1,000 matches2,000 reads, unless the index covers the query
→
Covering indexEXPLAIN shows "Using index", no second hop

Every secondary entry carries a copy of the primary key. A long string key makes every secondary entry longer. Longer entries mean more pages per index. Keep the primary key short. Use an integer id when you can.

Exact check. Run EXPLAIN. Then refresh statistics. Then check what the index holds.

EXPLAIN SELECT id, email FROM users WHERE status = 'active'; ANALYZE TABLE users; SELECT INDEX_NAME, COLUMN_NAME, CARDINALITY FROM information_schema.statistics WHERE TABLE_SCHEMA = 'shop' AND TABLE_NAME = 'users';

Failover with GTIDs: subtraction, not forensics

Source gtid_executedthe full set of committed transactions
−
Replica gtid_executedwhat it has applied
=
The gapexactly the transactions the replica lacks

Read EXPLAIN for the access type. A scan on a wide query is the planner doing its job. A scan on a narrow query means stale statistics or a missing index.

Next · chapter 4High availabilityReplication, failover and InnoDB Cluster← Chapter 2: How it stores your data
Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect