Vineet Ganti
Inside Postgres and MySQL: Processes, WAL, MVCC and Why Uber Moved
All posts

Data Engineering/Database Engineering · Part 14 of 14

·19 min read

Inside Postgres and MySQL: Processes, WAL, MVCC and Why Uber Moved

The last post of the series opens up the servers: a process per connection, what really happens at a crash, how heap-only tuples save index writes, why one update can touch every index, the NULL traps, what SELECT * costs, and two-phase commit.

DatabasesPostgreSQLMySQLInternalsWAL

This last post gathers what the rest of the series has been pointing at. It covers how the two servers are built, what a log is really for, and the design choice behind one of the most discussed database migrations ever: Uber's move from Postgres to MySQL.

The course's final section is a set of articles and talks, so this post is a mix. Most of it I could run. By the end, one update measured here wrote nearly four times as much log just because the table had five more indexes.

#Processes or threads

A database server has to serve many clients at once. The two engines answer this differently.

Request or acknowledgment

Here's what's actually running:

✅ ran here · PostgreSQL 18.6
SELECT backend_type, count(*) FROM pg_stat_activity GROUP BY 1;
autovacuum launcher            1
background writer              1
checkpointer                   1
client backend                 2
io worker                      3
logical replication launcher   1
walwriter                      1

-- two client connections are two operating system processes
backend pids: 5002, 5003
shared_buffers = 256MB, io_method = worker

-- MySQL, for comparison: one process, many threads
processes in the container: 5, threads in mysqld: 42
BACKGROUND	36
FOREGROUND	3
thread/innodb/buf_dump_thread
thread/innodb/buf_resize_thread
thread/innodb/clone_gtid_thread
thread/innodb/dict_stats_thread
thread/innodb/fts_optimize_thread
thread/innodb/io_ibuf_thread
thread/innodb/io_read_thread
thread/innodb/io_read_thread
  • The postmaster listens for connections, and forks a backend for each.
  • Shared buffers hold pages and are shared by all backends, as are the WAL buffers.
  • The background writer trickles dirty pages out, so backends rarely have to.
  • The WAL writer flushes the log.
  • The checkpointer forces pages to disk and marks a safe point.
  • The autovacuum launcher starts workers to clean up.
  • I/O workers are new in Postgres 18, as io_method = worker shows.

The course's article gives the reasoning for processes: isolation, and Postgres's long history. A crash in one process doesn't scribble on another's memory, though a backend crash does restart the others, to protect shared memory. The cost is that a process is heavier than a thread, which is why connection pools matter so much on Postgres. Note also that settings such as work_mem apply per process, so they multiply with connections.

MySQL's output above shows the alternative: one mysqld process, with dozens of threads.

#The log, in detail

Post 1 introduced the write-ahead log. Here it is at the record level, using pg_walinspect:

✅ ran here · PostgreSQL 18.6
SELECT pg_current_wal_insert_lsn() AS start_here \gset
BEGIN;

INSERT INTO t VALUES (1, 'a');

UPDATE t SET v = 'b' WHERE id = 1;

COMMIT;

SELECT resource_manager, record_type, record_length, fpi_length FROM pg_get_wal_records_info(:'start_here', pg_current_wal_insert_lsn());
 resource_manager | record_type | record_length | fpi_length 
------------------+-------------+---------------+------------
 Heap             | INSERT+INIT |            61 |          0
 Heap             | HOT_UPDATE  |            69 |          0
 Transaction      | COMMIT      |            34 |          0
(3 rows)

An insert, an update and a commit are three small records, 164 bytes in all, and the commit record is what makes the transaction count. That's also exactly what replication ships to a standby. Read your own:

Read the logruns in your browser
pg_walinspect reads the WAL. Run a change, then read the records it wrote, including the commit record.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#Crash recovery

Here's a working model. Change pages, commit, checkpoint, and crash at any moment. Try crashing with an uncommitted change, then again just after COMMIT:

Memory (lost in a crash)
page A11 version
page B11 version
WAL buffer
empty
Data files on disk
page A11 version
page B11 version
WAL on disk (survives)
empty
Update a page, commit, then crash at any point. Try crashing before and after COMMIT.

Two things to see. A commit changes the log and leaves the data files alone. And after a crash, recovery replays everything since the last checkpoint, including uncommitted work, which then stays invisible because no commit record exists. That's the design: no undo is needed in Postgres, only redo.

#Checkpoints, and why they spike

A checkpoint writes all dirty pages to the data files and records a position in the log. Recovery can start there, so checkpoints bound recovery time. The course notes that they're I/O heavy, and can hit at awkward times.

There's a hidden cost as well. A page half-written at the moment of a crash can't be repaired from a small log record. So the first change to each page after a checkpoint logs the whole page. That's full_page_writes:

✅ ran here · PostgreSQL 18.6
CHECKPOINT;

SELECT pg_current_wal_insert_lsn() AS a \gset
UPDATE t SET v = 1 WHERE id % 100 = 0;

SELECT pg_size_pretty(pg_current_wal_insert_lsn() - :'a') AS wal_just_after_a_checkpoint;
 wal_just_after_a_checkpoint 
-----------------------------
 5758 kB
(1 row)

SELECT pg_current_wal_insert_lsn() AS b \gset
UPDATE t SET v = 2 WHERE id % 100 = 0;

SELECT pg_size_pretty(pg_current_wal_insert_lsn() - :'b') AS the_same_update_again;
 the_same_update_again 
-----------------------
 231 kB
(1 row)

The same update wrote 5,758 kB right after a checkpoint, and 231 kB the second time, which is 25 times less. Frequent checkpoints mean more full pages, and that's a direct trade against recovery time.

#Redo and undo

InnoDB updates a row in place, and writes the old value to an undo log, kept in undo tablespaces:

✅ ran here · MySQL 8.4.13
SELECT name, count FROM information_schema.innodb_metrics WHERE name = 'trx_rseg_history_len';
+----------------------+-------+
| name                 | count |
+----------------------+-------+
| trx_rseg_history_len |     1 |
+----------------------+-------+
1 row in set (0.01 sec)

SHOW VARIABLES LIKE 'innodb_undo_tablespaces';
+-------------------------+-------+
| Variable_name           | Value |
+-------------------------+-------+
| innodb_undo_tablespaces | 2     |
+-------------------------+-------+
1 row in set (0.05 sec)

SELECT space_type, name FROM information_schema.innodb_tablespaces WHERE row_format = 'Undo' OR name LIKE 'innodb_undo%';
+------------+-----------------+
| space_type | name            |
+------------+-----------------+
| Undo       | innodb_undo_001 |
| Undo       | innodb_undo_002 |
+------------+-----------------+
2 rows in set (0.01 sec)

A reader with an old snapshot follows undo records back to the version it needs, as the docs describe. The latest version is always in the table, and the history is elsewhere. Postgres does the reverse: new versions go in the table, and old ones stay there. So in Postgres a rollback is instant, and VACUUM is the bill.

The course mentions a real InnoDB cost here: a long transaction forces readers to walk further through undo records, which is why history list length is worth monitoring.

#MVCC's bill

Every Postgres update leaves a dead version behind. Here's what that does to a table:

✅ ran here · PostgreSQL 18.6
SELECT pg_size_pretty(pg_relation_size('t')) AS before;
 before  
---------
 3544 kB
(1 row)

UPDATE t SET v = v + 1;

UPDATE t SET v = v + 1;

UPDATE t SET v = v + 1;

SELECT pg_size_pretty(pg_relation_size('t')) AS after_three_updates;
 after_three_updates 
---------------------
 14 MB
(1 row)

SELECT pg_stat_force_next_flush();
 pg_stat_force_next_flush 
--------------------------
 
(1 row)

SELECT n_live_tup, n_dead_tup FROM pg_stat_user_tables WHERE relname = 't';
 n_live_tup | n_dead_tup 
------------+------------
     100000 |     299935
(1 row)

VACUUM t;

SELECT pg_size_pretty(pg_relation_size('t')) AS after_vacuum;
 after_vacuum 
--------------
 14 MB
(1 row)

VACUUM FULL t;

SELECT pg_size_pretty(pg_relation_size('t')) AS after_vacuum_full;
 after_vacuum_full 
-------------------
 3544 kB
(1 row)

Three updates took the table from 3.5 MB to 14 MB. Plain VACUUM made the space reusable, and didn't shrink the file, as post 3 said. Only VACUUM FULL did, with an exclusive lock.

And vacuum can only remove what no snapshot needs. One open transaction stops all of it:

One open transaction stops the cleanup✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN
A long report starts.
Step 1 of 8

That's why a forgotten transaction, or idle in transaction, is such a problem on a busy Postgres.

#One update, every index

This is where the design differences become a story. Recall what the leaves hold: Postgres indexes hold a physical address, and InnoDB's secondary indexes hold the primary key.

A new row version has a new address. Taken at face value, every index on the table then needs a new entry, even for columns that didn't change. Postgres has an optimisation for that: heap-only tuples.

#HOT

If an update changes no indexed column, and the new version fits on the same page, the indexes aren't touched. The old version just links to the new one, inside the page. Here it is on real pages, for one row and its primary key entry:

One row version, and one index entry pointing at line pointer 1.
heap page 0
lpoffsetflagsxminxmaxctidhot updatedheap only
18160121200(0,1)ff
primary key entries
entrypoints at
1(0,1)
✅ read from real pages on PostgreSQL 18.6

In the HOT steps the index keeps its single entry, still pointing at line pointer 1, and the chain grows inside the page. As soon as an indexed column changes, the primary key index gets a second entry, although id never changed. That's the behaviour Uber objected to.

Here's the size of the effect. I updated 50,000 rows, then added indexes one at a time:

At 5 secondary indexes on the table: unindexed column (HOT) 15 MB · indexed column 59 MB ✅ measured on PostgreSQL 18.6

Updating an unindexed column stayed at 15 MB, however many indexes there were. Updating an indexed one grew with every index on the table, reaching 59 MB, because each index needed a new entry. That's write amplification: one logical change, many physical writes.

HOT also needs room on the page, which is what fillfactor reserves:

✅ ran here · PostgreSQL 18.6
UPDATE t SET note = 'changed';

UPDATE t SET v = v + 1;

SELECT pg_stat_force_next_flush();
 pg_stat_force_next_flush 
--------------------------
 
(1 row)

SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables WHERE relname = 't';
 n_tup_upd | n_tup_hot_upd 
-----------+---------------
     20000 |          4368
(1 row)

Of 10,000 updates to an unindexed column, only 4,368 were HOT. A bulk update quickly fills the free space in a page, and then rows have to move. Try it:

HOT or not?runs in your browser
n_tup_hot_upd counts updates that touched no index. Update the unindexed column, then the indexed one, and compare.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#Why Uber moved

In 2016 Uber wrote about leaving Postgres, and the course goes through it point by point. Their complaints, as the course presents them:

ComplaintThe mechanism
Inefficient writesUpdates touch all indexes, as above
Inefficient replicationPhysical WAL carries every one of those changes across data centres
Table corruptionA bug they hit during a version upgrade
Poor replica MVCCLong reads on a replica conflict with replay
Difficult upgradesPhysical replication tied replicas to a major version

InnoDB avoids the first two, because its secondary indexes don't care where a row lives, and its logical replication ships smaller changes.

The course's take is measured, and I agree with it: that's a trade-off for one workload, not a verdict. Uber had many indexes and heavy updates to indexed columns. Reads go the other way, since a Postgres index reaches the row directly, and InnoDB needs a second tree walk. The course also criticises part of the original post, where a long transaction caused by application code was blamed on the database, and it points out that replication and upgrades have changed a lot since: logical replication arrived in Postgres 10.

📘 I couldn't fetch Uber's post from this machine, so that table follows the course's walkthrough, not the post itself.

#Write amplification all the way down

The course's talk on this follows a single update through every layer. One API call becomes a row version, index entries and WAL records. A database page write becomes file system blocks. On an SSD, an update marks old pages stale and writes new ones, and garbage collection later moves live pages to free a block, which is more writing that nobody asked for. Each layer multiplies the one above, which is why log-structured designs exist.

#NULLs

NULL means "no value", and the database has to store that fact somewhere. Postgres uses a null bitmap in the row header, and only when the row has a null:

✅ ran here · PostgreSQL 18.6
CREATE TABLE n (a int, b int, c int, d int, e int, f int, g int, h int, i int);

INSERT INTO n VALUES (1, 2, 3, 4, 5, 6, 7, 8, 9);

INSERT INTO n VALUES (1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

SELECT lp, lp_len, t_hoff, t_bits FROM heap_page_items(get_raw_page('n', 0));
 lp | lp_len | t_hoff |      t_bits      
----+--------+--------+------------------
  1 |     60 |     24 | 
  2 |     36 |     32 | 1000000000000000
(2 rows)

The row with eight nulls is 36 bytes against 60: nulls take no space in the data. The header grew from 24 to 32 bytes to fit the bitmap, so a row with nulls has a small fixed cost that the saved columns repay.

The trouble is the logic. NULL isn't a value, it's unknown, so comparing with it gives unknown:

✅ ran here · PostgreSQL 18.6
SELECT count(*) AS all_rows, count(parent) AS with_a_parent FROM t;
 all_rows | with_a_parent 
----------+---------------
        3 |             2
(1 row)

SELECT id FROM t WHERE parent = NULL;
 id 
----
(0 rows)

SELECT id FROM t WHERE parent IS NULL;
 id 
----
  1
(1 row)

SELECT id FROM t WHERE id NOT IN (SELECT parent FROM t);
 id 
----
(0 rows)

SELECT id FROM t WHERE id NOT IN (SELECT parent FROM t WHERE parent IS NOT NULL);
 id 
----
  2
  3
(2 rows)

SELECT NULL = NULL AS equal, NULL IS NOT DISTINCT FROM NULL AS same;
 equal | same 
-------+------
       | t
(1 row)
  • count(column) skips nulls, and count(*) doesn't.
  • = NULL matches nothing. Use IS NULL.
  • NOT IN with a NULL in the list returns no rows at all, because "is 2 unequal to unknown?" is unknown. It's the classic trap, and it silently returns nothing.

Predict these:

NULL isn't a valueruns in your browser
Each preset is a real trap. Try to predict the result first.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

Indexes are a design choice too. Postgres stores nulls in B-tree indexes. If you never search for them and most rows are null, a partial index can be far smaller:

✅ ran here · PostgreSQL 18.6
EXPLAIN (COSTS OFF) SELECT id FROM t WHERE v IS NULL LIMIT 1;
         QUERY PLAN          
-----------------------------
 Limit
   ->  Seq Scan on t
         Filter: (v IS NULL)
(3 rows)

SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) FROM pg_stat_user_indexes WHERE relname = 't';
 indexrelname | pg_size_pretty 
--------------+----------------
 t_v          | 6944 kB
 t_v_partial  | 240 kB
(2 rows)

6,944 kB against 240 kB, for an index on a column that's 99% null. The planner still chose a scan for the first query, because almost every row matches.

#What SELECT * costs

The course's article on SELECT * starts from a real incident, and lists the costs: no index-only scan, reading out-of-line columns, serialising everything, sending it over the network, and decoding it at the client. I built a table with a wide column and measured:

✅ ran here · PostgreSQL 18.6
SELECT id FROM students WHERE grade >= 90;
4.6 ms, 38 KB delivered to the client
Index Only Scan using students_grade on students (actual rows=5000.00 loops=1)
  Heap Fetches: 0
  Buffers: shared hit=17

SELECT * FROM students WHERE grade >= 90;
296.5 ms, 46.9 MB delivered to the client
Bitmap Heap Scan on students (actual rows=5000.00 loops=1)
  Buffers: shared hit=753
  ->  Bitmap Index Scan on students_grade (actual rows=5000.00 loops=1)

4.6 ms against 296.5 ms for the same rows, with 17 pages read against 753. The plan changed from an index-only scan to a bitmap scan, and the large values had to be fetched from TOAST and sent across. If your table has a few small columns, the difference is small, as the article says. The danger is that a table can gain a big column later, and every SELECT * silently gets slower.

#Distributed transactions

Post 7 lost 100 by committing on two shards with nothing connecting them. The course's talk on this starts with a monolith, where one transaction handles an order and a payment. Split those into services, and that guarantee is gone. There are three kinds of answer.

Two-phase commit adds a coordinator:

Request or acknowledgment

Postgres exposes the first phase as PREPARE TRANSACTION. It has to be enabled with max_prepared_transactions:

✅ ran here · PostgreSQL 18.6 · a prepared transaction through a crash
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
PREPARE TRANSACTION 'transfer-42';
SELECT gid FROM pg_prepared_xacts;
transfer-42

SELECT balance FROM accounts WHERE id = 1;
500   (not committed, so other sessions see the old value)

-- another session tries to change the row
canceling statement due to lock timeout

$ docker kill -s KILL (the server dies while prepared)
$ docker start
SELECT count(*) FROM pg_prepared_xacts;
1   (it survived the crash, and it's still holding its lock)

COMMIT PREPARED 'transfer-42';
SELECT balance FROM accounts WHERE id = 1;
400

The promise is strong: the prepared transaction survived SIGKILL, ready to commit. So is the cost: it kept its lock through the crash, and it'll keep it until someone decides. The docs warn that this isn't for applications, only for a real transaction manager, because a forgotten prepared transaction blocks vacuum and holds its locks forever.

Sagas give up atomicity. Each service commits locally, and a failure triggers compensating actions, such as a refund. Events usually travel through a broker like Kafka. That brings eventual consistency, and a lot of failure cases to design.

The third answer is the course's favourite, and it's a good one to end on: go back to one database, if you can. Much of this difficulty is self-inflicted by splitting things up too soon.

#Should databases use QUIC?

🎓 One talk asks whether database protocols should move to QUIC. Today a client opens many TCP connections, one query at a time on each, because responses can't be interleaved. HTTP/2 solved this for the web with streams over one connection, and it suffers head-of-line blocking from TCP, which QUIC removes with independent streams. In principle a database could run many concurrent queries over one connection, and a lost packet would delay just one of them. It's an idea rather than something shipping, so I've nothing to run. The course's conclusion is that the case is interesting, and pools work well enough today.

#Things that can trip you up

  • work_mem is per operation, per process. It multiplies with connections.
  • Checkpoints too often mean more full-page writes. Too rarely means longer recovery.
  • idle in transaction stops vacuum and lets tables bloat.
  • An index on a frequently updated column defeats HOT for that table's updates.
  • fillfactor = 100 leaves no room for HOT.
  • NOT IN with a nullable subquery. Use NOT EXISTS.
  • SELECT * in application code gets slower when someone adds a column.
  • Prepared transactions left behind. Check pg_prepared_xacts.

#Reproduce this yourself

  1. ✅ See the processes with SELECT backend_type, count(*) FROM pg_stat_activity GROUP BY 1;.
  2. ✅ Read WAL records: CREATE EXTENSION pg_walinspect;, note pg_current_wal_insert_lsn(), run something, then query pg_get_wal_records_info between the two positions.
  3. ✅ For write amplification, compare the WAL position before and after an UPDATE, as you add indexes, with a CHECKPOINT first.
  4. ✅ Count HOT updates with n_tup_hot_upd in pg_stat_user_tables. SELECT pg_stat_force_next_flush(); makes the numbers appear at once.
  5. ✅ For two-phase commit, start Postgres with -c max_prepared_transactions=10, then follow the output above.
  6. 📘 For InnoDB's undo history, look at trx_rseg_history_len in information_schema.innodb_metrics during a long transaction. I read the metric, but didn't run a long transaction against it.

#Glossary

TermMeaning
PostmasterThe Postgres process that accepts connections and starts backends
BackendThe process serving one connection
Shared buffersPages in shared memory
CheckpointFlushing dirty pages and recording a safe point in the log
Full-page writeLogging a whole page on its first change after a checkpoint
Redo, undoRecords to repeat a change, or reverse one
BloatSpace taken by dead row versions
HOTAn update that stays on its page and touches no index
FillfactorHow full to pack pages, leaving room for updates
Write amplificationOne logical change causing many physical writes
Null bitmapBits in a row header marking which columns are null
Two-phase commitPrepare everywhere, then commit everywhere
SagaLocal commits with compensating actions on failure

#Summary

Postgres gives each connection a process, and shares pages through memory, with background processes handling the log, checkpoints and cleanup. The log is what makes a crash survivable, and its cost shows up in full-page writes after a checkpoint. Keeping old versions in the table makes rollback free and gives VACUUM real work, and pointing indexes at physical rows makes reads direct and updates wide, which HOT softens and Uber's workload hit head on. InnoDB makes the opposite choices at each point. NULLs and SELECT * are everyday costs of the same machinery. Across databases, two-phase commit keeps atomicity at the price of held locks, and the simplest fix may be not splitting the data in the first place.

#Concepts at a glance

ConceptIn one lineWhy it matters
Process per connectionIsolation, at a memory costWhy pools matter
CheckpointBounds recovery, causes I/OA tunable trade-off
Full-page writesProtect against torn pagesWhy WAL spikes after a checkpoint
No undo logOld versions stay in the tableFree rollback, and bloat
Vacuum horizonThe oldest snapshot limits cleanupOne long transaction hurts everyone
HOTSame page, no index changeThe main defence against write amplification
Write amplificationEach index adds writesThe heart of Uber's complaint
NOT IN and NULLUnknown poisons the resultReturns no rows, silently
SELECT *Reads and sends everythingLoses index-only scans
Prepared transactionSurvives a crash, keeps its locksWhy 2PC needs a real coordinator

#Test yourself

The same UPDATE wrote 5,758 kB of WAL right after a checkpoint, and 231 kB when repeated. Why?

After a checkpoint the first change to each page logs the whole page, to protect against torn pages. The second run touched pages already logged, so it only wrote small records.

After a crash, Postgres replays uncommitted changes too. Why doesn't that show wrong data?

Replay only rebuilds pages. Those row versions belong to a transaction with no commit record, so they stay invisible to everyone. That's how Postgres manages without undo.

Why did updating an indexed column write more log with every index on the table, even indexes on other columns?

The new row version has a new address, and every Postgres index points at addresses, so each needs a new entry. HOT can't apply when an indexed column changes.

What two conditions does a HOT update need?

It must not change any indexed column, and the new version must fit on the same page. That's what fillfactor leaves room for.

SELECT id FROM t WHERE id NOT IN (SELECT parent FROM t) returns no rows, though you expected two. Why?

parent contains a NULL. Comparing with NULL gives unknown, so every NOT IN test is unknown or false, and no row qualifies. Filter the nulls out, or use NOT EXISTS.

A prepared transaction survives a crash. Why is that a risk as well as a feature?

It keeps its locks until someone commits or rolls it back, and it blocks vacuum. If the coordinator is gone, nobody may ever decide. That's why the docs say not to use it from applications.

#Open questions and gaps

  • I couldn't fetch Uber's post here, so its five points follow the course's reading of it.
  • I ran these on one laptop, so the size of write amplification depends on my row sizes and index choices.
  • I didn't measure InnoDB's update path for a direct comparison. The claims about it come from the docs and the course.
  • 🎓 The QUIC discussion and the saga patterns are reported from the course, with nothing run.
  • The course's talk on SSD write amplification sits below anything I can observe from a database.

#Sources