Home›Learn›Engines side by side
Course · ScaleLesson 17 of 330 read
Compare · same task, three engines

Engines side by side

What does each engine do when the same thing happens to it?

I keep coming back to four events when I compare engines, because each one exposes how an engine is built. Four everyday events: a write, a crash, a lagging replica, and a long transaction. For each, the three engines side by side, with the file names, the order of events, and a command to see it yourself.

Architecture · one picture per engine

Same job, same shape, different files

Every engine on this site does the same four things in the same order: a client connects, the change lands in memory, the log records it first, and the data files catch up later. The three pictures are drawn the same way on purpose, so the comparison lands. The names inside them are the real file and memory names. The log box is the one that matters: COMMIT returns only after the log is on disk.

PostgreSQL
Clients
App sessionsOne connection, one backend process.
PgBouncerPools connections. The fix for pool exhaustion.
Processes
PostmasterListens on the port, forks a backend per connection.
BackendRuns one session's queries.
WAL writerFsyncs WAL records to pg_wal/.
CheckpointerFlushes dirty pages on checkpoint.
BgwriterWrites dirty pages between checkpoints.
Autovacuum workersRemove dead tuples, freeze old transaction IDs.
ArchiverCopies finished WAL segments to the archive.
WAL senderStreams WAL to standbys.
Memory
shared_buffersPage cache, about 25% of RAM, 8 KB pages.
WAL buffersWAL records wait here before the fsync.
work_memPer sort or hash operation, not per connection.
maintenance_work_memVacuum and index builds.
OS page cacheThe second cache, under shared_buffers.
Disk
base/Tables and indexes, 8 KB pages.
pg_wal/16 MB segments. The log, written first.
pg_xact/Commit status per transaction.
global/pg_controlCheckpoint and control info.
WAL archiveFinished segments, for point-in-time recovery.
MySQL · InnoDB
Clients
App connectionsOne thread per connection.
Processes
mysqldOne process. All threads live inside it.
Connection threadsRun queries.
Page cleaner threadsFlush dirty pages to the .ibd files.
Purge threadDeletes undo records no reader still needs.
Log writer threadsFlush the redo log buffer.
I/O threadsMove pages between buffer pool and disk.
Replication threadsI/O thread pulls the binlog, applier threads apply it.
Memory
Buffer poolMost of the RAM budget, 16 KB pages.
Change bufferDeferred secondary-index writes, inside the pool.
Adaptive hash indexIn-memory hash for hot lookups.
Log bufferRedo records wait here before the flush.
Disk
users.ibdThe table is the clustered index.
#ib_redo0-31The redo ring, 32 files. The log, written first.
mysql-bin.*Logical record. Replicas replay it.
undo_001/002Undo logs, the old row versions.
ibdata1System tablespace: internal bookkeeping. The doublewrite buffer lives in #ib_*.dblwr files since 8.0.20.
mysql.ibdThe data dictionary.
MongoDB · WiredTiger
Clients
Driver connectionsOne connection per session.
mongos routersRoute queries, when sharded.
Processes
mongodOne per replica set member.
PrimaryOrders all writes into the oplog.
SecondariesTail the oplog, apply in the same order.
Checkpoint threadWiredTiger checkpoints about every 60 s.
BalancerMoves chunks between shards, when sharded.
Memory
WiredTiger cacheAbout 50% of RAM minus 1 GB, uncompressed data.
OS filesystem cacheThe second cache, under the WiredTiger cache.
Disk
collection-*.wtCompressed blocks, one file per collection.
index-*.wtOne file per index.
journal/WiredTigerLog.*The write-ahead log. Covers the 60 s gap.
local.oplog.rsThe oplog, a capped collection.
_mdb_catalog.wtMaps collection names to files.

Follow one insert through these boxes, and watch it cross each one: Follow one insert, end to end →

Scenario 1 of 4

I commit one row. What touches disk, and when?

The same INSERT in all three engines. Each one writes the log first and the data file later. They differ in how many logs there are and in what "acknowledged" means.

One commit, in four steps

Solid boxes happen before COMMIT returns. The dashed box happens later, on the engine's own schedule: the checkpointer in PostgreSQL, page cleaners through the doublewrite files in MySQL, a checkpoint about every 60 seconds in MongoDB.

1. Change in memory2. Log record3. COMMIT: log flushed4. Data file, laterthe client waits until herePostgreSQLshared_buffersWAL bufferspg_wal/base/MySQLbuffer pool + undolog bufferredo + binlogusers.ibdMongoDBWiredTiger cachejournal bufferjournal/collection-*.wt

Watch one commit happen

Pick an engine, then press Play or step through it. The dot is your change.

MEMORY DISK Client COMMIT OK 1. Change in memory 2. Log record 3. COMMIT: log flushed 5. Data file, later 4. COMMIT returns

PostgreSQL

  1. The row version is written into an 8 KB page in shared_buffers. The page is now dirty.
  2. A WAL record describing the change goes into the WAL buffers.
  3. COMMIT flushes the WAL to pg_wal/ and calls fsync. Only then does the client get its answer.
  4. The dirty page reaches base/ later, written by the checkpointer or the background writer.
See it
SHOW synchronous_commit;
SELECT pg_current_wal_lsn();
-- run an INSERT, then the line above again.
-- The position moved.

The priceAn UPDATE writes a whole new row version. The old one stays in the page until VACUUM removes it.

MySQL · InnoDB

  1. The row changes in a 16 KB page in the buffer pool. The old version goes to the undo log.
  2. A redo record goes into the log buffer.
  3. COMMIT flushes redo to #innodb_redo/ and writes the binlog. The two are committed together, with a two-phase commit, so they agree after a crash.
  4. The dirty page reaches users.ibd later, through the doublewrite files, written by the page cleaner threads.
See it
SHOW VARIABLES LIKE 'innodb_flush_log_at_trx_commit';
SHOW VARIABLES LIKE 'sync_binlog';
-- both 1 is the fully durable setting

The priceTwo logs mean two syncs per commit. Group commit shares them across concurrent transactions, which is why the cost is smaller than it sounds.

MongoDB · WiredTiger

  1. The document change is applied in the WiredTiger cache. On a replica set, the oplog entry is written in the same transaction.
  2. A journal record is written to journal/WiredTigerLog.*, flushed about every 100 ms, or at once for j: true.
  3. The acknowledgment depends on the write concern. w: 1 returns after the primary applied the write. w: "majority" waits until most members have it in their journal.
  4. A checkpoint, about every 60 seconds, writes the cache to collection-*.wt.
See it
rs.conf().writeConcernMajorityJournalDefault
db.getSiblingDB('local').oplog.rs.find().sort({$natural: -1}).limit(1)

The priceA write acknowledged at w: 1 but not yet replicated can be rolled back if the primary fails.

All three write the log first. The real difference is what the client was told, and when. Check the write concern or the commit setting before you trust an acknowledgment.

Measured: Notebook 2 times the durable setting against the fast one. Go deeper: follow one insert, end to end, or what a commit waits for.

Scenario 2 of 4

The server is killed in the middle of traffic. What does the restart do?

A power cut or a kill -9. Memory is gone. What survives is the log and whatever the last checkpoint wrote. The restart is the log being replayed.

What a restart replays

The same idea in all three engines: start from the last checkpoint, replay the log, discard what never committed.

timelast checkpointcrashalready in the data filesonly in the log: replayed at restartEach block is a committed transaction. Restart = data files as of the checkpoint + replay of every log record after it.More log after the checkpoint means a longer restart. checkpoint_timeout and max_wal_size set that in PostgreSQL.

PostgreSQL

  1. global/pg_control names the last checkpoint and where the redo should start.
  2. The startup process replays WAL forward from that point and puts the missing changes into the data pages.
  3. Transactions that never committed need no undo. Their row versions stay invisible, and VACUUM removes them later.
  4. The server accepts connections when the replay finishes.
See it
-- in the server log after a crash:
-- database system was not properly shut down; automatic recovery in progress
-- redo starts at ...
-- redo done at ...

The priceRecovery time follows how much WAL sits after the last checkpoint. That is set by checkpoint_timeout and max_wal_size.

MySQL · InnoDB

  1. Torn pages, half-written by the crash, are repaired from the doublewrite files first.
  2. InnoDB finds the last checkpoint in the redo log and applies every redo record after it.
  3. Transactions that were open at the crash are rolled back using the undo log. After startup, this continues in the background.
  4. Transactions caught between prepare and commit are settled against the binlog.
See it
-- in the error log after a crash:
-- InnoDB: Starting crash recovery.
-- InnoDB: Applying a batch of ... redo log records

The priceRolling back one huge in-flight transaction can take a long time. A crash does not hide that cost. It moves it to startup.

MongoDB · WiredTiger

  1. WiredTiger restores the last checkpoint, a consistent copy of the data about 60 seconds old.
  2. It replays the journal records written after that checkpoint.
  3. On a replica set, the member then catches up from the oplog. If another member became primary meanwhile, writes it had but the majority did not are rolled back.
  4. While it catches up, the member reports RECOVERING. When it is done, it reports SECONDARY.
See it
rs.status().members.map(m => m.name + ' ' + m.stateStr)

The priceA write that only the old primary had acknowledged at w: 1 is the one that gets rolled back.

Recovery is the same idea three times: start from the last known good point, replay the log, and discard what never committed. What differs is where the unfinished work goes, and how much log you have to replay.

Try it: break a database in the crash lab.

Scenario 3 of 4

A replica falls behind. Why, and how do I see it?

Lag is a queue. Changes arrive faster than the replica applies them. Each engine has a different place where that queue builds up.

Where does replication lag usually come from: the network, or the replica applying the change?

Usually the replica applying it. Shipping a log record takes milliseconds; the replica replaying it can wait behind a long query, a huge transaction or a single busy apply thread. Tick the box in the widget to see each engine's version.

PostgreSQL

  1. The standby receives WAL over the network and replays it with one recovery process.
  2. A burst of writes can arrive faster than one process replays it.
  3. A long query on the standby can conflict with replay. Replay waits, up to max_standby_streaming_delay (30 s by default), then cancels the query.
  4. With synchronous replication, lag stops being a delay and becomes commit latency.
See it
-- on the primary
SELECT client_addr, state, write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
-- on the standby
SELECT now() - pg_last_xact_replay_timestamp();

The priceThe standby holds WAL the primary cannot recycle if a replication slot is tied to it, so a stuck replica can fill the primary disk.

MySQL · InnoDB

  1. The replica copies the binlog into its relay log with the I/O thread.
  2. The applier threads replay it. This is usually where the queue builds up.
  3. One large transaction replays as one unit, so a big batch delete on the source becomes a long stall on the replica.
  4. Parallel replay (replica_parallel_workers) helps when the source workload is spread across many transactions.
See it
SHOW REPLICA STATUS\G
-- read Seconds_Behind_Source, Replica_IO_Running,
-- Replica_SQL_Running. Treat the seconds as a hint.

The priceThe binlog on the source must be kept long enough for a slow replica to catch up, or the replica needs a rebuild.

MongoDB · WiredTiger

  1. The secondary tails the primary oplog and applies the entries in batches.
  2. If writes outpace it, the secondary falls further behind the primary.
  3. The oplog is a capped collection. If the secondary falls behind by more than the oplog window, the entries it needs are gone, and it needs a full resync.
  4. Flow control, on by default, slows the primary down when the majority commit point lags too far.
See it
rs.printSecondaryReplicationInfo()
rs.printReplicationInfo()  // the oplog window

The priceSize the oplog for the longest outage you want a secondary to survive, not for the average day.

Lag is write rate minus apply rate, accumulated over time. Whatever the engine, the question is the same: what is the apply rate, and what is the limit on how far behind the log is kept?

Try it: watch the queue build in the replica lag lab.

Scenario 4 of 4

One transaction stays open for an hour. What does it cost?

Nothing is wrong with the transaction itself. The cost is everything the database must keep so that its snapshot still makes sense.

PostgreSQL

  1. The transaction holds a snapshot. Every row version that died after the snapshot was taken must be kept.
  2. VACUUM runs, but it cannot remove those versions, in any table in the database.
  3. Tables and indexes grow (bloat), and queries read more pages for the same rows.
  4. If the session is "idle in transaction", it also holds its locks the whole time.
See it
SELECT pid, state, now() - xact_start AS age
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY age DESC LIMIT 5;

The priceSet idle_in_transaction_session_timeout so a forgotten session cannot hold the cleanup back for hours.

MySQL · InnoDB

  1. The old read view needs old row versions, so the purge thread cannot delete the undo records for them.
  2. The history list grows, and the undo tablespaces grow with it.
  3. Reads of recently changed rows walk longer chains of old versions, so they slow down.
  4. Locks held by the transaction block other writers until it ends.
See it
SELECT trx_id, trx_started, trx_rows_modified
FROM information_schema.innodb_trx
ORDER BY trx_started LIMIT 5;
SHOW ENGINE INNODB STATUS\G  -- History list length

The priceUndo tablespaces are truncated only once they pass innodb_max_undo_log_size and purge has caught up, so the extra space can linger after the transaction ends.

MongoDB · WiredTiger

  1. A multi-document transaction is limited by transactionLifetimeLimitSeconds, 60 seconds by default. After that it is aborted.
  2. A long read cursor or snapshot keeps older versions of documents in the WiredTiger cache.
  3. The cache fills with history, and eviction starts to compete with the workload.
  4. Writers can see more retries from write conflicts if the transaction held documents.
See it
db.currentOp({ active: true, secs_running: { $gt: 60 } })

The priceMongoDB limits the problem with a hard timeout. The other two let it grow until you notice.

A long transaction is a debt: the database has to remember the past for as long as the transaction is open. PostgreSQL shows it as bloat, MySQL as undo, and MongoDB as cache pressure.

Measured: Notebook 1 runs this on all three engines. Related: the MVCC timeline lab shows why the snapshot is taken at the first query, not at BEGIN.

What is verified hereThe behavior on this page follows the documentation of PostgreSQL 18, MySQL 8.4 and MongoDB 8.0. The commands are standard and match the engine pages, but this page is not yet part of the automated command check that runs on the engine pages. The log lines are paraphrased, so match on the key words, not the exact text.
Beyond the big three

Redis, Cassandra and vector search, on the same questions

Most designs on this site put one of these next to the main database. Same questions as above, shorter answers; each has a full page.

RedisCassandraVector search
Where the data livesMemory. Snapshots and the AOF only for restartsCommit log, memtables, immutable SSTablesVectors plus an index (HNSW or IVF), usually in memory
What COMMIT waits forMemory only. appendfsync decides when the disk followsThe commit log write on enough replicas for the consistency levelWhatever the host database waits for: in pgvector, the WAL
ReplicationAsynchronous; WAIT narrows the windowEvery node equal; consistency chosen per queryFrom the host database, or the vector service's own
Queries it answersBy key, with commands per data typeBy partition key, then clustering orderNearest neighbours, approximate, plus filters
What breaks firstBig keys, hot keys, memory full, forksHuge partitions, tombstones, skipped repairIndex outgrows memory, filtered search returns too few rows
Measured hereZINCRBY 0.080 ms a round tripOne-partition read 3.3 msRecall 0.95 at ef_search 40, 0.65 ms

Measured in Notebook 7 for Redis and Cassandra, and Notebook 8 for vector search. The transcripts are on the Notebooks page.

Your turn

A new service does 2,000 small writes a second and must lose nothing on failover. In each engine, which settings make "lose nothing" true?

Write your answer down first. Then open mine.

Show my answer

PostgreSQL: synchronous_commit = on (the default) plus a synchronous standby in synchronous_standby_names, and a failover tool that only promotes a synchronous standby, such as Patroni in synchronous mode.

MySQL: innodb_flush_log_at_trx_commit = 1 and sync_binlog = 1, plus semi-synchronous replication with AFTER_SYNC, or Group Replication.

MongoDB: write concern w: "majority", the default since 5.0, with journaling.

The catch: in Notebook 2, one client doing fully durable commits managed about 4,200 a second on PostgreSQL, 1,770 on MySQL and about 1,100 on MongoDB. That run used one client and 2,000 commits per setting, run 2026-11-18; the numbers belong to that runner, not to your server. 2,000 a second needs several connections committing at once, so the engine can flush many commits together.

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. After a crash, where does recovery start?

2. In Notebook 6, 1,600 attempts tried to buy an item with 1,000 in stock by reading the stock and then writing the new value. How many sold?

3. Which MySQL setting trades a short window of acknowledged commits for speed?

Part 1 of 4 · Learn · 23 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.