Home›Learn›Database napkin math
Course · FoundationsLesson 4 of 330 read

Database napkin math

How big will this table be, and what will it cost to run?

One worked example in eight steps, and the rules of thumb behind it.

Press Play, or step with the arrows.

Napkin math is how you find out, before writing code, whether a design fits on one server. For a database it comes down to a few quantities: bytes per row, rows per page, bytes of index per row, bytes of log per change, and how fast one disk flush is.

The numbers worth remembering

Go deeper
QuantityRule of thumbWhere it comes from
Page8 KB in PostgreSQL, 16 KB in InnoDBThe unit every engine reads and writes
Row overheadAbout 28 bytes in PostgreSQL, about 20 in InnoDBHeader plus pointer, per row
bigint primary key indexAbout 22 bytes a rowNotebook 10: 21.4 MB per million rows
UUIDv4 primary key indexAbout 40 bytes a rowNotebook 10: 38.4 MB per million, pages 70% full
WAL per insertOften more than the row itselfNotebook 10: 235 MB for 1,000,000 rows of 145 bytes
Durable commit, one connectionA few thousand a second, set by the disk flushNotebook 2: 0.236 ms per commit
Index lookupA handful of pages, whatever the table sizeNotebook 3: 4 pages in 1,000,000 rows
Full scanEvery pageNotebook 3: 19,231 pages, 158 MB

Notebook 3 measured a users table, a different row size from the orders row above, which is why its page count does not match the 56 rows a page worked out here. These are from one GitHub runner with stock settings. They are good enough to tell whether a design needs one server or ten, which is what napkin math is for. Before you buy hardware, run the same insert on your own disk.

Check the estimate on a real table

Go deeper
SELECT pg_size_pretty(pg_relation_size('orders'))       AS table_size,
       pg_size_pretty(pg_indexes_size('orders'))        AS indexes,
       (SELECT reltuples::bigint FROM pg_class WHERE relname = 'orders') AS rows_estimate;
-- WAL written in the last minute: run twice, 60 seconds apart
SELECT pg_current_wal_lsn();
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), '<first value>'));
Connected

Where this shows up

The same mechanism, sharding and partitioning, keys and ids, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 3 questions

Check yourself

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

1. A 145-byte row. About how many fit in one 8 KB PostgreSQL page?

2. Which is usually bigger per insert in PostgreSQL?

3. One connection, one insert per commit, 0.236 ms per log flush. Roughly what is the ceiling?

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.