Home›Practice›Lab notebooks
Course · Stay upLesson 25 of 330 read
Notebooks · experiments run on real servers

Lab notebooks

What actually happens when you run it?

You will learn: what a long transaction, a durable commit, an index, two concurrent sessions and common query shapes cost on PostgreSQL 18, MySQL 8.4 and MongoDB 8.0, whether the rules in the design docs hold, and how Redis, ClickHouse and Cassandra behave in the roles the design docs give them.

Most pages on this site explain a mechanism. These notebooks show it happening. I wrote ten experiments, and a workflow in this site's repository runs them on real servers, PostgreSQL 18.7 (with pgvector for Notebook 8), MySQL 8.4.13, MongoDB 8.0.38, Redis 7.4, ClickHouse 24.8 and Cassandra 5.0, on a GitHub Actions runner. The output below is pasted as captured, with the run time. Nothing in it is written by hand.

How these were runA GitHub Actions runner with 4 vCPUs on a cloud VM, one container per engine, stock settings unless the notebook says otherwise. Timings belong to that machine. Your hardware will give different absolute numbers, and the comparisons are what carry over. The experiment code is scripts/notebooks/run_all.py and scripts/notebooks/run_more.py and the workflow is .github/workflows/lab-notebooks.yml. Run them yourself and compare.
The short version

Ten experiments, one line each

#What I triedWhat happened
1One snapshot left open while 500,000 rows were updatedVACUUM could remove none of the old versions until the snapshot closed
2Commits with and without waiting for the log flushNot waiting was 1.8 times faster in PostgreSQL, 2.3 in MySQL, 2.6 in MongoDB, and can lose the last commits
3Find one row in a million4 pages with an index, 19,231 without
4Two deposits to one balance at the same momentAt the default READ COMMITTED one deposit was lost; REPEATABLE READ refused the second
5An index on (customer_id, created_at), a filter on created_at onlyNone of the three engines used the index
61,600 purchases of 1,000 items, read then writeAll 1,600 sold; a conditional UPDATE sold exactly 1,000
7A month of revenue from 10 million order lines in ClickHouse870,400 rows read, about 15 MB, 8 ms
8One tenant's 10 nearest memories with pgvector and a filter1.3 rows on average instead of 10, until iterative scan was on
9Redis killed and failed over; Cassandra with nodes downkill -9 lost nothing; a failover to a lagging replica lost 2,217 acknowledged writes
10One million inserts, random key against ordered keyRandom keys made MySQL ten times slower: 55.5 s against 5.7 s

Each notebook below starts with a question to guess before you read the answer. The full output and the details are one click away.

Notebook 1 · run 2026-11-18 04:25 UTC

What one open transaction costs

I held one transaction open in each engine and kept writing from a second session. This is the experiment behind Compare, scenario 4.

PostgreSQL: 100,000 rows, a snapshot held open, then 500,000 row updates. How many dead row versions can VACUUM remove while the snapshot is open?

None of the 500,000. VACUUM says so itself: "500000 are dead but not yet removable". Once the snapshot is released, the same VACUUM removes all of them, and the file stays at 29 MB.

PostgreSQL: table size, in MB

Five updates of every row while one snapshot was open. VACUUM made the space reusable, but the file kept its size.

At start: 5.6 MB5.6 MBAt startAfter the updates: 29 MB29 MBAfter the updatesAfter VACUUM: 29 MB29 MBAfter VACUUM

MySQL: History list length while one snapshot stays open

It counts transactions waiting for purge, not rows. Measured in Notebook 1.

At start: 66At startAfter 5 updates of 100,000 rows: 1111After 5 updatesof 100,000 rowsAfter 20,000 one-row updates: 20,00620,006After 20,000one-row updates02 s after thesnapshot closed
## PostgreSQL 18: a REPEATABLE READ snapshot held open while 5 x 100,000 rows are updated
table size at start: 5784 kB
session A: BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) -> 100000
session B: 5 x UPDATE nb_accounts SET balance = balance + 1  (500,000 new row versions)
table size now: 29 MB
session B: VACUUM (VERBOSE) nb_accounts while A is still open:
  pages: 0 removed, 2655 remain, 2655 scanned (100.00% of total), 0 eagerly scanned
  tuples: 0 removed, 600000 remain, 500000 are dead but not yet removable
  removable cutoff: 757, which was 5 XIDs old when operation ended
dead tuples (pg_stat_user_tables): 500000
session A: ROLLBACK  (the snapshot is released)
session B: VACUUM (VERBOSE) nb_accounts again:
  pages: 0 removed, 2655 remain, 2655 scanned (100.00% of total), 0 eagerly scanned
  tuples: 500000 removed, 100000 remain, 0 are dead but not yet removable
  removable cutoff: 762, which was 0 XIDs old when operation ended
  index "nb_accounts_pkey": pages: 1099 in total, 0 newly deleted, 0 currently deleted, 0 reusable
table size after VACUUM: 29 MB  <- VACUUM made the space reusable; the file did not shrink

## MySQL 8.4: a consistent snapshot held open while 5 x 100,000 rows are updated
History list length at start: 6
session A: START TRANSACTION WITH CONSISTENT SNAPSHOT; SELECT COUNT(*) -> 100000
session B: 5 x UPDATE nb_accounts SET balance = balance + 1
History list length after 5 big UPDATEs: 11  <- it counts transactions waiting for purge, not rows
session B: 20,000 single-row UPDATEs, each its own transaction (12 s)
History list length while A is still open: 20006
session A: COMMIT  (the old read view is released)
   2s after COMMIT, History list length: 0

## MongoDB 8.0: a multi-document transaction left open past the lifetime limit
transactionLifetimeLimitSeconds default: 60 | set to 10 for this run
session A: startTransaction; updateOne({_id: 1}, {$inc: {balance: 10}})
session A: waits 25 s without committing
session A: commitTransaction -> OperationFailure: Transaction with { txnNumber: 2 } has been aborted.
serverStatus().transactions.totalAborted: before 0 after 1
balance now: 100

What I take from it

Full transcript: long-transaction.txt

Notebook 2 · run 2026-11-18 04:26 UTC

What waiting for the log costs per commit

Two thousand single-row inserts, one commit each, with the durable setting on and then off. I ran the durable setting twice, before and after, to see whether the number holds.

How much faster are commits when they do not wait for the log flush: 10 percent, 2 times, or 10 times?

On this machine, about 1.8 times in PostgreSQL, 2.3 times in MySQL and 2.6 times in MongoDB. On a disk where a flush costs more, such as network-attached storage, the gap is larger. Measure on your own disk before you decide.

Milliseconds per commit, lower is faster

The durable setting waits for the log flush on every commit. Measured in Notebook 2, one client, 2,000 commits each.

Waits for the log flush (durable)Does not wait (faster, can lose recent commits)
00.250.50.751PostgreSQLPostgreSQL, Waits for the log flush: 0.236 ms0.236 msPostgreSQL, Does not wait: 0.131 ms0.131 msMySQLMySQL, Waits for the log flush: 0.565 ms0.565 msMySQL, Does not wait: 0.249 ms0.249 msMongoDBMongoDB, Waits for the log flush: 0.954 ms0.954 msMongoDB, Does not wait: 0.368 ms0.368 ms
## PostgreSQL 18: synchronous_commit on vs off
  synchronous_commit = on     4238 commits/s  0.236 ms per commit
  synchronous_commit = off    7607 commits/s  0.131 ms per commit
  synchronous_commit = on     4131 commits/s  0.242 ms per commit

## MySQL 8.4: innodb_flush_log_at_trx_commit and sync_binlog
  innodb_flush_log_at_trx_commit = 1, sync_binlog = 1    1770 commits/s  0.565 ms per commit
  innodb_flush_log_at_trx_commit = 2, sync_binlog = 0    4013 commits/s  0.249 ms per commit
  innodb_flush_log_at_trx_commit = 1, sync_binlog = 1    1798 commits/s  0.556 ms per commit

## MongoDB 8.0 (single-node replica set): write concern j: true vs j: false
  w: 1, j: true     1048 commits/s  0.954 ms per commit
  w: 1, j: false    2716 commits/s  0.368 ms per commit
  w: 1, j: true     1121 commits/s  0.892 ms per commit

What I take from it

Full transcript: commit-cost.txt

Notebook 3 · run 2026-11-18 04:26 UTC

One lookup in a million rows, without and with an index

The same lookup by email, on 1,000,000 rows, in all three engines. Parallel query is off in PostgreSQL so that the plan shows one plain scan.

With an index on email, how many 8 KB pages does PostgreSQL read to find one row out of a million?

Four: shared hit=1 read=3. Without the index it read 19,231, every page of the 150 MB table.

Work to find one row in 1,000,000, log scale

PostgreSQL counts 8 KB pages read. MySQL counts rows read. MongoDB counts documents examined. Each step on the axis is ten times the last.

No indexWith an index
1101001,00010,000100,0001,000,000PostgreSQL pagesPostgreSQL pages, No index: 19,23119,231PostgreSQL pages, With an index: 44MySQL rowsMySQL rows, No index: 1,000,0011,000,001MySQL rows, With an index: 11MongoDB documentsMongoDB documents, No index: 1,000,0001,000,000MongoDB documents, With an index: 11
## PostgreSQL 18
table size: 150 MB | 19231 pages of 8 KB
-- no index on email (parallel query off, to show one plain scan)
  Seq Scan on nb_users (actual time=40.672..70.484 rows=1.00 loops=1)
    Filter: (email = 'user500000@example.com'::text)
    Rows Removed by Filter: 999999
    Buffers: shared hit=14362 read=4869
  Planning:
    Buffers: shared hit=25 read=1
  Planning Time: 0.122 ms
  Execution Time: 70.500 ms
-- after CREATE INDEX nb_users_email ON nb_users (email)
  Index Scan using nb_users_email on nb_users (actual time=0.027..0.027 rows=1.00 loops=1)
    Index Cond: (email = 'user500000@example.com'::text)
    Index Searches: 1
    Buffers: shared hit=1 read=3
  Planning:
    Buffers: shared hit=16 read=1
  Planning Time: 0.158 ms
  Execution Time: 0.038 ms

## MySQL 8.4
-- no index on email
  -> Filter: (nb_users.email = 'user500000@example.com')  (cost=104422 rows=99032) (actual time=361..509 rows=1 loops=1)
      -> Table scan on nb_users  (cost=104422 rows=990318) (actual time=0.971..437 rows=1e+6 loops=1)
  Handler_read_rnd_next (rows read in a scan): 1000001 | Handler_read_key (index lookups): 1 | Handler_read_next: 0
-- after CREATE INDEX nb_users_email ON nb_users (email)
  -> Index lookup on nb_users using nb_users_email (email='user500000@example.com')  (cost=0.706 rows=1) (actual time=0.47..0.471 rows=1 loops=1)
  Handler_read_rnd_next (rows read in a scan): 0 | Handler_read_key (index lookups): 1 | Handler_read_next: 1

## MongoDB 8.0
-- no index on email
  plan: COLLSCAN
  nReturned: 1 | totalKeysExamined: 0 | totalDocsExamined: 1000000 | executionTimeMillis: 436
-- after createIndex({email: 1})
  plan: FETCH <- IXSCAN
  nReturned: 1 | totalKeysExamined: 1 | totalDocsExamined: 1 | executionTimeMillis: 0

What I take from it

Full transcript: scan-vs-index.txt

Notebook 4 · run 2026-11-18 04:27 UTC

Two sessions, interleaved step by step

Two classic concurrency bugs, lost update and write skew, run in each engine with the default settings and then with the fix. Every step is real, in the order shown. The Isolation page explains each one.

Two sessions each read a balance of 100 and add to it, +10 and +20. With the default settings, does PostgreSQL keep both deposits?

No. At READ COMMITTED, the default, the final balance is 120, and the +10 is lost. At REPEATABLE READ, PostgreSQL refuses the second update instead.

Lost update, step by step

PostgreSQL at READ COMMITTED and MySQL at REPEATABLE READ, the defaults. Both ran exactly this sequence in Notebook 4.

Session AThe row: balanceSession BSELECT balance -> 100100SELECT balance -> 100100UPDATE balance = 110; COMMIT110UPDATE balance = 120; COMMIT120final: 120, expected 130
## PostgreSQL 18, lost update, READ COMMITTED (the default)
  A: SELECT balance -> 100
  B: SELECT balance -> 100
  A: UPDATE balance = 110; COMMIT
  B: UPDATE balance = 120; COMMIT -> ok
  final balance: 120  (expected 130 if both deposits count)

## PostgreSQL 18, lost update, REPEATABLE READ
  A: SELECT balance -> 100
  B: SELECT balance -> 100
  A: UPDATE balance = 110; COMMIT
  B: UPDATE balance = 120 -> ERROR: could not serialize access due to concurrent update
  final balance: 110  (expected 130 if both deposits count)

## MySQL 8.4, lost update, REPEATABLE READ (the default)
  A: SELECT balance -> 100
  B: SELECT balance -> 100
  A: UPDATE balance = 110; COMMIT
  B: UPDATE balance = 120; COMMIT -> ok
  final balance: 120  (expected 130 if both deposits count)

## MySQL 8.4, lost update fixed with SELECT ... FOR UPDATE
  A: SELECT balance FOR UPDATE -> 100
  B: SELECT balance FOR UPDATE -> still waiting after 1.5 s: True
  A: UPDATE balance = 110; COMMIT
  B: ... the SELECT FOR UPDATE returns -> 110
  B: UPDATE balance = 130; COMMIT -> ok
  final balance: 130  (expected 130 if both deposits count)

## MongoDB 8.0, lost update, inside two transactions
  A: findOne -> balance 100
  B: findOne -> balance 100
  A: updateOne balance = 110; commitTransaction
  B: updateOne balance = 120 -> OperationFailure: Caused by :: Write conflict during plan execution and yielding is disabled. :: Please retry your operation or multi-document transaction.
  final balance: 110  (expected 130 if both deposits count)

## PostgreSQL 18, write skew, REPEATABLE READ
  A: SELECT count(*) WHERE on_call -> 2
  B: SELECT count(*) WHERE on_call -> 2
  A: UPDATE alice off call
  B: UPDATE bob off call
  A: COMMIT -> ok
  B: COMMIT -> ok
  doctors on call at the end: 0  (the rule was: at least 1)

## PostgreSQL 18, write skew, SERIALIZABLE
  A: SELECT count(*) WHERE on_call -> 2
  B: SELECT count(*) WHERE on_call -> 2
  A: UPDATE alice off call
  B: UPDATE bob off call
  A: COMMIT -> ok
  B: COMMIT -> ERROR: could not serialize access due to read/write dependencies among transactions
  doctors on call at the end: 1  (the rule was: at least 1)

## MySQL 8.4, write skew, REPEATABLE READ (the default)
  A: SELECT COUNT(*) WHERE on_call -> 2
  B: SELECT COUNT(*) WHERE on_call -> 2
  A: UPDATE alice off call
  B: UPDATE bob off call
  A: COMMIT -> ok
  B: COMMIT -> ok
  doctors on call at the end: 0  (the rule was: at least 1)

## MongoDB 8.0, write skew, inside two transactions
  A: countDocuments({on_call: true}) -> 2
  B: countDocuments({on_call: true}) -> 2
  A: updateOne alice off call
  B: updateOne bob off call
  A: commitTransaction -> ok
  B: commitTransaction -> ok
  doctors on call at the end: 0  (the rule was: at least 1)

What I take from it

Full transcript: anomalies.txt

Notebook 5 · run 2026-11-18 04:27 UTC

Five query shapes on a million orders

An orders table with an index on (customer_id, created_at), and five query shapes that show up in most application code. The Queries page walks through each one.

The index is on (customer_id, created_at). A query filters only on created_at. Does any of the three engines use the index?

None of them did. PostgreSQL and MySQL scanned the whole table, and MongoDB did a COLLSCAN, because the index is sorted by customer_id first.

Rows read: both index columns against the second column alone, log scale

Index on (customer_id, created_at). Measured in Notebook 5.

WHERE created_at >= ... onlyWHERE customer_id = 42 AND created_at >= ...
1101001,00010,000100,0001,000,000PostgreSQLPostgreSQL, Second column only: 1,000,0001,000,000PostgreSQL, Both columns, in order: 4444MySQLMySQL, Second column only: 1,000,0011,000,001MySQL, Both columns, in order: 4444MongoDBMongoDB, Second column only: 1,000,0001,000,000MongoDB, Both columns, in order: 4444

Rows read to return page 25,001 (20 rows), log scale

OFFSET 500000 against WHERE id > 500000. Measured in Notebook 5 on 1,000,000 orders.

OFFSET 500000 / skip(500000)WHERE id > 500000
1101001,00010,000100,0001,000,000PostgreSQLPostgreSQL, OFFSET or skip: 500,020500,020PostgreSQL, By key: 2020MySQLMySQL, OFFSET or skip: 500,019500,019MySQL, By key: 1919MongoDBMongoDB, OFFSET or skip: 500,020500,020MongoDB, By key: 2020
## PostgreSQL 18
-- 1. both columns of the index, in order
   SELECT * FROM nb_orders WHERE customer_id = 42 AND created_at >= '2026-06-01'
  Bitmap Heap Scan on nb_orders (actual time=0.046..0.089 rows=44.00 loops=1)
    Recheck Cond: ((customer_id = 42) AND (created_at >= '2026-06-01 00:00:00'::timestamp without time zone))
    Heap Blocks: exact=44
    Buffers: shared hit=44 read=4
    ->  Bitmap Index Scan on nb_orders_cust_created (actual time=0.036..0.037 rows=44.00 loops=1)
          Index Cond: ((customer_id = 42) AND (created_at >= '2026-06-01 00:00:00'::timestamp without time zone))
          Index Searches: 1
          Buffers: shared read=4
  Planning:
    Buffers: shared hit=33
  Planning Time: 0.149 ms
  Execution Time: 0.102 ms
-- 2. only the second column of the index
   SELECT * FROM nb_orders WHERE created_at >= '2026-11-17'
  Seq Scan on nb_orders (actual time=20.432..39.127 rows=1440.00 loops=1)
    Filter: (created_at >= '2026-11-17 00:00:00'::timestamp without time zone)
    Rows Removed by Filter: 998560
    Buffers: shared hit=7353
  Planning Time: 0.054 ms
  Execution Time: 39.180 ms
-- 3. covering: every column needed is in the index
   SELECT customer_id, created_at FROM nb_orders WHERE customer_id = 42
  Index Only Scan using nb_orders_cust_created on nb_orders (actual time=0.024..0.042 rows=100.00 loops=1)
    Index Cond: (customer_id = 42)
    Heap Fetches: 0
    Index Searches: 1
    Buffers: shared hit=5
  Planning Time: 0.081 ms
  Execution Time: 0.062 ms
-- 4a. paging with OFFSET
   SELECT * FROM nb_orders ORDER BY id OFFSET 500000 LIMIT 20
  Limit (actual time=64.443..64.447 rows=20.00 loops=1)
    Buffers: shared hit=5046
    ->  Index Scan using nb_orders_pkey on nb_orders (actual time=0.019..51.008 rows=500020.00 loops=1)
          Index Searches: 1
          Buffers: shared hit=5046
  Planning:
    Buffers: shared read=3
  Planning Time: 0.150 ms
  Execution Time: 64.461 ms
-- 4b. paging with a key (keyset)
   SELECT * FROM nb_orders WHERE id > 500000 ORDER BY id LIMIT 20
  Limit (actual time=0.040..0.047 rows=20.00 loops=1)
    Buffers: shared hit=4
    ->  Index Scan using nb_orders_pkey on nb_orders (actual time=0.039..0.043 rows=20.00 loops=1)
          Index Cond: (id > 500000)
          Index Searches: 1
          Buffers: shared hit=4
  Planning:
    Buffers: shared hit=3
  Planning Time: 0.097 ms
  Execution Time: 0.060 ms
-- 5. N+1 from the application: latest order for 100 customers
  100 queries, one per customer: 20.1 ms | 1 query with = ANY(list): 1.6 ms

## MySQL 8.4
-- 1. both columns of the index, in order
   SELECT * FROM nb_orders WHERE customer_id = 42 AND created_at >= '2026-06-01'
  -> Index range scan on nb_orders using nb_orders_cust_created over (customer_id = 42 AND '2026-06-01 00:00:00' <= created_at), with index condition: ((nb_orders.customer_id = 42) and (nb_orders.created_at >= TIMESTAMP'2026-06-01 00:00:00'))  (cost=20.1 rows=44) (actual time=0.138..0.144 rows=44 loops=1)
  rows touched (Handler_read_next + Handler_read_rnd_next): 44
-- 2. only the second column of the index
   SELECT * FROM nb_orders WHERE created_at >= '2026-11-17'
  -> Filter: (nb_orders.created_at >= TIMESTAMP'2026-11-17 00:00:00')  (cost=100443 rows=332398) (actual time=118..224 rows=1440 loops=1)
      -> Table scan on nb_orders  (cost=100443 rows=997294) (actual time=0.229..177 rows=1e+6 loops=1)
  rows touched (Handler_read_next + Handler_read_rnd_next): 1000001
-- 3. covering: every column needed is in the index
   SELECT customer_id, created_at FROM nb_orders WHERE customer_id = 42
  -> Covering index lookup on nb_orders using nb_orders_cust_created (customer_id=42)  (cost=11.2 rows=100) (actual time=0.0166..0.0239 rows=100 loops=1)
  rows touched (Handler_read_next + Handler_read_rnd_next): 100
-- 4a. paging with OFFSET
   SELECT * FROM nb_orders ORDER BY id LIMIT 20 OFFSET 500000
  -> Limit/Offset: 20/500000 row(s)  (cost=25427 rows=20) (actual time=98.8..98.8 rows=20 loops=1)
      -> Index scan on nb_orders using PRIMARY  (cost=25427 rows=500020) (actual time=0.253..86.1 rows=500020 loops=1)
  rows touched (Handler_read_next + Handler_read_rnd_next): 500019
-- 4b. paging with a key (keyset)
   SELECT * FROM nb_orders WHERE id > 500000 ORDER BY id LIMIT 20
  -> Limit: 20 row(s)  (cost=99876 rows=20) (actual time=0.252..0.257 rows=20 loops=1)
      -> Filter: (nb_orders.id > 500000)  (cost=99876 rows=498647) (actual time=0.251..0.256 rows=20 loops=1)
          -> Index range scan on nb_orders using PRIMARY over (500000 < id)  (cost=99876 rows=498647) (actual time=0.25..0.253 rows=20 loops=1)
  rows touched (Handler_read_next + Handler_read_rnd_next): 19

## MongoDB 8.0
-- 1. both fields of the index, in order
   {"find": "nb_orders", "filter": {"customer_id": 42, "created_at": {"$gte": "2026-06-01 00:00:00"}}}
  plan: FETCH <- IXSCAN
  nReturned: 44 | totalKeysExamined: 44 | totalDocsExamined: 44 | executionTimeMillis: 1
-- 2. only the second field of the index
   {"find": "nb_orders", "filter": {"created_at": {"$gte": "2026-11-17 00:00:00"}}}
  plan: COLLSCAN
  nReturned: 1440 | totalKeysExamined: 0 | totalDocsExamined: 1000000 | executionTimeMillis: 436
-- 3. covering: projection only uses indexed fields
   {"find": "nb_orders", "filter": {"customer_id": 42}, "projection": {"_id": 0, "customer_id": 1, "created_at": 1}}
  plan: PROJECTION_COVERED <- IXSCAN
  nReturned: 100 | totalKeysExamined: 100 | totalDocsExamined: 0 | executionTimeMillis: 0
-- 4a. paging with skip
   {"find": "nb_orders", "filter": {}, "sort": {"_id": 1}, "skip": 500000, "limit": 20}
  plan: LIMIT <- FETCH <- SKIP <- IXSCAN
  nReturned: 20 | totalKeysExamined: 500020 | totalDocsExamined: 20 | executionTimeMillis: 231
-- 4b. paging with a key (keyset)
   {"find": "nb_orders", "filter": {"_id": {"$gt": 500000}}, "sort": {"_id": 1}, "limit": 20}
  plan: LIMIT <- FETCH <- IXSCAN
  nReturned: 20 | totalKeysExamined: 20 | totalDocsExamined: 20 | executionTimeMillis: 0

What I take from it

Full transcript: queries.txt

Notebook 6 · run 2026-11-18 21:22 UTC

The rules the design docs rely on

The design docs say "let the database enforce the rule". This notebook checks four of those rules on real servers: the last item in stock, a retried payment, an overlapping booking, and a query that forgets its tenant filter.

Sixteen clients try 1,600 purchases of an item with 1,000 in stock. Each one reads the stock, and if it is above zero, writes the stock minus one. How many sales go through?

All 1,600, in every engine, and the stock still shows hundreds left. The conditional update, UPDATE ... WHERE available >= 1, sold exactly 1,000 and left 0.

Units sold of a 1,000-unit stock, 1,600 attempts

Sixteen clients at once. Measured in Notebook 6.

Read, then write the new valueUPDATE ... WHERE available >= 1
05001,0001,5002,000PostgreSQLPostgreSQL, Read, then write the new value: 1,6001,600PostgreSQL, Conditional update: 1,0001,000MySQLMySQL, Read, then write the new value: 1,6001,600MySQL, Conditional update: 1,0001,000MongoDBMongoDB, Read, then write the new value: 1,6001,600MongoDB, Conditional update: 1,0001,000stock: 1,000
## 1. The last item: 1000 units, 16 clients each trying 100 purchases at once (1600 attempts)
  PostgreSQL, read, then write the new value:    sold 1600 of 1000, stock left  869, 0.5 s
  PostgreSQL, UPDATE ... WHERE available >= 1:   sold 1000 of 1000, stock left    0, 0.3 s
  MySQL,      read, then write the new value:    sold 1600 of 1000, stock left  888, 0.4 s
  MySQL,      UPDATE ... WHERE available >= 1:   sold 1000 of 1000, stock left    0, 0.6 s
  MongoDB,    read, then $set the new value:     sold 1600 of 1000, stock left  799, 0.6 s
  MongoDB,    updateOne({available: {$gte: 1}}, $inc): sold 1000 of 1000, stock left    0, 0.3 s

## 2. A retried payment with an idempotency key (PostgreSQL)
  attempt 1, key pay-abc: committed
  attempt 2, same key (a client retry): rolled back: duplicate key value violates unique constraint "nb_idem_pkey"
  ledger rows: 2 | sum of amounts: 0 | alice: -500

## 3. Two bookings for the same room and overlapping times
  PostgreSQL, room 7, 14:00-16:00 -> booked
  PostgreSQL, room 7, 15:00-17:00 -> conflicting key value violates exclusion constraint "nb_room_bookings_room_id_during_excl"
  PostgreSQL, room 7, 16:00-18:00 -> booked
  MySQL, event 99, seat A12, booking 1 -> booked
  MySQL, event 99, seat A12, booking 2 -> Duplicate entry '99-A12' for key 'nb_seat_bookings.PRIMARY'

## 4. A query that forgets WHERE tenant_id = ... (PostgreSQL row-level security)
  as the application role, tenant 2, SELECT count(*) FROM nb_projects -> 10
  same role, the rows it sees, by tenant -> [(2, 10)]
  as postgres (a superuser), same query -> 30  <- superusers bypass row-level security

What I take from it

Full transcript: design-checks.txt

Notebook 7 · run 2026-11-18 21:26 UTC

Redis, ClickHouse and Cassandra

The design docs add three stores to the main engines: Redis for counters and leaderboards, ClickHouse for reports, Cassandra for message history. This notebook runs the pattern each design doc relies on.

ClickHouse holds 10,000,000 order lines. A revenue report filters on one month and sums two columns. How many rows does it read?

870,400 rows and about 15 MB, in 8 ms. The table is partitioned by month and sorted by SKU and time, so ClickHouse skipped every part that could not match and read only the columns the query names.

ClickHouse: compression ratio per column, log scale

Columns with few distinct values compress by 100 times or more. Unique or time-like columns barely compress. Measured in Notebook 7 on 10,000,000 rows.

1101001,000notenote, Compression ratio: 208.5x208.5xqtyqty, Compression ratio: 195.4x195.4xskusku, Compression ratio: 100.2x100.2xprice_centsprice_cents, Compression ratio: 18.8x18.8xcustomer_idcustomer_id, Compression ratio: 9.3x9.3xorder_idorder_id, Compression ratio: 1.8x1.8xcreated_atcreated_at, Compression ratio: 1.0x1.0x
# Redis: 7.4.12
## Redis: a leaderboard of 100,000 players in a sorted set
  memory for the sorted set: 9.6 MB
  10,000 ZINCRBY, one round trip each: 12511 ops/s, 0.080 ms each
  ZREVRANGE top 10: 0.212 ms -> player:11605=100045, player:52494=100036, player:4988=100022 ...
  ZREVRANK player:42: rank 67405 in 0.099 ms
## Redis: a fixed-window rate limit, 5 requests per window
  request 1 -> count 1 -> allowed
  request 2 -> count 2 -> allowed
  request 3 -> count 3 -> allowed
  request 4 -> count 4 -> allowed
  request 5 -> count 5 -> allowed
  request 6 -> count 6 -> rejected
  request 7 -> count 7 -> rejected
  TTL on the key: 2 s; waiting 3 s ...
  key exists after the window: False -> the next request starts a new window

# ClickHouse: 24.8.14.39
## ClickHouse: 10,000,000 order lines, then a report that reads two columns
  INSERT ... SELECT of 10,000,000 rows in one statement: 4.2 s
  column created_at   on disk 37.26 MiB  uncompressed 37.10 MiB  ratio 1.0x
  column customer_id  on disk 8.02 MiB   uncompressed 74.19 MiB  ratio 9.3x
  column note         on disk 592.07 KiB uncompressed 120.56 MiB ratio 208.5x
  column order_id     on disk 41.27 MiB  uncompressed 74.19 MiB  ratio 1.8x
  column price_cents  on disk 3.95 MiB   uncompressed 74.19 MiB  ratio 18.8x
  column qty          on disk 194.42 KiB uncompressed 37.10 MiB  ratio 195.4x
  column sku          on disk 142.99 KiB uncompressed 13.99 MiB  ratio 100.2x
  revenue by SKU since 2026-10-01, top 3: [('sku-499', 444315.9), ('sku-99', 444051.0), ('sku-399', 444025.9)] in 8 ms
  rows read: 870400, bytes read: 15273984
## ClickHouse: one row per INSERT against one batch
  200 single-row INSERTs: 0.24 s, 200 parts on disk (merges paused to show it)
  1 INSERT of 200 rows:   0.004 s, 1 part on disk

# Cassandra: 5.0.9
## Cassandra: chat messages, partitioned by (conversation_id, bucket)
  100,000 messages across 1,000 conversations written in 10.7 s
  latest 20 messages of conversation 42 (one partition): 20 rows in 3.3 ms, newest first: message 99042
  query by sender_id (not part of the key): rejected -> "Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING"

What I take from it

Full transcript: other-engines.txt

Notebook 8 · run 2026-11-19 02:14 UTC

pgvector for agent memory

An agent remembers things by storing text with an embedding and searching for the nearest ones before each step. This notebook stores 100,000 memories for 100 tenants in PostgreSQL 18 with pgvector 0.8.7, then measures what it costs to store them, how recall trades against speed, and what a tenant filter does to the search.

One tenant's memories are 1% of the table. You ask for that tenant's 10 nearest memories with WHERE tenant_id = ? and LIMIT 10, using the HNSW index with the default ef_search of 40. How many rows come back?

1.3 on average, not 10. The index found its 40 nearest candidates across all tenants, then the filter threw away the 99% that belonged to someone else. Turning on iterative scan returned all 10.

Recall of the top 10 against hnsw.ef_search

Share of the true 10 nearest memories the index returned, 200 searches. Median time per search: 0.6 ms at 10, 0.59 ms at 20, 0.65 ms at 40, 0.71 ms at 80, 0.81 ms at 160, 2.64 ms at 400. Exact search without the index: 21.7 ms. Measured in Notebook 8 on 100,000 memories.

00.250.50.751ef_search 10ef_search 10, recall@10: 0.7970.797ef_search 20ef_search 20, recall@10: 0.8630.863ef_search 40ef_search 40, recall@10: 0.950.95ef_search 80ef_search 80, recall@10: 0.9850.985ef_search 160ef_search 160, recall@10: 11ef_search 400ef_search 400, recall@10: 11

Searching one tenant's memories: rows returned out of 10

The same search with WHERE tenant_id = ?, where one tenant is 1% of the table. Median time: HNSW, then filter 0.76 ms, ef_search 400, filter 3.89 ms, HNSW, iterative scan 8.96 ms, tenant index, exact 2.66 ms. Measured in Notebook 8.

025810HNSW, then filterHNSW, then filter, rows returned: 1.31.3ef_search 400, filteref_search 400, filter, rows returned: 4.84.8HNSW, iterative scanHNSW, iterative scan, rows returned: 1010tenant index, exacttenant index, exact, rows returned: 1010
Data: 100,000 memories of 384 dimensions, generated around 500 topics in a 64-dimension space and
projected up, because real embeddings cluster by subject and use far fewer directions than they have.
100 tenants (agents or customers), 1,000 memories each.
Generated vectors are not real embeddings, so treat recall as the shape of the curve, not a promise.
Timings are from a client on the same machine and include the round trip.

## 1. What it costs to store
  loaded 100,000 rows in 11.0 s
  table: 157 MB, 1641 bytes per memory (a 384-dimension vector is 1536 bytes of floats)
  HNSW index (m = 16, ef_construction = 64): built in 10.5 s, 195 MB, 2048 bytes per memory
  table plus HNSW index: 3689 bytes per memory, 2.4 times the raw floats

## 2. Recall against speed: top 10 nearest memories, 200 searches each
  exact search (no index, reads every row): 21.7 ms per search
  plan with the index: Index Scan using nb_memory_hnsw
  hnsw.ef_search =  10   recall@10 0.797   median 0.60 ms   p95 1.10 ms
  hnsw.ef_search =  20   recall@10 0.863   median 0.59 ms   p95 0.85 ms
  hnsw.ef_search =  40   recall@10 0.950   median 0.65 ms   p95 1.08 ms
  hnsw.ef_search =  80   recall@10 0.985   median 0.71 ms   p95 2.17 ms
  hnsw.ef_search = 160   recall@10 1.000   median 0.81 ms   p95 1.40 ms
  hnsw.ef_search = 400   recall@10 1.000   median 2.64 ms   p95 3.62 ms

## 3. Filtering by tenant: one tenant's memories are 1% of the table
  planner's choice for the filtered query: HNSW index, then filter
  HNSW, ef_search 40, then filter:                     rows returned 1.3 of 10   recall@10 0.130   median 0.76 ms
  HNSW, ef_search 400, then filter:                    rows returned 4.8 of 10   recall@10 0.477   median 3.89 ms
  HNSW, ef_search 40, iterative_scan = relaxed_order:  rows returned 10.0 of 10   recall@10 0.906   median 8.96 ms
  tenant index, then exact distance on 1,000 rows:     rows returned 10.0 of 10   recall@10 1.000   median 2.66 ms

Read it this way: with the filter applied after the index, the index hands back about ef_search
candidates and 99% of them belong to other tenants. Raising ef_search or scanning iteratively
fixes it at a cost; for small tenants an exact search inside the tenant is both exact and fast.

What I take from it

Generated vectors, not real embeddings: treat the recall numbers as the shape of the curve. Full transcript: agent-memory.txt. Script: scripts/notebooks/run_vector.py.

Notebook 9 · run 2026-11-19 19:50 UTC

Redis and Cassandra when something fails

Notebook 7 measured Redis and Cassandra on one healthy node. This one breaks them. Redis is killed mid-write with and without the AOF, then a primary is killed while its replica lags. Cassandra runs as a real three-node cluster with replication factor 3, and nodes are stopped one at a time while the client writes and reads at ONE, QUORUM and ALL.

Redis has appendfsync everysec. The process is killed with kill -9 while a client writes as fast as it can. How many acknowledged writes are lost?

None, of about 40,000. Redis writes the AOF to the file before it replies, so the data is in the operating system's cache; only the fsync waits up to a second. A killed process loses nothing. A power cut or kernel crash could lose that last second, which this lab cannot simulate.

# Notebook 9: Redis and Cassandra when something fails
# run at: 2026-11-19 19:50 UTC
# runner: Linux-7.0.0-1019-azure-x86_64-with-glibc2.43 | 4 vCPU
Timings are from a client on the same machine and include the round trip.

## Redis
### 1. The process is killed (kill -9) while one client writes, then restarted
  AOF on, appendfsync everysec:                acknowledged  40200, present after restart  40200, lost      0
  AOF off, snapshots on the default schedule:  acknowledged  42269, present after restart      0, lost  42269
  Redis 7.4.12, one client, one SET per round trip: about 8040 writes a second
  Read it this way: a killed process does not lose what it already handed to the operating system.
  The AOF is written to the file before the reply, and only the fsync waits up to a second, so only
  a machine crash or power loss can lose that last second. With snapshots only, everything since the
  last snapshot is gone: the default schedule had not taken one yet.

### 2. Failover to a lagging replica
  The replica is frozen (docker pause) for one second to stand in for a slow network or a busy
  replica. The primary is killed during that second, then the replica is unfrozen and promoted.
  plain SET, replication is asynchronous:              acknowledged  29981, on the promoted replica  27764, lost 2217. Median write 0.132 ms
  SET then WAIT 1 500, count only confirmed writes:    acknowledged   9894,    1 of them reported unconfirmed by WAIT; confirmed and lost: 0. Median write 0.299 ms
  Read it this way: the primary acknowledges a write before any replica has it. Writes acknowledged
  while the replica was behind are gone after the promotion. WAIT does not stop that, but it tells the
  client which writes no replica confirmed, so the application can retry them or report them. It does
  not make Redis a consensus system. Only 1 write was reported unconfirmed because the client writes
  one at a time: the first write after the freeze spent its 500 ms WAIT timing out, and the primary
  was killed before the next WAIT could time out, so the client saw a dead connection instead.

## Cassandra: three nodes, replication factor 3
  cluster of 3 up in 139 s
    --  Address     Load        Tokens  Owns (effective)  Host ID                             
    UN  172.18.0.3  80.02 KiB   16      59.3%             1840ea45-98cf-4cec-aeb7-c5ad7552a155
    UN  172.18.0.2  119.83 KiB  16      64.7%             b4f5ca88-5c68-4577-9116-f2c49c185178
    UN  172.18.0.4  30.88 KiB   16      76.0%             d73d5592-9df2-429a-8354-9b7f1c4f2bd8
# Cassandra: 5.0.9
### 1. All three nodes up: 500 writes and 500 reads at each consistency level
  3 of 3 up:             ONE     writes ok  500 of 500   reads found  500   median write  2.05 ms, read  1.86 ms
  3 of 3 up:             QUORUM  writes ok  500 of 500   reads found  500   median write  1.51 ms, read  2.32 ms
  3 of 3 up:             ALL     writes ok  500 of 500   reads found  500   median write  1.27 ms, read  1.92 ms
### 2. One node stopped
  2 of 3 up:             ONE     writes ok  500 of 500   reads found  500   median write  0.74 ms, read  0.77 ms
  2 of 3 up:             QUORUM  writes ok  500 of 500   reads found  500   median write  0.92 ms, read  1.02 ms
  2 of 3 up:             ALL     writes ok    0 of 500 (Unavailable)   reads found    0   median write   nan ms, read   nan ms
### 3. Two nodes stopped
  1 of 3 up:             ONE     writes ok  500 of 500   reads found  500   median write  0.41 ms, read  0.59 ms
  1 of 3 up:             QUORUM  writes ok    0 of 500 (NoHostAvailable)   reads found    0   median write   nan ms, read   nan ms
  1 of 3 up:             ALL     writes ok    0 of 500 (NoHostAvailable)   reads found    0   median write   nan ms, read   nan ms
### 4. Both nodes back. Do they get the writes they missed?
  pending hints on the other nodes: none after 15 s
  with only node 3 running, reads at ONE of the 1500 writes it missed while down: 1500 found
  (1,000 written at ONE and QUORUM with node 3 down, 500 at ONE with nodes 2 and 3 down)
  Read it this way: with three copies, QUORUM needs two. One node down, QUORUM still works and ALL
  fails at once with Unavailable. Two down, only ONE works, and those writes live on one machine until
  the others come back and hints (kept up to max_hint_window, 3 hours by default) or repair copy them.

What I take from it

Containers on one GitHub runner, so network delay between replicas is near zero; docker pause stands in for a lagging replica. Full transcript: failure.txt. Script: scripts/notebooks/run_failure.py.

Notebook 10 · run 2026-11-22 08:21 UTC

What the primary key costs on insert

One million rows, inserted in 100 transactions of 10,000, into three tables that differ only in the primary key: an increasing integer, a random 16-byte UUID, and a time-ordered one. PostgreSQL 18 and MySQL 8.4, stock settings.

MySQL, one million rows, a random 16-byte primary key against a time-ordered one. How much slower are the random inserts?

About ten times: 55.5 seconds against 5.7. The table, which in InnoDB is the primary key B-tree, ended up 236 MB instead of 146 MB. The random keys spread inserts over every page of a tree that no longer fit in the 128 MB default buffer pool, so most inserts had to read a page from disk first.

Notebook 10: what the primary key costs on insert
run: 2026-11-22 08:21 UTC | Linux-7.0.0-1020-azure-x86_64-with-glibc2.43
1000000 rows per table, 100 transactions of 10000 rows, a 100-byte pad column
server: PostgreSQL 18.7 (Debian 18.7-1.pgdg13+5) on x86_64-pc-linux-gnu, compiled by gcc (Debian 14.2.0-19) 14.2.0, 64-bit
PostgreSQL | bigint identity | insert 3.4 s | 293046 rows/s | index 21.4 MB | leaf pages 2733 | leaf density 90.0% | tree levels 3 | table 142.0 MB | WAL 234.6 MB
PostgreSQL | uuid v4, gen_random_uuid() | insert 4.6 s | 218065 rows/s | index 38.4 MB | leaf pages 4889 | leaf density 70.6% | tree levels 3 | table 150.2 MB | WAL 262.0 MB
PostgreSQL | uuid v7, uuidv7() | insert 3.2 s | 311824 rows/s | index 30.1 MB | leaf pages 3832 | leaf density 90.0% | tree levels 3 | table 150.2 MB | WAL 248.0 MB
server: 8.4.13
MySQL | BIGINT AUTO_INCREMENT | insert 6.2 s | 162104 rows/s | clustered index (the table) 137.7 MB | page splits 8782
MySQL | BINARY(16), RANDOM_BYTES(16) | insert 55.5 s | 18017 rows/s | clustered index (the table) 236.0 MB | page splits 21895
MySQL | BINARY(16), UUID_TO_BIN(UUID(), 1) | insert 5.7 s | 174368 rows/s | clustered index (the table) 145.8 MB | page splits 31169

Containers on one GitHub runner, 4 vCPUs, stock settings. Full transcript: ids.txt. Script: scripts/notebooks/run_ids.py.

Your turn

Notebook 2 shows durable commits costing about twice as much as non-durable ones, with one client. Why would that gap shrink with 50 clients committing at once?

Write your answer down first. Then open mine.

Show my answer

Group commit: when many transactions commit at the same moment, the engine writes all their log records and flushes the log once for the whole group. One flush is shared by dozens of commits, so the cost of waiting for the disk is spread across them.

PostgreSQL, InnoDB with the binary log, and WiredTiger's journal all do this. That is why a single-client benchmark is the worst case for durability, and why the honest answer to "can we afford durable commits" is to measure it with your real concurrency.

Connected

Where this shows up

The same mechanism, what a commit promises, indexes and plans, concurrent writes and isolation, elsewhere on the site: in real incidents, in measurements, and in designs.

Part 2 of 4 · Practice · 9 pagesAll pages

Can I see it happen? Simulations, an index you build yourself, a real PostgreSQL in your browser, experiments run on real servers, and tools for your own database: a query coach, an EXPLAIN reader, a config checker and a health check.