System Design · Concept Library · Free article
Database Sharding: Splitting One Database Across Many Machines
Sharding splits one database across many machines, each owning a slice of the rows, so you can grow past the disk, write and memory limits of a single node. The key you slice on is close to a one-way door: it decides your hot shards, your joins and how you reshard.
Sharding splits one logical table across many independent databases so that no single machine has to hold all the data or take all the writes. You reach for it only when a single node has genuinely run out of road — disk, write-IOPS, memory, or connections — because a bigger box can buy you more reads and more storage but it can never make one server absorb more writes. The whole game is the shard key: the field you slice on decides which machine each row lives on. Pick it well and load spreads evenly across the cluster; pick it badly and every new write funnels onto one hot shard that melts while the others sit idle. The two default strategies are range (contiguous buckets — great for scans, but sequential keys stampede onto one shard) and hash (scatter by a hash function — even load, but range scans become a broadcast to every shard). And it is a one-way door: once your data is spread by a key, cross-shard joins, transactions, unique IDs, and changing the key later all become hard. Sharding is the most powerful and the most expensive move in the data tier — the last thing you reach for, and the thing you cannot easily take back.
One database node is on fire, and there is no bigger box
It is a Saturday night and a mega-creator drops a link to forty million followers at once. Hatch has survived spikes before — there is a CDN, a load balancer, read replicas, a Redis in front of the hot key. But this time the thing melting is the one piece none of those protect: the single Primary Postgres in US-East that owns every write. Its disk is 98% full with billions of link rows, its write IOPS are pinned, CPU sits at 100%, and link-creation latency has blown past 8,000 ms — one in three writes is simply timing out. The pager reads: "the primary is dropping 30% of creations and we cannot scale this box any further."
And that last clause is the whole problem. Every trick that saved Hatch before was a trick for reads. A read replica copies the data so more machines can serve reads — but every one of those copies still funnels its writes back to the one primary. A cache answers reads from memory — but a brand-new link has nothing to cache yet; it has to be written first. You can buy a bigger primary — more cores, more RAM, faster disks — and it will help right up until you have bought the biggest box the cloud sells, and the writes still all land on that one machine. There is a ceiling, and Hatch has hit it. The only move left is the one that changes the shape of the system: stop asking one machine to hold all the data and take all the writes, and split the data across many machines. That is sharding, and this page is about doing it without setting a different fire.
What sharding actually is (and three words people confuse)
Before the mechanics, clear up three words that get used interchangeably in hallways and get you in trouble in interviews: replication, partitioning, and sharding. They are not the same thing, and the difference is one sentence each. Replication keeps the same data on many machines — a full copy on each — so you survive a machine dying and can serve more reads. Partitioning splits different data into subsets so no one machine holds it all. And sharding is simply partitioning where those subsets live on different physical machines (a "shard" being one of those machines with its own slice). Replication is copies; sharding is slices. Real systems do both at once — you shard to spread the data, then replicate each shard so a dead node does not take its slice down with it.
| Term | What it splits or copies | What it buys you | What it does NOT do |
|---|---|---|---|
| Replication | The same data, copied to N machines | Read scaling + surviving a node death | Does not add write capacity — writes still hit the primary |
| Partitioning | Different rows into disjoint subsets | No one machine holds the whole dataset | Nothing, until the subsets live on separate machines |
| Sharding | Different rows onto different physical machines | Write + storage scaling — each shard takes only 1/N | Does not survive a shard dying — that needs replication too |
There is a second axis worth naming, because it is the one interviewers use to check you actually understand the word. Splitting a table can go two directions. Vertical partitioning slices by column — you pull the rarely-touched, bulky columns (a link’s full analytics blob) into their own table so the hot columns (short code, destination URL) stay small and cache-friendly. Horizontal partitioning slices by row — every shard has the same columns but only some of the rows (shard 0 holds these links, shard 1 holds those). Sharding is horizontal partitioning taken across machines. When this page says "shard," it always means the horizontal, by-row kind — because that is the one that breaks the single-machine ceiling on writes and storage.
Why you shard — the four walls a single node hits
You do not shard because it is impressive; you shard because a single machine has run out of exactly one of four things, and no bigger machine will fix it for long. Naming which wall you hit is the first thing a good engineer does, because the wall you hit changes the urgency and sometimes the cheaper alternative. Here are the four:
The four single-node limits that force a shard
- Storage / disk — the table is simply too big for one machine’s disk. Billions of link rows plus their indexes outgrow even a large volume, and you cannot add disk forever. This is the wall Hatch is staring at (98% full).
- Write throughput / IOPS — the limit sharding exists for. Reads you can scale with replicas; writes have nowhere to go but the one primary, and once it maxes out its write IOPS, only splitting the writes across more primaries helps. If your bottleneck is writes, sharding is often the only answer.
- Memory / working set — a database is fast when the rows it touches most (the "working set") fit in RAM. Once the hot data no longer fits, every query starts hitting disk and latency falls off a cliff. Postgres’ own guidance is that table partitioning starts to pay off once a table exceeds the machine’s physical memory.
- Connections — Postgres runs a whole OS process per connection (several MB of RAM each), so a few thousand connections cost gigabytes before a single query runs. Enough clients and you run out of connection headroom on one box — though this one often has a cheaper fix (a pooler like PgBouncer) before you reach for a shard.
Notice the through-line: a bigger box cannot fix writes. Scaling up (a beefier single machine) genuinely helps storage, memory, and connections for a while — but every write still passes through one machine, so the moment writes are your wall, vertical scaling has nothing left to give. That is the tell that you have reached real sharding territory and not just "buy more RAM." Feel it below — drag the load up and watch a single primary climb to its ceiling and melt, while a sharded cluster spreads the same load so each machine only ever carries its slice:
The interactive version of this example is available when JavaScript loads.
The shard key — a one-way door you walk through once
Once you have decided to split the data, exactly one question dominates every other: what do you slice on? The shard key is the field the system runs through some rule to decide which shard a row belongs to — link code, user id, tenant id, creation timestamp, whatever you choose. It sounds like a small technical detail. It is the single most consequential decision in the whole design, for two reasons that compound each other.
The first is that the shard key decides whether your load is even or lopsided. If the key spreads rows uniformly, every shard carries roughly 1/N of the data and 1/N of the traffic, and the cluster scales the way the diagram promised. If the key clumps — if lots of hot rows share a key value, or new rows all get adjacent keys — then one shard drowns while its siblings idle, and you have paid for a cluster that performs like a single overloaded machine. The second reason is worse: the shard key is a one-way door. Changing it later is not a config tweak; it means recomputing which shard every existing row belongs to and physically moving most of your data across the network while the system is live. Teams schedule that months in advance. So you want to get it right the first time, which means understanding the strategies before you pick.
How rows pick a shard — range, hash, and two more
There are four strategies you will actually reach for, and they line up on a spectrum from "keeps related rows together" to "spreads load most evenly." You only need the first two in real depth — range and hash — because they are the default fork every design starts from, and they are exactly the fork the Hatch incident turns on. Start there.
Range partitioning. Give each shard a contiguous range of the key: shard 0 owns link ids 1–1B, shard 1 owns 1B–2B, shard 2 owns 2B–3B, and so on. The appeal is obvious and real — a query for "all links created in this id range" or "everything from last Tuesday" hits one or two adjacent shards and streams the answer in order, because neighbours in the key are neighbours on disk. Range partitioning makes range scans cheap, which is why time-series and analytics stores love it. But look at what happens on Hatch’s workload: link ids are auto-incrementing, so every brand-new link gets the highest id, which means every single new write falls into the newest range — the last shard. That one shard takes 100% of the write traffic while shards 0 through 2 sit idle holding cold history. The distributed cluster has quietly collapsed back into a single overloaded machine. This is the trap the incident sprang: sequential keys turn range partitioning into a hot-shard funnel.
Hash partitioning. Instead of slicing the key directly, run it through a hash function first and slice that: shard = hash(key) % N. A hash scrambles order, so two ids that were adjacent (1,000,001 and 1,000,002) land on completely different shards. That is exactly what you want under Hatch’s stampede — new writes scatter uniformly across all four shards like a dealer flicking cards around a table, so each shard takes only its 1/N and the whole cluster shares the load. Hashing is the default when your access is key-at-a-time (look up this link, write this row) and you need even write distribution more than you need ordered scans. The price is the mirror image of range’s gift: because order is destroyed, a range scan ("all links from last Tuesday") can no longer live on one shard — it has to broadcast to every shard and merge the results, which gets expensive fast. Toggle the two below and watch a stream of sequential ids either funnel onto one shard or scatter evenly:
The interactive version of this example is available when JavaScript loads.
Two more strategies round out the toolkit for when the default fork is not enough. Directory (lookup-based) partitioning keeps a separate little table that maps each key (or each block of keys) to a shard, and every access consults it first. It is the most flexible of all — to move a hot user off a crowded shard you just edit one row in the directory, no rehashing — but that directory is an extra network hop on every request and a new thing that can bottleneck or fail, so it earns its place only when you genuinely need per-key control. Geo / entity partitioning routes by where or who: put European users’ rows on EU shards (data near its users, and a nod to data-residency law), or deliberately colocate everything belonging to one tenant on one shard so that the common "show me everything in this workspace" query stays on a single machine. Its gift is cheap within-entity joins and transactions; its risk is a hot region or hot tenant that lands entirely on one shard.
| Strategy | How a row picks a shard | Gift | Cost | Reach for it when |
|---|---|---|---|---|
| Range | Contiguous key buckets (ids 1–1B → shard 0) | Cheap ordered range scans | Sequential keys funnel onto one hot shard | Time-series / analytics with ordered scans and a non-monotonic key |
| Hash | hash(key) % N scatters the key | Even write distribution — no natural hotspot | Range scans become a broadcast to every shard | Key-at-a-time access needing even load (the default for Hatch) |
| Directory | A lookup table maps key → shard | Total flexibility — move a hot key by editing one row | An extra hop + a bottleneck/SPOF to run | You need explicit per-key placement or easy rebalancing |
| Geo / entity | Route by region or colocate a tenant | Data near users; cheap within-entity queries | Hot region / hot tenant risk | Multi-tenant or data-residency workloads |
Choosing a shard key for a real workload
Strategies are easy to list and hard to choose between under pressure, so here is the framework that collapses the choice down to a few questions. It falls straight out of the "spread vs togetherness" tension we just named: you are trying to find the key that keeps the queries you run most often on a single shard while still spreading load evenly enough that no shard melts.
The four questions that pick your shard key
- What is my dominant access pattern? If it is look up one row by id (a link click, a user profile), hash on that id — you get even spread and every read is a single-shard hit. If it is scan a contiguous range (a time-ordered feed, a report), lean range — but on a non-monotonic key.
- Is my key monotonic? Auto-increment ids and
created_attimestamps always grow, so range on a monotonic key is a hot-shard trap. If your natural key is sequential and you still want range scans, that tension is real — usually you hash, and accept that scans broadcast. - Do I need related rows together? If the app constantly asks "everything for this user / tenant / workspace," colocate by that entity so those queries stay on one shard and can even use local transactions. The cost you accept is a possible hot tenant.
- How high is my cardinality, and how skewed? A key with millions of roughly-equal values (link code) hashes beautifully. A low-cardinality or skewed key (country, status, a celebrity’s id) will pile rows onto a few shards no matter how you hash it — that is the hot-key problem, and it needs its own treatment.
Run a workload through those questions below — pick what the system mostly does and see which strategy fits and why, and where each one bites:
The interactive version of this example is available when JavaScript loads.
What you give up the moment you shard
Everything so far has been the good news: split the data, spread the load, break the single-machine ceiling. Now the bill. On one database, a whole category of operations is free — the engine can see every row, so joining two tables, running a transaction across several rows, or enforcing that an id is unique all just work. Sharding takes that away, because your rows now live on separate machines that have no idea the others exist. None of these become impossible; they become your job instead of the database’s. Knowing this list cold — and how you work around each one — is the difference between "I would shard it" and "I have actually run a sharded system."
Start with the one that bites first: a query that does not name the shard key. When you ask for a row by its shard key ("give me link abc123"), the system hashes the key, learns it lives on shard 2, and asks exactly one machine — fast and cheap. But ask a question that the shard key cannot answer ("give me every link created last Tuesday," when you sharded by link code) and there is no single shard that owns the answer. The only way to be sure you found them all is to ask every shard, wait for all of them, and merge the results — a pattern called scatter-gather. It is expensive for a reason people underestimate: your response is only as fast as the slowest shard that replies, so as you add shards, the odds that at least one is having a slow moment go up, and your tail latency quietly gets worse. Feel it below — flip between a key-lookup and a scatter-gather query and watch the cost:
The interactive version of this example is available when JavaScript loads.
The rest of the bill follows the same shape — things that were one-machine-easy are now many-machine-hard. Here is the list a senior engineer keeps in their head, with the honest workaround for each:
The five things sharding takes away — and how you get them back
- Cross-shard JOINs. Joining two tables that live on different shards cannot happen inside one database. You get it back by colocating (shard both tables on the same key so the join stays on one machine), by replicating a small reference table to every shard, or by doing the join in your application code — all more work than a plain SQL
JOIN. - Transactions across shards. A single-database transaction that flips two rows atomically ("move $10 from A to B") is gone if A and B sit on different shards. Restoring true atomicity needs a distributed transaction (two-phase commit) — a coordinator that asks every shard to prepare, then tells them all to commit — which is slow, locks rows while it waits, and has ugly failure modes if the coordinator dies mid-flight. The common real-world answer is to avoid needing it: design so a transaction stays on one shard.
- Unique ids. A single database hands out unique ids for free with
AUTO_INCREMENT. Across shards that breaks instantly — two shards would both mint id 1,000,001. You now need a coordination-free id scheme (a time-sortable 64-bit id that bakes in a machine or shard number). That whole arc — collisions, Snowflake-style ids — has its own home in the Short Codes & Unique IDs pattern; just know sharding is why you need it. - Referential integrity (foreign keys). A database enforces "every link must point to a real user" only within one machine. Across shards it cannot check a foreign key it cannot see, so the guarantee becomes your application’s job — plus a background clean-up job to catch the orphaned rows that slip through.
- Secondary indexes. An index on a non-shard-key column ("find links by owner") is either kept per shard (cheap to write, but a read must scatter-gather to search them all) or maintained as one global index split by term (fast reads, but a single write may have to touch many shards, so it lags). There is no free lunch — you pick which side pays.
The failure modes of a live cluster
A sharded cluster does not fail the way a single database does. It has its own signature failure — one you have already met in passing, and one that is the whole reason the next chapter exists. Name them, because in an interview "what goes wrong with sharding?" is where the senior points are hiding.
The hot shard. The most common failure of a sharded system is that your even split of the data turns out to be an uneven split of the load. Every shard can own the same number of rows and still one of them melts — because traffic does not spread as evenly as data does. One mega-viral link, one celebrity user, one giant tenant: that single key lives on exactly one shard, and no amount of adding shards helps, because the hot key does not split when you add machines. This is important enough — and general enough — that it has its own companion page, Hot Keys & Partition Skew, which covers both the general skew problem and the database-shard-specific moves. The one-line preview: you cannot spread a single hot key, so you replicate or cache it in front of its shard, dedicate a shard to a whale tenant, coalesce the identical reads, or split the key into sub-keys.
And then there is the failure that is not really a failure of running the cluster, but of growing it — and it is the one this whole chapter has been quietly walking you toward. You sized the cluster at four shards using hash(key) % 4. It fills up. So you add a fifth shard and switch the rule to hash(key) % 5. That one-character change is a catastrophe. Drag the shard count below and watch what happens to your existing data:
The interactive version of this example is available when JavaScript loads.
That is the sting. Because hash(key) % N ties every key’s home to the total number of shards, changing that number recomputes the destination of almost every key at once — going from 4 to 5 shards moves roughly 80% of your billions of rows to a new machine. All of it copies across the network simultaneously, the disks pin, the caches empty in one giant miss, and the cluster goes dark for hours. You did not add capacity gently; you detonated the whole layout to bolt on one node.
Measuring and operating a real cluster
Here is the part most write-ups skip entirely, and it is exactly the part that separates someone who has read about sharding from someone who has run it. A sharded cluster hides its problems in the average. Your dashboard says "database CPU: 40%" and everything looks calm — but that 40% is the mean across four shards, and it is perfectly consistent with one shard pinned at 95% and three coasting at 25%. The single most important rule of operating a cluster is: never look at an aggregate; always break every metric out per shard. The moment you chart per-shard, the hot shard that the average was hiding jumps off the screen.
What to watch, per shard
- Load, split read vs write — queries per second on each shard. The hot-shard tell is one shard’s QPS (and its p99) climbing while the others stay flat. If you only chart the total, you will never see it coming.
- Storage per shard — how full each machine’s disk is. Shards fill at different rates, and the fullest one sets your clock for the next (painful) resharding, not the average.
- Skew, on two axes — measure imbalance on both traffic and storage, because they diverge: a shard can hold few rows but serve the hottest key, or hold the most rows but be quiet. A simple health line ("no shard should exceed ~1.25× the median") turns skew into an alert instead of a surprise.
- Replication lag per shard — each shard is itself replicated, so each has its own lag. One slow replica means stale reads for just that slice of your users — invisible unless you watch it per shard.
- Cross-shard query rate — how often you are paying the scatter-gather tax. A creeping rise here means an access pattern is drifting away from your shard key, and it is an early warning that the key is going stale.
The other operational reality worth naming is how the cluster knows which shard owns a key — the routing tier — and how you move data when you must. Where the routing decision lives (in your app, or in a proxy like Vitess or ProxySQL, or inside the engine like Citus) is its own design choice with real trade-offs, so it gets a dedicated companion page: Application-Level Shard Routing. And when you do have to reshard, the modern way avoids the big-bang outage from the last section: tools like Vitess copy data to the new shards while the old ones keep serving live traffic, verify the copy matches, then flip routing over in a brief, near-instant cutover. The lesson to carry: resharding is a routine, tooled operation on a mature stack — not a heroic weekend migration — precisely because someone solved the "move only a sliver" problem.
The cost, and when NOT to shard
Now the honest accounting, because the most senior thing you can say about sharding is "not yet." Everything on this page is real power, and all of it is expensive: you go from one database to a fleet of them (more machines to pay for and patch), you give up the free joins/transactions/ids from the last few sections, you take on the operational weight of watching every shard, and — quietly — you add risk, because a distributed system has more moving parts and more ways to fail than the single box you started with. Sharding is the heaviest move in the data tier, which is exactly why it should be the last one. There is a whole ladder of cheaper fixes to climb first, and reaching for a shard before you have is the number-one mistake in a design interview.
The cheaper ladder — climb these before you shard
- Scale up (a bigger box). Boring, and it works for a long time. More RAM, faster disks, more cores buy you years of runway on storage, working set, and connections — and the engineering cost is a config change, not a re-architecture. Only writes are truly immune.
- Add read replicas. If your pain is reads, copies of the database serve them and take that load off the primary entirely — no sharding needed. This is the read replication move, and it solves a huge share of "the database is slow" problems.
- Cache the hot reads. Put a cache in front of the database so the popular reads never touch it at all. Often the single highest-leverage change you can make, and far cheaper than splitting the data.
- Pool your connections. If the wall you hit is connections, a pooler (PgBouncer) lets thousands of clients share a small set of real database connections — fixing the exact problem sharding would, for a fraction of the effort.
- Fix the schema first. Add the missing index, kill the N+1 query, archive cold rows to cheaper storage, or split a table by columns (vertical partitioning). A surprising number of "we need to shard" moments are really "we never added the right index."
How the real world shards
You almost never hand-roll sharding from scratch — you adopt a system that already does it, and knowing the landscape is half the interview. The tools split into two camps: databases that shard for you (you pick a shard key and they handle placement and rebalancing), and layers you bolt onto a database that does not. Here is the map:
| System | What it is | How you shard with it |
|---|---|---|
| Vitess | A sharding layer over MySQL (born at YouTube; runs Slack, GitHub, Shopify) | A proxy tier routes queries by shard key and does online resharding without downtime |
| Citus | An extension that turns Postgres into a distributed cluster | A coordinator node spreads rows across workers; you pick a distribution column |
| MongoDB | A document store with built-in sharding | Choose a shard key; a balancer auto-splits and moves chunks between shards |
| Cassandra / DynamoDB | Wide-column / key-value stores, sharded from the ground up | You cannot not shard — the partition key IS the shard key, chosen at design time |
And the stories worth stealing in an interview, because they show the trade-offs are real and not academic. Notion sharded its Postgres by workspace id into hundreds of logical shards spread across a few dozen machines — and when they later grew the machine count, they did it with almost no downtime precisely because their logical shard count never changed (the trick the next chapter reveals). Discord learned the hot-partition lesson the hard way: their message store keyed on channel-plus-time-window, and a single busy channel would turn one partition into a hotspot — the exact failure from earlier, at trillions-of-messages scale. Instagram bakes the shard number into every id it generates, so an id tells you which shard to look on without a lookup. Different companies, same handful of ideas you just learned.
Show me the code
Here is the shape of application-level hash routing in words you can turn into any language. The whole thing is smaller than people expect — the hard part was never the code, it was choosing the key and living with the consequences. The one rule: the router must compute the target shard before it opens a connection, so each request talks to exactly one shard.
- Hold a map from shard number to a database connection pool:
shards = [pool0, pool1, pool2, pool3]— each pool points at a separate database. - On every request, pick the shard from the shard key, never from anything else:
index = hash(shardKey) % shards.length(use a stable hash likexxhashormd5, not the language’s built-in string hash, which can change between versions). - Route the query to that one pool:
pool = shards[index]; pool.query(sql, params). One request, one shard, one connection — no fan-out. - For a write, the shard key must be present before you insert (you cannot route a row you cannot place), which is why sharded systems generate the id — and bake the shard into it — up front.
- For a query that lacks the shard key, make the scatter-gather explicit and bounded:
Promise.all(shards.map(p => p.query(sql)))then merge — and treat every place you write this as a smell to design away. - Keep the shard map in config, not code, and change it through a controlled rollout — because the day you change
shards.lengthis the day the resharding storm from earlier is waiting for you.
Pitfalls that bite in production
- Sharding too early. The number-one interview mistake and a real production one: you take on all the cost (lost joins, lost transactions, operational weight) before you have exhausted the cheaper ladder. If a bigger box or a read replica still buys you a year, take the year.
- A monotonic shard key with range partitioning. Auto-increment ids and
created_attimestamps always grow, so range-partitioning them funnels every new write onto the newest shard — the hot-shard funnel you can see coming from a mile away. - Assuming even data means even load. Every shard can own the same number of rows and one still melts, because one key went viral. Balance the traffic, not just the row count.
hash(key) % Nas your forever plan. It works beautifully until the day you add a shard, when it re-homes almost everything at once. Know that this trap exists before you build on top of it.- Choosing a key you cannot query by. If your dominant query cannot name the shard key, every one of those queries is a scatter-gather. The key must match how you actually read the data, not just how it distributes.
- Forgetting each shard needs its own replicas and backups. A shard is a whole database; sharding multiplies your operational surface (four shards, four things to replicate, monitor, back up, and patch), it does not divide it.
- Charting cluster averages. An aggregate dashboard hides the one hot shard that is actually on fire. Break every metric out per shard or you will be blind to the exact failure sharding is prone to.
Best practices
- Exhaust the cheaper ladder first — scale up, read replicas, caching, connection pooling, indexing — and shard only when a specific limit is about to break and nothing cheaper is left.
- Choose the shard key from your dominant access pattern, so the queries you run most stay on a single shard. Default to hashing a high-cardinality key for even writes; reach for range only on a non-monotonic key when ordered scans dominate.
- Design so transactions and joins stay within one shard — colocate the rows that are read and written together (a user’s data, a tenant’s data) so you rarely pay the cross-shard tax.
- Generate ids that encode their shard so a row can be routed without a lookup, and never rely on per-shard
AUTO_INCREMENT. - Replicate every shard for availability — sharding scales writes, replication survives a node death; production needs both.
- Instrument per shard — load (read/write), storage, skew on both axes, replication lag, and cross-shard query rate — and alert when any one shard drifts past ~1.25× the median.
- Keep the shard map in config and rehearse resharding with a tool that moves data online, so growing the cluster is a routine operation and not a heroic outage.
The interview deck — intern to principal
- What is sharding, and why do you need it? (intern)
- Sharding splits one logical table across many independent databases so no single machine holds all the data or takes all the writes. You need it when one node runs out of disk, write-IOPS, memory, or connections — it is the only tool that scales writes and storage, because replicas and caches only scale reads.
- Replication vs partitioning vs sharding? (intern → SDE2)
- Replication copies the same data to many machines (read scaling + HA). Partitioning splits different data into subsets. Sharding is partitioning across separate physical machines. Real systems do both: shard to spread the data, then replicate each shard so a dead node does not take its slice down.
- How would you choose a shard key? (SDE2)
- From the dominant access pattern. Hash a high-cardinality key when access is key-at-a-time and I need even writes (a link shortener). Range on a non-monotonic key when ordered scans dominate. Above all, pick the key that keeps my most common query on a single shard — and never range-partition a monotonic key, or every new write funnels onto one shard.
- What do you give up when you shard? (senior)
- Cross-shard joins, transactions across shards (now a slow two-phase commit), free unique ids, cross-shard foreign keys, and cheap secondary indexes — plus any query that does not name the shard key becomes a scatter-gather whose latency is set by the slowest shard. The fix for most of it is to colocate related rows so operations stay on one shard.
- A shard is hot even though every shard owns the same number of rows — why, and what do you do? (senior → staff)
- Even data does not mean even load: one viral key lives on one shard and no amount of adding shards splits it. You cannot spread a single hot key, so you replicate it, cache it in front of its shard, or split it into sub-keys. And you only see it because you chart load per shard, not as a cluster average.
- You have 4 shards on hash % 4 and need to add a fifth. What happens, and how would you avoid the pain? (staff)
- Naive
hash(key) % 5re-homes ~80% of your keys at once — a data-movement storm that takes you offline. Adding one node to four should only move ~20%. The fix is a scheme that ties a key to a position on a ring rather than to the node count, so adding a node moves only its slice — that is consistent hashing, and it is the next chapter. - When would you NOT shard? (principal)
- Almost always, at first. If the pain is reads → replicas or caching; if it is connections → a pooler; if it is a slow query → an index. Scale up while it still buys runway. Shard only when a specific limit — often a soft one like VACUUM strain or txid wraparound, not raw hardware — is about to break and every cheaper rung is exhausted. "Not yet" is the senior answer.
The one thing to carry
The whole chapter collapses to a single sentence: when one machine can no longer hold the data or take the writes, you split the data across many — and the key you split on decides whether the cluster scales or melts. A bigger box buys you reads and storage but never more write capacity, so sharding is the one move that lets a fleet share the write load. Hash the key for even distribution, range it for ordered scans (never on a monotonic key), keep the queries you run most on a single shard, and remember that the shard key is a one-way door: joins, transactions, unique ids, and changing your mind later all get harder the moment you walk through it.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.