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.
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:
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 = workershows.
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:
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:
#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:
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:
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:
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:
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:
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READThat'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:
| lp | offset | flags | xmin | xmax | ctid | hot updated | heap only |
|---|---|---|---|---|---|---|---|
| 1 | 8160 | 1 | 2120 | 0 | (0,1) | f | f |
| entry | points at |
|---|---|
| 1 | (0,1) |
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:
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:
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:
#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:
| Complaint | The mechanism |
|---|---|
| Inefficient writes | Updates touch all indexes, as above |
| Inefficient replication | Physical WAL carries every one of those changes across data centres |
| Table corruption | A bug they hit during a version upgrade |
| Poor replica MVCC | Long reads on a replica conflict with replay |
| Difficult upgrades | Physical 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:
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:
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, andcount(*)doesn't.= NULLmatches nothing. UseIS NULL.NOT INwith aNULLin 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:
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:
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:
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:
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_memis per operation, per process. It multiplies with connections.- Checkpoints too often mean more full-page writes. Too rarely means longer recovery.
idle in transactionstops vacuum and lets tables bloat.- An index on a frequently updated column defeats HOT for that table's updates.
fillfactor = 100leaves no room for HOT.NOT INwith a nullable subquery. UseNOT EXISTS.SELECT *in application code gets slower when someone adds a column.- Prepared transactions left behind. Check
pg_prepared_xacts.
#Reproduce this yourself
- ✅ See the processes with
SELECT backend_type, count(*) FROM pg_stat_activity GROUP BY 1;. - ✅ Read WAL records:
CREATE EXTENSION pg_walinspect;, notepg_current_wal_insert_lsn(), run something, then querypg_get_wal_records_infobetween the two positions. - ✅ For write amplification, compare the WAL position before and after an
UPDATE, as you add indexes, with aCHECKPOINTfirst. - ✅ Count HOT updates with
n_tup_hot_updinpg_stat_user_tables.SELECT pg_stat_force_next_flush();makes the numbers appear at once. - ✅ For two-phase commit, start Postgres with
-c max_prepared_transactions=10, then follow the output above. - 📘 For InnoDB's undo history, look at
trx_rseg_history_lenininformation_schema.innodb_metricsduring a long transaction. I read the metric, but didn't run a long transaction against it.
#Glossary
| Term | Meaning |
|---|---|
| Postmaster | The Postgres process that accepts connections and starts backends |
| Backend | The process serving one connection |
| Shared buffers | Pages in shared memory |
| Checkpoint | Flushing dirty pages and recording a safe point in the log |
| Full-page write | Logging a whole page on its first change after a checkpoint |
| Redo, undo | Records to repeat a change, or reverse one |
| Bloat | Space taken by dead row versions |
| HOT | An update that stays on its page and touches no index |
| Fillfactor | How full to pack pages, leaving room for updates |
| Write amplification | One logical change causing many physical writes |
| Null bitmap | Bits in a row header marking which columns are null |
| Two-phase commit | Prepare everywhere, then commit everywhere |
| Saga | Local 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
| Concept | In one line | Why it matters |
|---|---|---|
| Process per connection | Isolation, at a memory cost | Why pools matter |
| Checkpoint | Bounds recovery, causes I/O | A tunable trade-off |
| Full-page writes | Protect against torn pages | Why WAL spikes after a checkpoint |
| No undo log | Old versions stay in the table | Free rollback, and bloat |
| Vacuum horizon | The oldest snapshot limits cleanup | One long transaction hurts everyone |
| HOT | Same page, no index change | The main defence against write amplification |
| Write amplification | Each index adds writes | The heart of Uber's complaint |
NOT IN and NULL | Unknown poisons the result | Returns no rows, silently |
SELECT * | Reads and sends everything | Loses index-only scans |
| Prepared transaction | Survives a crash, keeps its locks | Why 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
- Hussein Nasser, Fundamentals of Database Engineering, including his articles on Postgres processes and
SELECT * - PostgreSQL docs: Heap-Only Tuples, Write-Ahead Log settings, Routine Vacuuming, PREPARE TRANSACTION, pg_walinspect
- MySQL 8.4 docs: InnoDB Multi-Versioning
- Uber Engineering, Why Uber Engineering Switched from Postgres to MySQL (2016)