Scaling a database
One shop's database through a growing day. The usual moves in the usual order: an index, a bigger machine, a cache, read replicas, sharding. Watch which one carries the reads, which carries the writes, and what each costs.
What you'll take away
- Find the slow queries with
pg_stat_statementsand index them before buying machines - Put the moves in order, index to sharding, and say what each one costs
- Explain why a replica shows the old value right after a save, and work around it
- Know why replicas don't help writes, and pick a shard key that spreads them
The 1-minute version
Tap a point and the picture below plays that step.
Step to the flash sale, then try each move: which one carries reads, which one carries writes. The numbers are the model's (4,000 units a second a machine; a read 1, a write 2, a read without its index 10)
The database is slow even with few visitors. What do you do first?
The picture: shoppers on the plaza, the app up the avenue, the database machines on the street behind it. Blue lights are reads, amber ones writes; lit windows are work, and a machine past its capacity turns red, and so do the lights it can't take. Redis is the low building beside the app. With replicas the primary (P) stands first and R1 to R4 follow down the street: the dashed cable on their roofs carries each change, and a replica's roof slab is amber while it is behind. With shards, S0 to S7 each hold the customers whose id % 8 is their number. The load beside each name, and every number, comes from a model, not a real database.
Compare them all: Scaling a database
The same day in every tile: opening, busy, packed, a write-heavy flash sale, and a report over every customer. See which move carries the reads, the writes or the report, and which pays with values that may be old.
Use it when Every system starts here: index the slow queries and fix them before buying machines. The cheapest move
Skip it when Once the queries are as good as they get and it's still not enough, move on
A model: 4,000 units a second a machine (the biggest 8,000), a read 1, a write 2, a cache answering 90%, 4 replicas, 8 shards. Made-up numbers. Press any tile to see it large above, with when it fits.
What each move carries
| Move | Reads | Writes | The price |
|---|---|---|---|
| Index, better queries | Much cheaper | A little dearer | Disk, write cost |
| A bigger machine | Up to its ceiling | Up to its ceiling | Money, a ceiling |
| Cache | Most never reach the DB | No help | Values may be old |
| Read replicas | Shared out | No help | Replication lag |
| Sharding | Shared out | Shared out | Cross-shard joins, resharding |
Cheap and easy first
Most slow databases have a few slow queries, not too little hardware. Measure first (the slow query log, pg_stat_statements), index and fix, then grow the machine. Caches and replicas come when reads outgrow it; sharding when the writes or the data itself do.
Denormalise on purpose
Keeping a copy (an order's total, a post's like count) saves a join or a count on every read, at the cost of keeping the copy right on every write. Worth it for the hot reads, not everywhere.
In real code
-- PostgreSQL 16: a big orders table split into 4 partitions by customer_id (on one machine). A query that names the
-- customer reads one partition (partition pruning); a report over everyone reads them all. Sharding is the same idea
-- spread over machines (Citus does it for PostgreSQL), where "reads them all" means asking every machine.
CREATE TABLE orders (id bigint, customer_id int NOT NULL, total numeric(10, 2) NOT NULL) PARTITION BY HASH (customer_id);
CREATE TABLE orders_p0 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE orders_p1 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE orders_p2 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE orders_p3 PARTITION OF orders FOR VALUES WITH (MODULUS 4, REMAINDER 3);
INSERT INTO orders SELECT i, i % 1000, (i % 50) * 10 FROM generate_series(1, 100000) AS i;
ANALYZE orders;
-- The rows spread over the four parts.
SELECT tableoid::regclass AS part, count(*) FROM orders GROUP BY 1 ORDER BY 1;
-- One customer: only one partition is read.
EXPLAIN (COSTS OFF) SELECT sum(total) FROM orders WHERE customer_id = 42;
-- Everyone: every partition is read, then the results appended.
EXPLAIN (COSTS OFF) SELECT sum(total) FROM orders;
psql -f partition.pg.sql (checked against PostgreSQL 16 in Docker)It printed:orders_p0|25900
orders_p1|23400
orders_p2|27600
orders_p3|23100
Aggregate
-> Seq Scan on orders_p2 orders
Filter: (customer_id = 42)
Aggregate
-> Append
-> Seq Scan on orders_p0 orders_1
-> Seq Scan on orders_p1 orders_2
-> Seq Scan on orders_p2 orders_3
-> Seq Scan on orders_p3 orders_4One orders table in 4 hash partitions by customer_id. A query for one customer reads one partition; a report reads them all. Really run on PostgreSQL 16 in Docker; below is what it printed (the rows per part, then both plans).
Common questions
My database is slow. Where do I start?
Measure first: the slow query log or pg_stat_statements shows which queries eat the time, and it's usually a handful. Index or fix those before anything else. A database that's slow with few users is almost always the queries, not the machine.
Can't I just keep buying a bigger machine?
You can, and it's the easiest second step: no app changes, the data stays in one place, transactions stay simple. But there's a ceiling, the biggest machine on sale, and the price climbs faster than the power you get.
Cache or read replicas: what's the difference?
Both take reads off the primary. A cache answers the same repeated reads from memory, and its values can be old. A replica is a full copy that can answer any query, heavy reports too, but it trails a little behind. Neither one helps with writes.
A user saves their profile, then sees the old one. Why?
Most likely replication lag: the read went to a replica that hasn't replayed the latest write yet. For reads that must see what the user just wrote, read from the primary for a while, or wait until the replica has caught up.
Will more read replicas help with heavy writes?
No. Every write still lands on the one primary, and every replica has to replay it too. For heavy writes, write less (batch it, queue it), grow the primary, or split the data so several machines take the writes.
Partitioning vs sharding: what's the difference?
Partitioning splits a table into parts on the same machine: a query for one range reads only some of them, and old data can be dropped a whole part at a time. Sharding puts the data on different machines, so it really adds write capacity, but joins and transactions across machines get hard.
How do I pick a shard key?
A value that spreads the work evenly and that most queries carry, like customer_id. Pick wrong, a date for example, and the new writes all pile onto one shard, or every query has to ask every shard.
Why does id % N make adding a shard hard?
Change N and the remainder of almost every id changes with it, so most of the data has to move. In this lesson's code, going from 4 shards to 5 moves 8 in 10 customers; rendezvous hashing, a simple consistent hash, moves about 2 in 10.
Next lesson
CAP theoremLevel: Deep
Read replicas trail the primary; CAP is what each copy does when it can't reach the others.