Sharding and partitioning
Split one large data set across machines: choose a strategy and a shard key, handle hot spots and cross-shard work, and know when not to shard at all.
The problem
A marketplace runs on one PostgreSQL leader with three read replicas. Reads are fine, because the replicas absorb them. Writes are not: every order, payment and event still lands on the single leader. The orders table reaches 2 TB, an index build takes most of a day, restoring a backup takes hours, and the leader is already on the largest machine the cloud provider sells. Replication cannot help, because every replica has to apply every write too.
The team works through the cheaper options first. They tune queries and add a cache. They archive orders older than two years. They move the analytics events table to its own database server, which buys a year. Eventually one table on one machine is still too big and too busy, and the only move left is to split its rows across several machines. That is sharding. The idea is old (large sites such as Flickr and Facebook sharded MySQL by hand in the mid-2000s), and it is still the main way to scale writes.
Vertical and horizontal partitioning
Two different splits share the word “partitioning”.
- Vertical partitioning splits by column or by table. Moving the
eventstable to its own server is vertical, and so is moving a largedescriptioncolumn out of a hot table. It is simple, and it runs out when a single table is the problem. - Horizontal partitioning splits by row. Some rows live in one place and the rest in another. When the pieces are on different machines, each piece is a shard.
Partitioning inside one server, such as PostgreSQL’s declarative table partitioning, helps with maintenance and with dropping old data. It does not add write capacity. Sharding does, and each shard is normally replicated for availability.
Three ways to map a row to a shard
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Range | Each shard owns a contiguous range of the key | Range scans touch one or two shards | Sequential keys send every new write to the last shard |
| Hash | A hash of the key picks the shard | Keys spread evenly | Range scans must ask every shard |
| Directory | A lookup table maps each key, often a tenant, to a shard | Any key can be moved or isolated | The directory is one more critical system to keep fast and available |
HBase, Bigtable, Spanner and CockroachDB use range partitioning, with ranges that split automatically as they grow. Cassandra and DynamoDB hash the partition key. Whichever you choose, do not compute hash(key) mod N with N as the number of machines. Consistent hashing explains why, and what to use instead.
Many stores combine the two ideas with a compound key. In Cassandra and DynamoDB the first part of the key is hashed to choose the partition and the second part sorts rows inside it. A key of (user_id, created_at) spreads users evenly and still gives a cheap range scan over one user’s history.
Choosing a shard key
The shard key decides which queries are cheap, so choose it from the queries, not from the schema. A good key has four properties:
- It is in almost every query. A query that includes the key goes to one shard. A query that does not must go to all of them.
- It keeps related rows together. Rows that are read or changed in one transaction should share a key, so the transaction stays on one shard.
- It has many values and no dominant one. Millions of user ids spread well. A
countrycolumn with 200 values, one of which holds 40% of the rows, does not. - It does not change. Changing a row’s key means moving the row to another shard.
For a consumer app the key is usually the user id. For a business product it is usually the tenant id, which keeps each customer’s data together and makes one very large customer a risk.
Hot spots
A hot shard receives far more than its share of the load. There are three usual causes.
- A sequential key with range partitioning. Timestamps and auto-increment ids put every insert on the newest range. Hash the key, or lead with another column such as a device id.
- One huge key. A celebrity account, or a tenant ten times the size of the next. Hashing does not help, since one key is still on one shard. Move the tenant to a dedicated shard through a directory, or split the key by adding a bucket suffix (
tenant42#0totenant42#9) and accept that reads must now query ten buckets. - One busy moment. Everyone writes to today’s partition. Add a second component to the key so that one day is spread across shards.
Queries and transactions that cross shards
A query without the shard key becomes scatter-gather: the router sends it to every shard and merges the results. It is as slow as the slowest shard, it fails when any shard fails unless you accept partial results, and its cost grows with the shard count. Sorting, pagination and aggregation have to be redone in the router.
Joins across shards mostly disappear. You denormalise so that the data a query needs sits on one shard, or you join in the application.
A transaction that touches two shards needs two-phase commit or a saga. Both are slower and more fragile than a local transaction, which is the best argument for the second property above.
Secondary indexes
Finding a user by email when the shard key is the user id needs an index, and there are two kinds.
- A local index lives on each shard and covers only that shard’s rows. Writes stay cheap, because the row and its index entry change together on one machine. Reads by the indexed column are scatter-gather.
- A global index is a separate structure, partitioned by the indexed column. A read goes to one index partition and then to one shard. A write now touches two places, so most systems update the index asynchronously and it can be briefly stale.
DynamoDB offers both. Its local secondary indexes share the table’s partition key and can be read with strong consistency. Its global secondary indexes are always eventually consistent.
Rebalancing and resharding
Shards fill unevenly and clusters grow, so data has to move. Three approaches keep that manageable.
- Many logical shards on few machines. Create, say, 4,096 logical shards on day one and map them onto 8 servers. Growing means moving whole logical shards to a new server and updating the map, never re-hashing rows. Instagram has described running several thousand logical shards on far fewer PostgreSQL servers.
- Automatic range splitting. The database splits a range that has grown too large and moves ranges between nodes itself.
- Consistent hashing, where a new node takes a small slice from each of its neighbours.
Whichever you use, moving data on a live system follows the same sequence.
Step 1 of 8
Shard A holds users 0 to 999 and is running out of room. The routing table sends every query for those users to A.
Read the steps as text
- Shard A holds users 0 to 999 and is running out of room. The routing table sends every query for those users to A.
- You add an empty Shard B and plan to move users 500 to 999 onto it. The routing table does not change yet, so B receives no traffic and nothing is at risk.
- Backfill. A copy job reads a consistent snapshot of users 500 to 999 from A and writes it to B. Shard A keeps serving reads and writes throughout. The copy is throttled so it does not starve live traffic.
- Writes that reach A during the copy would be missed. So a change stream tails the replication log on A and replays every change for the moving users onto B, until B is less than a second behind.
- Verify before switching. Compare row counts and checksums between A and B for the moved range. Optionally send a copy of live reads to B and compare the answers.
- Cutover. Writes for users 500 to 999 are paused for a few seconds, B applies the last changes, and then the routing table is updated. That short pause is the only effect users can notice.
- The router now sends users 500 to 999 to B. The old rows stay on A for a while, with changes flowing back from B to A, so that you can switch back if something is wrong.
- Once you trust the new layout, delete the moved rows from A. Every online data migration has this shape: copy, catch up, verify, switch, clean up.
Why to delay sharding
Sharding takes away things you rely on: joins, multi-row transactions, unique constraints across the whole table, and simple schema changes, which now run once per shard. Every shard needs its own replicas, backups and failover. The shard key is very hard to change later.
So exhaust the alternatives first: indexes and query fixes, caching, read replicas, a bigger machine, archiving cold data, and moving whole tables to their own servers. Then check the numbers.
Enter your data size, growth rate and peak write load, then double each one in turn to see which of them drives the shard count.
Choose sharding when write volume or data size has outgrown the largest practical machine, or when one node’s failure or maintenance affects too many users at once. Do not choose it to fix slow reads, or because the data might be large one day. If you know from the start that the data is huge and accessed by key, a store that shards itself (DynamoDB, Cassandra, or a distributed SQL database such as Spanner or CockroachDB) is usually a better choice than sharding a relational database by hand.
In the interview
Do not open with sharding. Estimate the data size and write rate first, and say plainly whether one machine with replicas would cope. If it will not, name the shard key and justify it from the main queries: “every request carries the user id, so I shard by user id and each user’s data stays together”. Then cover the parts that hurt. Say which query lacks the key and how you will serve it, where a hot key could appear and what you would do about it, and how you would add capacity later without downtime.
Key takeaways
- Replication scales reads. Sharding is how you scale writes and data size beyond one machine, and each shard is still replicated.
- Range partitioning keeps range scans cheap but concentrates sequential writes. Hash partitioning spreads writes but turns range scans into queries on every shard.
- Choose the shard key from the queries: it should appear in almost all of them, keep related rows together, have many evenly used values, and never change.
- Hashing cannot split a single hot key. Isolate it on its own shard or split it into buckets and pay with fan-out reads.
- A local index makes writes cheap and index reads scatter. A global index does the opposite and is usually updated asynchronously.
- Map keys to many logical shards so that growing means moving whole shards and updating a map.
- Sharding costs you joins, cross-row transactions and simple operations. Exhaust the cheaper options first.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
Vertical versus horizontal partitioning
Vertical splits by column or table, for example moving one table to its own server. Horizontal splits by row. Horizontal pieces on different machines are shards.
Range versus hash partitioning: the trade-off in one sentence each
Range keeps neighbouring keys together, so range scans are cheap but sequential keys create a hot shard. Hash spreads keys evenly, so writes balance but range scans must ask every shard.
Four properties of a good shard key
It appears in almost every query, keeps rows that change together on one shard, has many values with no dominant one, and never changes.
Local versus global secondary index
Local: one index per shard, cheap writes, reads by the indexed column go to every shard. Global: partitioned by the indexed column, single-partition reads, but writes touch two places and are usually asynchronous.
What does a scatter-gather query cost?
It is as slow as the slowest shard, it is exposed to the failure of any shard, and its cost grows with the number of shards. Sorting and pagination must be redone when merging.
The steps of moving data between shards on a live system
Copy a snapshot, replay ongoing changes from the log until the copy has caught up, verify, pause writes briefly and switch routing, keep a way back, then clean up.
Interview questions on this
- You need to shard a multi-tenant orders table. How do you choose the shard key, and what happens to queries that do not include it?
- One of your 16 shards is at 90% CPU while the others sit at 20%. How do you find the cause and fix it?
- Your 8 shards are nearly full. How do you get to 16 without downtime?