Database sharding explained: from one box to hot shards
The order engineers reach for fixes when a database hits its limit, and what each one breaks: indexes, a bigger machine, caching, replicas, then sharding, with shard keys, routing, hot shards, rebalancing and failover.
14:05 video12 min read
- 2 architecture diagrams
- 4 sequence flows
- 2 data models
- 2 interviewer follow-ups
- 3 self-checks
2 of 3
database servers idle while the site was down
~100
reads for every booking written in the example
75%
of keys move when hash-mod-N goes from 3 shards to 4
16,384
fixed hash slots in Redis Cluster
On this page14 sectionsHLDLLDSenior depth
- The order to scale a database: queries, a bigger machine, cache, replicas, then shard.
- What makes a good shard key, and why it is the hardest decision to reverse.
- Why spreading data evenly does not spread traffic evenly (hot shards).
- How rebalancing and failover work while the system stays live.
Chapters
- 0:00Three servers, two idle, site down (opens the video at this moment on YouTube)
- 0:54One box (opens the video at this moment on YouTube)
- 1:59Stop asking the database (opens the video at this moment on YouTube)
- 3:05Read replicas and replication lag (opens the video at this moment on YouTube)
- 4:18The write wall (opens the video at this moment on YouTube)
- 5:16Sharding and shard keys (opens the video at this moment on YouTube)
- 7:03Routing, scatter-gather and cross-shard purchases (opens the video at this moment on YouTube)
- 8:33The hot shard (opens the video at this moment on YouTube)
- 10:00Rebalancing live data (opens the video at this moment on YouTube)
- 11:25When a shard dies (opens the video at this moment on YouTube)
- 12:52Where state lives (opens the video at this moment on YouTube)
At ten o'clock on a Friday morning, a ticketing app had three database servers. Two of them were almost idle, and the site was down. The servers were not too small. The problem was a decision made two years earlier about where the data should live. The app, which the video calls Encore, is a fictional example; the failure is a real and common one.
A single database is the simplest system you will ever run: one place for every query, easy transactions, joins and backups. Then the app grows, and the database CPU sits near 100% all day. Engineers reach for fixes in a very specific order.
The first two fixes are boring and work surprisingly well. Read the slow query log: one query was scanning the whole bookings table to find a single user's tickets because nobody had added an index on the user ID. One index later, CPU drops. The second is a bigger machine: more cores, memory and faster disks. This is vertical scaling, and it is underrated because your code does not change. But each size costs more than the last, and the biggest machine money can buy is still one machine.
The cheapest query is the one that never reaches the database. In the example, for every booking written about a hundred reads arrive, and most are the same read: thousands of people refreshing the same seat map. An in-memory cache such as Redis keeps recent answers, and on a hit the database never hears about the request.
A cache can go stale. The moment someone books a seat, the cached seat map is out of date, so entries either expire after a few seconds or are cleared on every write. For a short window, people see seats that are already taken and find out at checkout. That is why the purchase itself always goes to the database: a cache can show you a seat, but only the database can sell it to you. More on this in the caching lesson.
If one machine cannot answer every read, give reads more machines. The database becomes a primary and replicas: the primary takes every write and streams each change to the replicas, which apply it in the same order. Any read that misses the cache can go to any copy.
The stream takes time, usually milliseconds, sometimes seconds under load. That creates the first version of the data that is not the truth everywhere at once.
The usual fix is read your writes: for a short window after a user writes something, send that user's reads to the primary. Everyone else can live with a copy that is a second old; the person who just paid cannot.
Replicas copy writes; they do not share them. Every write still goes through the primary, and every replica has to apply every write too. Replicas multiply read capacity, but write capacity stays exactly where it started: one machine, one write path.
At scale the primary CPU pins, writes queue behind each other, and replicas fall behind because they are replaying a fire hose. The data keeps growing too. Once the table is past several terabytes, a backup takes hours, a restore takes longer, and building a new index can take most of a day. Every fix so far kept one assumption alive: all the data lives on one machine. Now that assumption has to go.
Sharding means no single machine holds all the data. Instead of copying the table you cut it: each piece is a shard, and each shard is a complete database holding only some of the rows. The rule that decides which row goes where is the shard key, and choosing it is the most important decision in the design.
| Shard key | Result | Problem |
|---|---|---|
| First letter of the name | Easy to picture | Lopsided: far more names start with S or M than with Q or X |
| Booking date | Storage splits across shards | Every new booking hits the newest shard while old shards sit idle |
| Hash of the user ID | Load spreads evenly; one user's data stays together | Range questions such as "all bookings last Tuesday" must ask every shard |
A good shard key does two jobs: it spreads load evenly, and it keeps the data a request needs in one place. It is also the hardest decision to change later. Here, bookings are sharded by a hash of the user ID, so everything one user needs lives on one shard, while seats are sharded by show ID, because a seat belongs to a show.
booking_iduuid
PKuser_idbigint
the shard key: one user's bookings live together
SHARD KEYshow_idbigint
INDEXseatssmallint
created_attimestamptz
Spreads evenly; "all bookings last Tuesday" must ask every shard.
show_idbigint
the shard key: every seat for a show lives together
PKSHARD KEYseat_idtext
PKstatussmallint
free, held, sold
held_untiltimestamptz
NULL
Keeps a seat map in one place, and creates the hot shard described below.
Once the data is split, every request needs directions. A router hashes the user ID, looks the result up in a shard map, and forwards the query to the right shard. The shard map is the most important small piece of data in the system, and every router has to agree on it: if two routers disagree about where a user lives, one of them writes to the wrong place.
Even buying a ticket crosses shards. The seat belongs to the show and the booking belongs to the user, so one purchase touches two machines and no single database transaction can cover both. The example holds the seat first, writes the booking second, and releases the hold if the booking fails. Queries that were free on one database now have a price.
Spreading the data evenly is not the same as spreading the traffic evenly. The example's shards are balanced, about a third of the rows each, with CPU around 30% everywhere. Then the biggest tour of the year goes on sale: two million fans, one show. Bookings spread out because they are sharded by user, but every fan needs a seat, and every seat for that show lives on one shard.
This is a hot partition. More shards will not help, because the hot key still lives on exactly one of them. You deal with the key itself, and all three of these must be in place before the sale starts:
- Split the key. Divide the show's seats into sections, each with its own key, so the floor and the balcony can live on different shards.
- Cache the read. Serve the seat map from the cache and touch the database only when someone tries to hold a seat.
- Add a waiting room. Let requests arrive at a pace the shard can take.
You find hot keys by knowing your traffic, not by watching a dashboard turn red.
Adding a shard takes minutes. Moving data onto it is the hard part. If rows were placed with a simple rule, hash the key and take the remainder when dividing by the number of shards, then changing three shards into four changes the answer for most keys: with a uniform hash, about three out of every four rows now belong somewhere else.
The common fix is an extra layer. Split the data into many small partitions up front, say a thousand, and map those onto machines. Adding a fourth shard means handing it a quarter of the partitions; every other row stays put. Redis Cluster is a real example of the idea: it divides its keyspace into 16,384 fixed hash slots and moves slots between nodes.
Even then the move happens while people are still writing, so it follows a careful sequence:
At every step there is a chance to lose a write or apply one twice, which is why teams rehearse rebalancing, and why a large database is usually moving data somewhere almost all the time.
Every machine you add is another machine that can fail. With one database, a dead server is a rare disaster; with a hundred machines, it is a weekly event you plan for. So each shard gets the protection the original database had: its own primary and its own replicas. Sharding splits the data; replication protects each piece.
Two traps hide here. If replication was asynchronous, the last few writes the old primary accepted may never have reached the replica, and those writes are gone. The fix is to wait for at least one replica to confirm each write before telling the user it worked: safer, and every write gets a little slower. And if the old primary was only slow, it can wake up still believing it is in charge. Two primaries accepting writes for the same data is split brain, so the cluster fences the old one off before the new one takes a single write. Notice what never happened: the other shards stayed up the whole time. When one database fails, everyone is down; when one shard fails, only the users on that shard are.
One database gives you a simplicity you never get back. A sharded database gives you a ceiling that keeps rising, and you pay for it in operations for as long as it runs. So: fix the queries first, cache what repeats, replicate for reads, and shard only when the writes or the data genuinely will not fit on one machine.
Interviewer follow-upL6Your chat app shards messages by user ID, and a group chat has a million members. What breaks, and what do you change?How to answer
Messages are read by conversation, not by user, so a per-user key scatters one conversation across every shard and makes each read a scatter-gather. Shard by conversation ID so a conversation's messages live together, and watch for the new hot spot: a very large or very active conversation concentrates traffic on one shard. Mitigate with sub-keys (conversation plus a time bucket), caching recent messages, and fan-out designs for the largest groups.
Interviewer follow-upL6You need to query bookings by show, but they are sharded by user. How?How to answer
A query on a non-shard-key column must ask every shard. Options: scatter-gather and accept the cost for rare queries, or maintain a secondary index sharded by show ID that maps shows to booking IDs, updated asynchronously (so it can lag). Be explicit that a global secondary index trades extra write work and eventual consistency for fast lookups.
QuestionWhy do read replicas not fix a write bottleneck?Reveal answer
Every write still goes through the primary, and every replica must also apply every write. Replicas add read capacity but leave write capacity exactly where it was.
QuestionShards are perfectly balanced in data, yet one is overloaded. What happened, and what do you do?Reveal answer
Traffic is concentrated on a hot key (for example every seat for one show lives on one shard). Fix the key rather than adding shards: split it into finer keys, cache the hot reads, and shape arrivals with a waiting room.
QuestionWhy does changing from 3 to 4 shards with hash-mod-N cause so much data movement, and what avoids it?Reveal answer
The remainder changes for about three quarters of the keys, so most rows move. Use many small partitions mapped to shards, or consistent hashing, so adding a shard moves only a fraction of the partitions.
The replication and sharding lesson covers the strategies in depth, and the consistent hashing lab lets you watch keys move when a node is added. For what a stale cache and replica lag do to correctness, see consistency and availability.
- Martin Kleppmann, Designing Data-Intensive Applications, chapter 6 (Partitioning): shard keys, hot spots and rebalancing.
- MongoDB documentation, Hashed Sharding (opens in a new tab): the trade-off between even distribution and range queries.
- Redis documentation, Redis cluster specification (opens in a new tab): 16,384 hash slots and moving slots between nodes.
Spot a mistake, or have a question?
Accuracy matters here. Tell me what looks wrong or unclear and I will fix it and credit you.