TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท scaling ยท distributed systems

Sharding

Splitting one large dataset across several databases by a shard key, so storage and load scale beyond one machine. The shard key decides which queries stay fast and where hotspots appear.

10 min4 animations

๐Ÿ–จ๏ธ Cheat sheet

Volumes

The phone book got too thick to bind, so it's split into volumes: Aโ€“H, Iโ€“P, Qโ€“Z. To find or add someone, a guide tells you which volume, and you only open that one. Different people can use different volumes at the same time.

Partitioning by key

Replicas copy all the data, which scales reads but not data size or write volume. Sharding (horizontal partitioning) splits the rows across independent databases. A shard key decides where each row lives:

  • Range: key ranges per shard. Range scans are efficient; uneven ranges can hotspot.
  • Hash: hash(key) decides the shard. Even spread; range scans hit every shard. Consistent hashing limits data movement when shards are added.
  • Directory: a lookup table maps keys to shards, flexible but one more thing to keep available.

A router (in the app, a proxy like Vitess, or the database itself, as in MongoDB or Citus) sends each query to the right shard.

One phone book, several volumes3 steps
Volume Aโ€“H0123Volume Iโ€“P0123Volume Qโ€“Z0123๐Ÿง’Reader๐ŸงญVolume guide
Press play and watch it happen!

The busy volume

If you split by month instead, everyone writes in this month's volume while the others gather dust. Scattering entries by a scrambled customer number shares the work evenly.

Choosing the shard key

A good shard key has high cardinality, spreads writes evenly, and matches your most common queries. Bad keys create hotspots: monotonically increasing ids or timestamps send every new write to one shard, and a celebrity user can overload theirs. Changing the key later means moving all the data, so choose carefully.

The volume everyone wants2 steps
๐Ÿ‘ฅReaders๐ŸงญVolume guide๐Ÿ“•January volume๐Ÿ“—February volume๐Ÿ“˜March volume
Press play and watch it happen!

Questions about everyone

"Everyone who lives in Leeds?" isn't sorted by surname, so you open every volume and combine the answers. And changing two people in different volumes, all or nothing, needs careful coordination.

The costs of splitting

  • Queries without the shard key scatter-gather to every shard: latency is set by the slowest shard, and every shard does work for one query.
  • Joins and transactions across shards need two-phase commit or sagas; foreign keys can't span shards.
  • Rebalancing when adding shards moves data while the system is live (see the failure list below).
  • Operations (backups, schema changes) multiply by the shard count.

So shard late: indexes, caching, read replicas and a bigger machine go a long way first. In multi-tenant SaaS, sharding by tenant_id keeps each customer's data, and queries, on one shard.

Questions across volumes2 steps
๐Ÿง’Reader๐ŸงญVolume guide๐Ÿ“•Volume 1๐Ÿ“—Volume 2๐Ÿ“˜Volume 3
Press play and watch it happen!

When a volume goes missing

A few things can go wrong. One volume is borrowed by a thousand people at once, say the one holding a famous name, and the queue for it grows while the other volumes sit idle. Worst of all, if the book was split the wrong way, re-splitting it means copying every page.

Or one volume goes missing: only people who need names in it are stuck, and everyone else carries on. The fix is a spare copy kept in another building.

And when the library moves pages between volumes, the guide's notes can be out of date, so readers get sent to the wrong volume for a while.

What can go wrong

  • A hot shard (celebrity key). One shard saturates while others idle: its CPU, queue depth or p99 latency sits far above its siblings. Fix: a better shard key, splitting the hot range, or caching and read replicas for hot reads (see Choosing the shard key above).
  • One shard down (partial outage). Requests for that shard's keys fail while the rest succeed, so error rates look like a fixed percentage of users, and anything scatter-gathering across all shards fails or returns partial data. Fix: run each shard as a primary with replication and automatic failover; the router must then learn the new primary. Asynchronous replication can lose the newest writes on failover.
  • Cross-shard queries and transactions. A transaction touching two shards has no single-database atomicity: a crash between the two commits can leave one applied. Symptoms are slow tail latency and half-applied updates. Fix: keep related rows together, use two-phase commit or sagas with idempotent steps, and avoid cross-shard joins on hot paths (see The costs of splitting above).
  • Resharding while writes continue. Rows are copied to a new shard while the old one still takes writes, so changes made mid-copy must be replayed; for a while a key may live in both places, and a router with stale routing sends reads or writes to the old one (lost or stale data, duplicate rows). Fix: copy, replay changes, verify, then switch routing atomically and drop the old copy later; use consistent hashing or many small virtual shards so only a fraction of keys move.
  • A bad shard key. Changing it means a long online migration that rewrites and moves all the data (MongoDB 5.0+ can change a collection's shard key online with reshardCollection, but it still copies all the data). You'd see permanent hotspots or most queries scatter-gathering. Fix: model your top queries before choosing (see Choosing the shard key above).
ChoiceYou gainYou pay
Hash key vs range keyHash: even spread, no hot tailRange scans hit every shard; range keeps scans on few shards but risks hotspots
More shards vs fewer shardsMore: smaller units, more headroom, smaller failuresMore machines to run, more scatter-gather fan-out, more rebalancing and operations
Routing in the application vs a proxyApp: one fewer hop, no extra serviceEvery client must know the shard map and be updated; a proxy centralises routing and failover but adds a hop and a component to keep available
Synchronous vs asynchronous shard replicasSync: no acknowledged writes lost on failover (if the promoted replica was in sync)Slower writes; async is faster but can lose recent writes
One volume goes missing4 steps
๐Ÿ‘ฅReaders๐ŸงญVolume guide๐Ÿ“•Volume A-H๐Ÿ“—Volume I-P๐Ÿ“˜Volume Q-Z
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿ”—Design a URL shortenerShort codes for long links, and billions of redirects.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Sharding, told the same way as the story.
  1. To find one person, how many volumes do you open?
  2. You split the book by month. What goes wrong?
  3. What does "everyone who lives in Leeds?" cost when the book is split by surname?
  4. The I-P volume goes missing and there is no spare copy. What happens to readers?
Answer every question to check.Passing marks Sharding as done.
Got the hang of Sharding? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ•ธ๏ธ Distributed systems from zeroStep 4 of 7

โ† Previous on the pathโš–๏ธ CAP theoremNext on the path โ†’โญ• Consistent hashing

๐Ÿ—๏ธ Storing data at scaleStep 6 of 7

โ† Previous on the path๐Ÿ“š Replication and read replicasNext on the path โ†’๐Ÿ—„๏ธ NoSQL data models

๐Ÿ‘‰ Read next

  • ๐Ÿ“šReplication and read replicasA head office keeps the master ledger and a diary of changes that copy rooms replay, sometimes a little behind.
  • ๐Ÿ“ŒAmazon DynamoDBA hall of pinboards where each card goes on the board its name picks, so finding one name is quick.
  • โญ•Consistent hashingPlates around a round table: when someone sits down or leaves, only their neighbours' plates change hands.
  • ๐Ÿ—„๏ธNoSQL data modelsSwapping one big ruled ledger for storage furniture built for each job: pegs, filing cabinets, card catalogues.
  • ๐ŸซRedis ClusterA school office with 16,384 numbered pigeonholes shared out among the staff, picked by a fixed sum on each name.