All posts
System Design Mastermind · F06
  • System design
  • Interview prep
  • Replication
  • Sharding

Replication and sharding: copying and splitting your data

Foundations F06. What to say when one database machine isn't enough: leader and followers, synchronous vs asynchronous replication, replication lag and read-your-writes, failover without split brain, multi-leader and leaderless quorums, range vs hash shard keys, consistent hashing with virtual nodes and fixed slots, and hot keys and cross-shard queries. Each idea is told as a story you'll remember, with a lab that sizes shards and shows what moves when you add a machine.

22 Oct 2026 · 25 min read · interactive

Share

Start here

One database machine eventually runs out of something: it can't serve all the reads, it can't take all the writes, it can't hold all the data, or it simply dies and takes the app with it. There are two answers, and every scaled design uses both. Replication keeps copies of the same data on several machines: more readers, and a spare when one fails. Sharding (also called partitioning) splits the data into pieces that live on different machines: more writers and more space.

This page covers eight ideas: leader and followers, waiting for the copy (synchronous vs asynchronous), replication lag and reading your own writes, failover without two leaders, multi-leader and leaderless replication, choosing a shard key (range vs hash), rebalancing (consistent hashing, virtual nodes, fixed slots), and the bills sharding sends (hot keys and cross-shard queries). The previous page covered one database on one machine; what replicas agree on (CAP and quorums in depth) is the page after next.

The one story for this page

IPL final night on a fantasy-cricket app

Picture a fantasy-cricket app on the night of the IPL final. Crores of users pick teams, change captains until the toss, and refresh leaderboards every few seconds. One evening touches every idea on this page:

  • Team edits go to one main database; leaderboards and team pages are read from copies. (leader and followers)
  • When you save your team, does the app wait until a second machine has it too? (sync vs async)
  • You switch your captain, refresh, and the old captain is back. (replication lag)
  • The main database dies ten minutes before the toss. Someone else must take over, and only one. (failover)
  • A user edits the same team on a phone in Mumbai and a laptop routed to Delhi. (multi-leader)
  • Thirty crore users' teams don't fit on one machine. Split them by user. (shard key)
  • Ops adds machines on the afternoon of the final without moving everything. (rebalancing)
  • Everyone joins the same mega contest, and its leaderboard spans every shard. (hot keys, cross-shard queries)

This is a made-up app for teaching, not a description of any real company's systems.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

Replication: one leader, many followers

All writes go to one leader, which streams its change log to followers; any copy can serve reads, so you scale reads and survive a machine failure, but not writes.

The story · remember it like this

The principal's circular

In a school, only the principal's office issues circulars: "School closed on Friday", "Sports day moved to the 14th". Each classroom has a notice board, and a peon pins a copy of every circular on every board, in the order they were issued.

Students read whichever board is closest; nobody walks to the office to read one. If the office makes a mistake, it issues a correction, and the peon pins that too. If one classroom's board falls down, the others still have every circular. The office is the leader, the boards are followers, and the peon's round is replication.

What it really is
  • The leader (primary) accepts every write and records it in its log (the write-ahead log in PostgreSQL, the binary log in MySQL).
  • Followers (replicas, standbys) receive that log and replay it in the same order, so they end up with the same data.
  • Reads can go to any copy. Writes can't: there is still one leader, so replication scales reads, not writes.
  • Followers are also spares: if the leader dies, one is promoted (failover, below).
  • Two ways to ship changes: physical (byte-level log, whole database, same version) and logical (row changes, can filter tables and cross versions; also used for change-data capture).

Copies in different racks, zones or regions protect against those failing too. Three copies across three zones is a common default.

In a real system ✅ Seen · AWS docs

Amazon Aurora lets one writer have up to 15 Aurora Replicas that serve reads through a reader endpoint, and promotes one of them if the writer fails. AWS says replica lag is "usually much less than 100 milliseconds", rising when writes are heavy (AWS docs, checked Oct 2026).

Figma ran a single PostgreSQL database on AWS's largest instance in 2020, then added caching and read replicas before splitting anything (Figma, Mar 2024). Read replicas are usually the first step, because they don't change the data model.

Trade-offs
  • Cheap read scaling and a hot spare; every follower that serves reads may be slightly behind the leader.
  • Write capacity stays at one machine's. When writes or data size outgrow it, replication alone can't help: that's sharding.
Say it in the interview

Writes go to the leader; it streams its log to two followers in other zones. Reads that can tolerate a little staleness go to followers, and one follower is the failover target.

Trap

Saying "add read replicas" to fix a write bottleneck. Every replica has to apply every write too, so replicas add read capacity, never write capacity.

Synchronous vs asynchronous: how long you wait for the copy

Synchronous replication waits for a follower to confirm before telling the user "saved" (no loss, slower, can stall); asynchronous replies at once and copies later (fast, but a crash can lose the last few seconds).

The story · remember it like this

The kirana shop and the backup ledger

Suresh runs a kirana shop. His brother keeps a backup ledger in the shop across the road, in case Suresh's ledger is ever lost.

On a calm day Suresh shouts each sale across the road and waits for his brother to call back "likh liya" (written) before handing over the bag. Nothing is ever missing from the backup, but every customer waits for the shout and the reply, and if his brother steps out for tea, the queue stops.

On a festival day Suresh writes the sale, hands over the bag, and a boy runs a bundle of slips across every few minutes. Customers fly through. But if Suresh's shop catches fire, the sales since the boy's last trip are gone from both ledgers.

The middle way: Suresh has two brothers in two shops and waits for whichever replies first.

What it really is
  • Synchronous: the commit waits until at least one follower has the change on disk. Data is lost only if the leader and that follower die together. Cost: every commit pays at least one round trip to the follower, and if no follower answers, writes stall.
  • Asynchronous (the default in PostgreSQL and MySQL): the leader commits and replies, then ships the change. If it dies, whatever hadn't been shipped is lost.
  • Semi-synchronous and quorum commit: wait for one (or any k) of several followers, so one slow follower doesn't block writes.
  • The interview words: RPO (recovery point objective) is how much recent data you can afford to lose; async gives an RPO of roughly the replication lag, sync gives zero. RTO is how long recovery takes.

Precise point: "synchronous" usually means the follower has received and stored the change, not that it is visible to reads there. PostgreSQL has a separate remote_apply level for that.

In a real system ✅ Seen · PostgreSQL docs

PostgreSQL's docs: with synchronous replication each commit waits for confirmation that the change is in the write-ahead log on disk of both primary and standby; "the minimum wait time is the round-trip time between primary and standby". Streaming replication is asynchronous by default, and on a crash "the amount of data loss is proportional to the replication delay at the time of failover". It also supports quorums: synchronous_standby_names = 'ANY 2 (s1, s2, s3)'.

MySQL's semisynchronous replication waits until at least one replica has received and logged the change, not applied it, and falls back to asynchronous if no replica answers within a timeout (MySQL 8.4 manual).

Rough round trips for the cost: a millisecond or two between zones in one region, tens of milliseconds between cities, 100+ ms across continents (typical, varies by provider).

Trade-offs
  • Sync to a follower in the same region: zero data loss for a millisecond or two per commit. Sync across continents: every write pays 100+ ms; most systems go async across regions.
  • Fully synchronous to all followers is fragile: any one slow or dead follower stops all writes. Use one sync follower plus async ones, or a quorum (any 1 of 2).
Say it in the interview

Payments commit synchronously to one follower in another zone, so a lost leader loses nothing; the cross-region copy is asynchronous, so a region disaster could lose a few seconds, which we accept and reconcile.

Trap

Claiming async replication "never loses data" or that sync is free. Name the RPO each choice gives and what a commit costs in round trips.

Replication lag: reading your own writes

An async follower can be behind the leader, so a user may not see what they just wrote, or may see data go backwards between refreshes; fix it by routing that user's reads, not by making everything synchronous.

The story · remember it like this

The comment that disappeared

You post a comment under a cricket highlight: "What a catch!" The page refreshes and your comment isn't there. You think it failed, so you post it again. A minute later there are two.

Nothing was lost. Your write went to the leader; the refresh happened to read from a follower that was a second behind. Then you refresh again, land on a different follower, and the comment count goes from 41 to 40. The data seemed to go back in time.

The fix the app needs is small: for a minute after you post, show you the leader's copy (or at least a copy that has caught up to your comment). Other people can wait a second to see it.

What it really is

Asynchronous followers are "eventually consistent": stop writing and they catch up, but at any moment they may be behind. Lag is usually milliseconds and grows to seconds or minutes when a follower is overloaded or the network is slow. Three guarantees interviewers ask about:

  • Read-your-writes: after you write, your own reads see it. Fix: read from the leader for a short window after a write, or remember the write's log position (a version or LSN) and only read from a follower that has reached it.
  • Monotonic reads: you never see newer data and then older data. Fix: pin each user to one follower (choose it by hashing the user id).
  • Consistent prefix: you never see an answer before its question. Fix: keep causally related writes on the same shard, in order.

These are much cheaper than making every read strongly consistent, and they cover what users notice.

In a real system ✅ Seen · PostgreSQL docs

PostgreSQL's synchronous_commit = remote_apply makes a commit wait until the standby has applied it, which its docs say allows "load balancing with causal consistency" in simple cases: a read on that standby right after the commit sees the write.

Aurora replica lag is usually far below 100 ms but rises under heavy writes (AWS docs). Monitor it: PostgreSQL exposes the gap between the leader's WAL position and each standby's (pg_stat_replication).

Trade-offs
  • Reading from the leader after a write is simple but sends more load to the leader; tracking log positions keeps reads on followers but needs plumbing in the client or proxy.
  • Some reads must always be fresh (the balance before a payment, the seat before booking): send those to the leader, not a follower.
Say it in the interview

Followers serve reads that can be a second stale. For read-your-writes, the client sends the version of its last write; the router picks a follower that has reached it, or the leader.

Trap

Sending every read to followers, including "check stock, then buy". Stale reads before a write cause oversells; that read must hit the leader or be a conditional write.

Failover: a new leader, and never two

When the leader dies, detect it with a timeout, promote the most up-to-date follower, redirect writes, and fence the old leader so it can't keep accepting writes; the hard parts are false alarms, lost writes and split brain.

The story · remember it like this

Two class monitors

The class monitor, Priya, writes the homework on the board. One day she's out for a dental appointment, so the teacher makes Arjun the monitor, and he starts writing homework.

Priya comes back after lunch. Nobody told her, so she also writes homework, on the other half of the board. Now the class has two lists, and half the students do the wrong one. That's split brain.

The teacher's fix: every monitor gets a numbered badge, and the number only goes up. Priya's badge says 7, Arjun's says 8. The class only follows instructions signed with the highest number they've seen. When Priya returns with badge 7, her list is ignored. That number is a fencing token.

What it really is

Steps in an automatic failover:

  • Detect: the leader misses heartbeats for a timeout. Too short and a slow moment triggers a needless failover; too long and writes are down longer.
  • Choose: promote the follower with the most recent data, ideally a synchronous one so nothing is lost. The choice should be made by a quorum of observers (a consensus system such as etcd, ZooKeeper or Raft-based tools), not by one watcher.
  • Redirect: clients and proxies send writes to the new leader.
  • Fence: stop the old leader from accepting writes when it comes back: revoke its lease, cut it off at the proxy, or reject writes carrying an older epoch number.

With async replication, writes the old leader accepted but never shipped are lost or must be reconciled by hand. If both leaders accepted writes (split brain), data diverges.

In a real system ✅ Seen · GitHub, 2018

GitHub, 21 October 2018: a 43-second loss of connectivity between its US East Coast hub and primary data centre led its failover tool (Orchestrator, coordinating via Raft) to promote database leaders in the US West Coast data centre. The East Coast leaders held a few seconds of writes that hadn't replicated west, and the West Coast then took new writes, so neither side had everything. GitHub couldn't safely fail back east, chose to protect the data over speed, and the site was degraded for 24 hours and 11 minutes while it restored and reconciled (GitHub post-incident analysis, Oct 2018).

The lesson they drew: a short network blip triggered a cross-country failover the applications weren't built for.

Trade-offs
  • Automatic failover gives seconds of downtime but can fire on a network blip; manual failover is safer but takes minutes to hours of a human's time.
  • Promoting an async follower is fast but can drop the last writes; requiring a sync follower costs write latency every day to protect the rare failover.
Say it in the interview

Leader health is tracked by a three-node consensus group; on failover we promote the synchronous standby, bump the epoch, and the proxy rejects writes from any older epoch, so the old leader can't split the brain.

Trap

"If the leader fails, a replica takes over" with nothing else. Say how failure is detected, which replica wins, what happens to unreplicated writes, and how the old leader is stopped.

Multi-leader and leaderless: more than one copy takes writes

Let writes land on several copies (one leader per region, or any replica) for lower latency and higher availability, and pay for it with conflicts: two copies can accept different writes to the same item.

The story · remember it like this

Two grocery lists and five aunties

A joint family lives in two houses, one in Hyderabad and one in Bengaluru, each with a grocery list on its fridge. Anyone can add to the list in their own house, and on Sunday the two houses read their lists to each other over the phone. One list says "milk 2 L", the other "milk 1 L". Who's right? If they simply take whichever was written later, someone's change is silently dropped. That's multi-leader, and that's a write conflict.

Now the wedding. Five aunties keep track of the date. When the date changes, you must tell at least three of them. When you need the date, you ask any three. Any three you ask always include at least one who heard the latest change, so you take the newest answer. That's a leaderless quorum: write to W, read from R, with W + R > N.

What it really is
  • Multi-leader: one leader per region (or per device, for offline apps). Each takes local writes fast and replicates to the others asynchronously. Conflicts are inevitable, so you need a rule: last-writer-wins (simple, drops data), merge by field, CRDTs (data types that merge automatically, like counters and sets), or ask the user.
  • Leaderless (Dynamo style: Cassandra, Riak, ScyllaDB): the client or a coordinator writes to N replicas and waits for W acknowledgements; reads ask R replicas and take the newest. With W + R > N, the read and write sets overlap.
  • Repair: replicas that missed writes are fixed by read repair and background anti-entropy.

Precise point: W + R > N makes a read overlap the latest acknowledged write, but it is not full linearizability. Concurrent writes, sloppy quorums and clock-based "newest" can still surprise you. The Consistency, CAP and quorums page goes deeper.

In a real system ✅ Seen · Dynamo; AWS

Amazon's Dynamo paper (SOSP 2007): the common (N, R, W) configuration was (3, 2, 2). Amazon Aurora's storage keeps six copies across three Availability Zones, with a write quorum of 4/6 and read quorum of 3/6, so it survives losing a whole zone and still writes (AWS, Aug 2017).

DynamoDB global tables (multi-Region): in the default mode, changes replicate asynchronously "typically within a second or less", and concurrent updates to the same item are resolved by "last writer wins". An optional multi-Region strong consistency mode replicates synchronously to another Region before returning, giving zero RPO at higher latency (AWS docs, checked Oct 2026).

Trade-offs
  • Multi-leader: local write latency in every region and survives a region outage; conflicts and last-writer-wins data loss. Avoid it for anything with invariants such as balances or seat counts.
  • Leaderless: no failover step and tolerates slow nodes; reads and writes do more work (W and R replicas each), and you must reason about conflicts and repair.
Say it in the interview

Single-leader by default. Multi-region writes only for data where a merge is safe, like a user's own preferences with last-writer-wins; money and inventory stay single-leader per item.

Trap

Choosing multi-leader "for availability" without a conflict rule. The interviewer will write the same row in two regions and ask which one wins.

Sharding: split by a key, by range or by hash

Split the rows across machines by a shard key; range keeps neighbouring keys together (good for scans, risks hot ranges), hash spreads them evenly (good for load, loses range queries); pick the key from your main query so most requests touch one shard.

The story · remember it like this

Seating 30,000 exam candidates

An entrance exam has 30,000 candidates and 20 exam centres. First idea: by surname. A–B to centre 1, C–D to centre 2, and so on. The Kumar, Reddy, Sharma and Singh centres overflow while the X–Z centre sits half empty. That's a range split with skewed keys.

Second idea: the last two digits of the roll number decide the centre. Every centre gets about the same number, and your hall ticket tells you exactly where to go: one lookup, no searching. But "list every candidate named Sharma" now means phoning all 20 centres.

Third rule, kept either way: siblings applying together get the same centre, so a family's papers are in one place. That's keeping related data on one shard.

What it really is
  • Shard first only when you must: when data size or write rate outgrows one leader (the lab shows the arithmetic). Before that, try a bigger machine, read replicas, a cache, and vertical partitioning (moving groups of tables to their own database).
  • Range sharding: each shard owns a key range (A–F, 2025-01 to 2025-03). Range scans are one shard; but sequential keys (timestamps, auto-increment ids) send every new write to the last shard.
  • Hash sharding: shard = f(hash(key)). Spreads keys and writes evenly; a range query must ask every shard.
  • Directory (lookup) sharding: a table maps each key or tenant to a shard. Flexible (move one big customer alone), but the directory must be fast and highly available.
  • Choose the key from the main access pattern: user_id for a user's data, workspace or org id for a SaaS app. Keep things that are queried or updated together (a workspace's pages, an order's items) on the same shard, so joins and transactions stay local.
In a real system ✅ Seen · Notion; Figma

Notion split its PostgreSQL database in 2021 into 480 logical shards (Postgres schemas) on 32 physical databases, 15 per database, partitioned by workspace ID, because every block belongs to exactly one workspace (Notion, Oct 2021).

Figma, whose database stack grew almost 100× from 2020, first split tables into a dozen vertically partitioned databases, then horizontally sharded, with the first table shipped in September 2023. Almost every table could be sharded by UserID, FileID or OrgID, and it routes by a hash of the key to avoid hotspots from sequential IDs (Figma, Mar 2024).

MongoDB's docs: hashed shard keys distribute monotonically increasing values (ObjectIds, timestamps) evenly, but range queries become broadcast operations; with ranged sharding the chunk ending at MaxKey takes most inserts.

Trade-offs
  • Range: efficient scans and natural time-based archiving; hot spots on sequential keys and uneven ranges.
  • Hash: even load; range scans and "top N across everyone" must fan out to all shards.
  • Any shard key makes queries by other fields expensive. That is the real cost of the choice.
Say it in the interview

I shard the documents table by hash of workspace_id: every page load and edit is within one workspace, so it hits one shard, and a workspace's data stays together for joins and transactions.

Trap

Sharding on day one, or by a field the main query doesn't use (sharding orders by order_id when the screen is "my orders by user"). Show the capacity numbers first, then pick the key from the query.

Rebalancing: consistent hashing, virtual nodes and fixed slots

With hash mod N, adding a machine moves almost every key; consistent hashing moves only about 1/(N+1), virtual nodes even out the load, and many systems simply create far more fixed slots than machines and move whole slots.

The story · remember it like this

Opening a fifth reservation counter

A railway booking hall has four counters. Your token number decides the counter: token mod 4. The queue gets long, so they open a fifth and switch to token mod 5. Suddenly four out of five people are standing at the wrong counter, and the whole hall reshuffles. That's hash mod N.

A smarter station puts the counters around a big clock face. Your token is a time on the clock; you walk clockwise to the next counter. A new counter at 4 o'clock only takes the people between 3 and 4 o'clock, from one neighbour. Everyone else stays. That's consistent hashing.

But with only five counters on the clock, gaps are uneven, and one clerk serves a quarter of the hall. So each clerk runs several small windows dotted around the clock (virtual nodes). Or the station hands out 1,024 numbered queue slips up front and gives each counter a bundle; a new counter takes a few bundles from each (fixed slots).

What it really is
  • hash(key) mod N: perfectly even, but when N changes almost every key's answer changes. Going from N to N + 1 keeps only 1 key in N + 1 where it was: 4 → 5 moves 80%.
  • Consistent hashing (Karger et al., 1997; popularised by Dynamo): machines and keys hash onto the same circle; a key belongs to the next machine clockwise. Adding a machine takes keys from its neighbours only, about 1/(N+1) of the total on average.
  • Virtual nodes: each machine takes many positions on the circle, so its share is a sum of many arcs and evens out; a new machine takes a little from many.
  • Fixed slots (pre-sharding): hash keys into far more slots than machines (Redis: 16,384); a small map assigns slots to machines; growing moves whole slots. A key's slot never changes, so clients just refresh the map. Dynamo's own paper found equal-sized fixed partitions balanced load best.

Precise point: "consistent hashing moves 1/N of the data" is an average and assumes balanced tokens. With one random token per machine, arcs are very uneven. The lab computes it.

In a real system ✅ Seen · Redis; Instagram

Redis Cluster: HASH_SLOT = CRC16(key) mod 16384; slots are the unit of migration, a node that doesn't own a slot replies MOVED with the right address, and hash tags ({user42}:cart) put related keys in one slot. The spec suggests up to about 1,000 nodes (Redis cluster spec, checked Oct 2026).

Cassandra's production docs use num_tokens: 16 as their example and spell out the trade: more tokens make adding nodes easier, but each node then shares data with more peers, which lowers availability.

Instagram mapped several thousand logical shards (Postgres schemas) to a few physical servers and put the 13-bit logical shard id inside every 64-bit photo ID, so moving a logical shard never changes an ID (Instagram Engineering, 2011). Notion picked 480 logical shards because 480 divides evenly into 32, 40, 48 … hosts (Oct 2021).

Trade-offs
  • Ring with virtual nodes: no central map; balance depends on how many tokens, and more tokens means more peers per machine.
  • Fixed slots: simple and even, with a small slot map to keep consistent; the slot count is a ceiling on machines, so choose it large on day one.
Say it in the interview

Keys hash into 1,024 logical shards mapped to 16 machines. Adding a machine moves about 60 slots, roughly 1/17 of the data, in the background, while a slot map tells routers where each slot lives.

Trap

Proposing hash mod N and then "we'll add servers when needed". Ask yourself what fraction moves when N changes; for mod N it's nearly all of it.

The bills sharding sends: hot keys and cross-shard work

Sharding spreads keys, not traffic: one celebrity key still lands on one shard, and anything that doesn't include the shard key (other lookups, global top-N, unique checks, multi-shard transactions) becomes slow or hard.

The story · remember it like this

Tirupati on a festival day

On a festival day, lakhs of devotees come for the same deity. Building more temples in other towns doesn't shorten this queue: everyone wants this one. What helps is opening more queue lines into the same temple (splitting the hot key) and showing the darshan on big screens outside for those who only want to see it (a cache or read copies).

Meanwhile the temple office gets asked, "How many devotees came from Guntur today, across all temples?" Each temple keeps its own register, so someone must phone every temple and add up the answers. If that question comes daily, the office keeps a separate register by district, updated after each darshan: a global index.

What it really is

Hot keys:

  • A key that gets a big share of traffic (a celebrity, a mega contest, a viral product) overloads its shard whatever the shard count.
  • Reads: cache it, or add followers to that shard. Writes: split the key into sub-keys (contest#0 … contest#9) and merge on read, or buffer and batch them (count likes in memory, flush every second).

Cross-shard work:

  • Queries without the shard key fan out to every shard (scatter-gather): latency is the slowest shard's, and load grows with shard count.
  • Secondary indexes: local (each shard indexes its own rows; queries fan out) or global (one index sharded by the other field; reads are one hop, writes update two places, usually asynchronously).
  • Unique constraints and foreign keys across shards are no longer enforced by the database.
  • Transactions across shards need two-phase commit or a saga; design so most transactions stay in one shard.
In a real system ✅ Seen · AWS; Figma

DynamoDB: every partition is designed for at most 3,000 read units and 1,000 write units a second, so one hot partition key is capped there however big the table; AWS's guidance is uniform activity across keys and write sharding (adding a suffix to the key) for hot ones (AWS docs, checked Oct 2026).

Figma after sharding (Mar 2024): no atomic cross-shard transactions, no foreign keys or globally unique indexes unless they include the shard key, joins only between tables sharing a shard key, and scatter-gather queries add load comparable to the unsharded database. Its proxy supports the most common 90% of query shapes.

Trade-offs
  • Key splitting fixes hot writes, but every read of that key now reads and merges several sub-keys.
  • A global secondary index makes lookups by another field one hop, at the cost of extra writes and a short delay before the index catches up.
Say it in the interview

Most queries carry user_id and hit one shard. The leaderboard is the exception: each shard keeps its own top 100, and an aggregator merges them every few seconds instead of fanning out on every request.

Trap

Assuming more shards fix a hot key, or forgetting that a query without the shard key now visits every shard. Name your hot key and your one cross-shard query, and say how each is handled.

Try it: Split it: shards, copies, and what moves

Enter a workload. The lab works out how many shards the data size and write rate force, how many copies the reads need, how evenly four placement methods spread keys and how much data each moves when you add one machine, and whether the hottest key fits on its shard. The ring numbers come from real token arithmetic, not a formula.

Start from

An online store's catalogue: 300 GB, 2,000 updates a second, 150,000 page views a second during a sale. No single product gets more than 1% of traffic.

What we're sizingNumberHow we got itSo we decide
1 · How many shards and copies
Shards × copiesData size and write rate decide how many pieces you split into, because every write goes to a shard's one leader. Reads decide how many copies each piece needs, because any copy can serve a read.1 × 8 = 8 machines
for data: 300 GB ÷ 1.00 TB per machine = 1 shard
for writes: 2.0K/s ÷ 5.0K/s per leader = 1 shard
shards = the larger = 1
for reads: 150K/s ÷ 1 shards ÷ 20K/s per copy = 8 copies; you asked for 3 → 8
One shard is enough. Scale reads with followers and a cache; keep the simplicity of one database.
2 · Placing keys, and adding one machine
Method
hash mod NShard = hash(key) mod N. Perfectly even, and simple, until N changes: then almost every key's answer changes, so almost all data must move.50% moves · busiest 1.00×
a key stays put only if hash mod 1 = hash mod 2: 1 key in 2
moved = 1 ÷ 2 = 50% of the data = 150 GB copied
Fine for a fixed number of shards that never changes. Growing from 1 to 2 would copy 50% of everything while serving traffic: avoid.
MethodBusiest ÷ averageMoved on +1
1.00×50%
1.00×25%
1.00×58%
1.00×50%
3 · The hottest key
Shard that owns the hottest product_idOne key always lives on one shard, so hashing can't spread it. More shards shrink everyone else's slice but leave the hot key's traffic where it is.2.0K writes/s
its share = 1% (the hot key) + 99% ÷ 1 (an even slice of the rest) = 100%
writes: 2.0K/s × that share = 2.0K/s vs 5.0K/s one leader takes
reads per copy: 150K/s × that share ÷ 8 copies = 19K/s vs 20K/s
Within limits. Keep watching per-shard load: hot keys appear on match nights, sales and celebrity posts, not on average days.
4 · Verdict for these numbers
Our pickDon't shard: replicateThe data fits one machine and one leader takes 2.0K writes a second. Only reads are heavy, and reads scale by adding followers (8 copies here) and a cache. Sharding would add cross-shard queries and resharding work for nothing.

Try: Product catalogue needs no sharding at all, just copies. On Chat messages, switch the method from hash mod N to fixed slots and watch the data copied on growth drop from almost all of it to a few percent. On IPL final contest, one contest's 20% overloads its shard however many shards you add. Machine limits are rounded, typical teaching values (1.00 TB, 5.0K writes/s, 20K reads/s per machine); ring numbers come from real token arithmetic with a fixed seed, so other seeds give somewhat different arcs.

Remember it

One line per idea. Read this the night before.

  1. Leader and followers: copies scale reads and give a spare; writes still go to one leader.
  2. Sync vs async: waiting for a follower costs a round trip per commit and buys zero data loss; async loses about the lag.
  3. Lag: route a user's reads after their own write (leader, or a follower that has caught up); pin users to one follower.
  4. Failover: detect, promote the freshest follower, redirect, and fence the old leader with an epoch.
  5. Multi-leader and leaderless: writes in many places mean conflicts; W + R > N overlaps but isn't the whole story.
  6. Shard key: shard only when the numbers say so; pick the key from the main query; range for scans, hash for even load.
  7. Rebalancing: mod N moves almost everything; consistent hashing with virtual nodes or fixed slots moves about 1/(N+1).
  8. The bills: a hot key stays on one shard; queries without the key fan out; cross-shard constraints and transactions are on you.

Check yourself

Answer out loud, then open.

Your database is at 90% CPU from reads. Another team says "shard it". What do you do first?

Add read capacity before splitting anything.

  • Add followers and send reads that can be slightly stale to them; keep fresh-critical reads on the leader.
  • Put a cache in front of the hottest reads.
  • Check for missing indexes and expensive queries first; they're often the real cause.

Shard when writes or data size outgrow one leader, because replicas can't help there.

Say it Reads scale with copies; writes and size scale with shards.

Synchronous or asynchronous replication for a payment ledger? What does each cost?

Synchronous to at least one follower in another zone, async beyond that.

  • Sync: zero committed data lost if the leader dies, at the cost of a round trip (a millisecond or two in-region) on every commit; use a quorum (any 1 of 2) so one slow follower doesn't stall writes.
  • Async cross-region: a regional disaster could lose roughly the replication lag (seconds), which you reconcile from upstream records.

Say it RPO zero within the region, seconds across regions, and I can name what each commit pays.

A user updates their profile photo, refreshes, and sees the old one. Explain and fix it.

The write went to the leader; the refresh read an async follower that hadn't applied it yet: replication lag breaking read-your-writes.

  • Read that user's own profile from the leader for a short window after they change it, or
  • Return the write's version/log position to the client and route their next read to a follower that has reached it.
  • Pin each user to one follower so they never see data go backwards (monotonic reads).

Making every read synchronous would fix it too, at a much higher cost.

The leader goes silent for 20 seconds, a follower is promoted, then the old leader comes back. What can go wrong and how do you prevent it?

Two things: lost writes and split brain.

  • Writes the old leader accepted but hadn't replicated are missing on the new leader (unless a synchronous follower was promoted).
  • If the old leader still thinks it's leader, clients may write to both, and the data diverges.

Prevention:

  • Let a consensus group (etcd, ZooKeeper, Raft) decide leadership and hand out an increasing epoch.
  • Fence: the proxy or storage rejects writes with an old epoch; the old leader's lease expires before a new leader is chosen.
  • Prefer promoting a synchronous standby.

GitHub's 2018 incident is the real example: a 43-second partition, a cross-country promotion, and 24 hours of degradation.

You have 4 cache servers using hash(key) mod 4 and add a fifth. What happens, and what should you have done?

About 80% of keys now map to a different server (only 1 in 5 keys has the same answer for mod 4 and mod 5), so the hit rate collapses and the database behind the cache gets hammered.

Better:

  • Consistent hashing with virtual nodes: adding one server moves about 1/5 of keys, taken a little from each.
  • Or fixed slots (e.g. 1,024 or Redis's 16,384) mapped to servers: move whole slots, keys never change slot.
Pick a shard key for a chat app's messages table. What breaks with a bad choice?

channel_id (with a time bucket for very busy channels), with message_id as the sort order.

  • The main query is "latest 50 messages in this channel": one shard, in order.
  • message_id alone (hash) would scatter a channel across every shard: every page load fans out.
  • A timestamp range key would send all new writes to the newest shard.
  • A huge channel is a hot key: bucket it by time so one channel spans several partitions.
After sharding users by user_id, product asks for "find a user by email" and "global top 100". How?

Neither query has the shard key, so avoid fanning out on every request.

  • Email: a global secondary index, a separate table email → user_id sharded by email, written alongside the user (or from the change stream). One hop to find user_id, then one hop to the user's shard. Uniqueness of email is enforced in that table.
  • Top 100: each shard keeps its own top 100; an aggregator merges them every few seconds and caches the result.

Say it Queries without the shard key get their own index or a precomputed view, not a scatter-gather on every call.

Where you'll use this in the series

Sources

Checked October 2026. Replication behaviour comes from the official PostgreSQL, MySQL, Aurora, DynamoDB, Redis and Cassandra docs and the Dynamo paper; company figures are as published on the dates shown (Instagram 2011, Notion 2021, Figma 2024, GitHub's incident 2018, AWS 2017) and may have changed since. Round-trip times and the lab's per-machine limits are rounded, typical teaching values; the lab's ring figures come from a fixed hash seed.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

You're reading this Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts