Sharding, Partitioning and Replication
Almost every system design interview reaches the point where one database server isn't enough. Either there's too much data to fit on one machine, too many writes for one machine to absorb, too many reads, or the business can't tolerate that one machine failing. The two tools for this moment are replication (keep copies of the same data on several machines) and sharding, also called partitioning (split the data so each machine holds a different piece).
They solve different problems and are almost always used together:
- Replication gives you fault tolerance, read scaling, and lower latency by putting copies near users. It does nothing for write throughput or total data size, since every replica holds everything and applies every write.
- Sharding gives you write scaling and storage scaling, since each machine handles a fraction of the data. It does nothing for fault tolerance on its own: lose one shard's machine and that slice of data is gone.
A production database at scale is usually both: the data is split into shards, and each shard is replicated three ways. The interesting interview questions are about the choices inside each: which replication model, what to do about replication lag, which shard key, how to handle hot keys, and how to query across shards.
Before sharding anything, check whether you need to. A single modern Postgres or MySQL server with fast SSDs can hold several terabytes and handle on the order of tens of thousands of simple writes per second, and read replicas multiply read capacity. Saying "this fits on one primary with two replicas, so we don't shard yet" is a perfectly senior answer when the numbers back it up.
Replication
Single-Leader Replication
The most common setup. One replica is the leader (primary). All writes go to it. The leader writes the change to its own storage and sends it to followers (replicas, secondaries), which apply the changes in the same order. Reads can go to the leader or to any follower.
This is how Postgres streaming replication, MySQL replication, MongoDB replica sets and most managed relational databases work. It's simple, there are no write conflicts (one node orders all writes), and it scales reads nearly linearly by adding followers.
Synchronous vs asynchronous. The key decision is when the leader tells the client "done":
- Synchronous: wait until a follower has the write. If the leader dies, nothing acknowledged is lost. But every write pays an extra round trip, and if the synchronous follower is down or slow, writes stall.
- Asynchronous: acknowledge as soon as the leader has it, and ship to followers in the background. Fast and resilient to slow followers, but if the leader dies, the last moments of acknowledged writes may never have reached any follower, and they're lost on failover.
- Semi-synchronous: the common compromise. Wait for one follower (of several) to confirm, ship to the rest asynchronously. You always have the write on two machines, and one slow follower doesn't block you. Postgres lets you set this with
synchronous_standby_names; MySQL has a semi-sync plugin. Cloud databases like Aurora instead require a quorum of storage nodes across availability zones to acknowledge.
How changes are shipped. There are three broad approaches:
- Statement-based: send the SQL text. Breaks on anything nondeterministic (
NOW(),RAND(), auto-increment under concurrency). Rarely used now. - Physical (WAL shipping): send the database's own write-ahead log, which describes byte-level changes to pages. Exact and efficient, but ties leader and follower to the same database version, which complicates upgrades. Postgres streaming replication works this way.
- Logical (row-based): send a description of each changed row ("row with id 42 now has these values"). Independent of storage format, so it works across versions and can feed other systems. MySQL's row-based binlog and Postgres logical replication work this way, and it's what change data capture tools consume (/system-design/change-data-capture).
Failover
When the leader dies, a follower has to be promoted, and clients and the other followers must switch to it. It sounds mechanical, and it's where most replication incidents happen:
- Detecting failure relies on timeouts. Too short and you fail over during a brief network blip or a long GC pause; too long and writes are unavailable for longer. Typical managed databases take from several seconds to a minute or two.
- Choosing the new leader: it should be the follower with the most recent data. With async replication, even the best follower may be missing writes that the old leader acknowledged.
- Split brain: if the old leader wasn't actually dead (just partitioned), you may now have two nodes accepting writes. Safe failover needs a majority-based decision about who the leader is (/system-design/consensus) and fencing of the old leader, for example by revoking its storage access or rejecting writes with an old epoch number.
- Lost writes cause second-order damage. If the old leader assigned auto-increment IDs that the new leader reassigns, any external system (a cache, a search index, another service) that saw the old IDs now points at the wrong rows.
Replication Lag
With asynchronous followers, reads from a follower can be behind the leader. Usually by milliseconds, sometimes by seconds or minutes under heavy load or after a network issue. This is eventual consistency: if writes stop, followers eventually catch up. The problem is what users see in the meantime. Three anomalies come up constantly:
- Read-your-writes. A user updates their profile, the page reloads from a follower that hasn't received the update, and their change appears to have vanished. Fixes: read the user's own data from the leader; or read from the leader for a short window (say 10 seconds) after the user writes; or have the client remember the log position of its last write and only read from a follower that has caught up to it.
- Monotonic reads. A user refreshes twice, hits two followers with different lag, and sees a comment appear and then disappear. Fix: pin each user to one follower (hash the user ID to pick it), so their view only moves forward.
- Consistent prefix reads. Writes that have a causal order arrive out of order: you see an answer before the question it answers. This mostly hits sharded systems where the two writes went to different shards with different lag. Fix: write causally related data to the same shard, or track causal dependencies.
In an interview, the moment you add read replicas, mention lag and how you handle read-your-writes. "Users read their own profile from the primary; everyone else's from replicas" is a short sentence that shows you know where the bug will come from.
Multi-Leader Replication
Here several nodes accept writes, and each replicates its writes to the others. The usual reason is multiple regions: each region has a leader so writes are local and fast, and the regions sync asynchronously (/system-design/multi-region). Offline-capable clients (a calendar app on your phone) are an extreme case of the same thing: every device is a leader.
The cost is write conflicts. Two users edit the same document title in two regions at the same time; both writes succeed locally; when they replicate, which wins?
- Last write wins (LWW): attach a timestamp, keep the highest. Simple, and silently discards data. Clock skew between machines means the "last" write may not be the one that happened last.
- Merge the values: for some data types, the right answer is to combine. A set of tags can take the union; a counter can sum per-region increments. CRDTs are data types designed so that concurrent updates always merge deterministically (/system-design/crdts).
- Record the conflict and let the application or user resolve it, as version control does.
- Avoid conflicts: route all writes for a given record to one "home" leader, so in practice each record is single-leader.
The last option is the most common in real designs. Multi-leader with true conflicting writes is something to reach for deliberately, with a merge story, not by default.
Leaderless Replication
In leaderless (Dynamo-style) replication, used by Cassandra, ScyllaDB, Riak and the original Amazon Dynamo design, there's no leader at all. The client (or a coordinator node acting for it) sends each write to all N replicas of a key and considers it successful when W of them acknowledge. Reads ask R replicas and take the newest value.
The rule is if R + W > N, every read overlaps with every successful write on at least one replica. The common setting is N = 3, W = 2, R = 2: you tolerate one slow or failed replica for both reads and writes, and every read sees the latest successful write.
You can tune for your workload. W = 1, R = 1 is fastest and gives no overlap guarantee (fine for metrics). W = N, R = 1 makes reads cheap and writes fragile. Cassandra exposes this per query with consistency levels like ONE, QUORUM and LOCAL_QUORUM (/system-design/cassandra).
Replicas that missed writes have to catch up somehow:
- Read repair: when a read sees that one replica returned an older version, the coordinator writes the newer version back to it.
- Hinted handoff: if a replica is down during a write, another node stores the write as a "hint" and delivers it when the replica comes back.
- Anti-entropy: a background process compares replicas and fixes differences, using Merkle trees (hash trees over key ranges) so two replicas can find their differences without sending every key.
Quorums aren't magic. R + W > N doesn't make the system linearizable. Concurrent writes to the same key can land in different orders on different replicas and need conflict resolution (usually LWW on timestamps, with the same clock-skew caveats). A write that failed to reach W replicas may still have reached some, so it's neither cleanly committed nor rolled back. And sloppy quorums (accepting writes on any W available nodes, not the key's designated replicas, during a failure) trade the overlap guarantee for availability. If you need compare-and-set or strict uniqueness, you need consensus (Cassandra adds a Paxos round for its lightweight transactions for exactly this reason).
Comparing the Models
| Single-leader | Multi-leader | Leaderless | |
|---|---|---|---|
| Writes go to | One leader | Any leader (one per region, usually) | Any W of N replicas |
| Write conflicts | None | Yes, must be resolved | Yes, usually LWW or version vectors |
| Failover | Promote a follower; risky | Each leader independent | No failover needed |
| Strong consistency | Possible (read from leader, sync replicas) | No | No (tunable, not linearizable) |
| Typical systems | Postgres, MySQL, MongoDB | Cross-region active-active setups, offline-first apps | Cassandra, ScyllaDB, Riak |
Sharding
Why and When
Shard when one machine can't hold the data or absorb the writes. Some quick arithmetic: 500 million users × 2 KB of profile data each is 1 TB, which a single server handles fine. 50,000 writes per second of 1 KB events, kept for a year, is about 1.6 PB, which no single server handles. The second system needs sharding for both storage and write throughput.
Sharding has real costs, which is why you shouldn't do it prematurely:
- Queries that don't include the shard key must hit every shard (scatter-gather).
- Transactions across shards need distributed coordination (/system-design/transactions).
- Joins across shards are expensive or impossible.
- Uniqueness constraints only hold within a shard, unless the unique column is the shard key.
- Operations (backups, schema changes, rebalancing) get harder.
Partitioning Strategies
There are two main ways to decide which shard a key belongs to.
Range partitioning. Each shard owns a contiguous range of keys: A-F on shard 1, G-M on shard 2, and so on. Keys within a shard are sorted, so range scans are efficient ("all events for device 17 between 9:00 and 10:00" touches one shard if the key is device_id, timestamp). HBase, Bigtable, Spanner, CockroachDB and TiKV partition by range. The weakness is hot spots: if the key is a timestamp, every current write goes to the shard holding "now," and one machine takes the whole write load while the others idle.
Hash partitioning. Hash the key and use the hash to pick the shard. A good hash spreads keys evenly even when the keys themselves are clustered, so sequential IDs or timestamps no longer pile onto one shard. Cassandra, DynamoDB, Redis Cluster and MongoDB's hashed sharding work this way. The cost is that range queries over the original key are gone: adjacent keys land on unrelated shards.
A common hybrid is a compound key: hash the first part to choose the shard, and sort by the second part within it. Cassandra's primary key ((user_id), created_at) hashes user_id to place the partition and stores each user's rows sorted by created_at. You get even distribution across users and efficient time-range queries for one user. DynamoDB's partition key + sort key is the same idea.
Directory-based partitioning is a third option: keep an explicit lookup table from key (or key group) to shard. It's the most flexible, since you can move a single tenant to its own shard, but the directory is extra infrastructure and must be fast and highly available. Multi-tenant SaaS systems often do this at the tenant level.
Choosing a Shard Key
This is the most important sharding decision, and the one interviewers probe. A good shard key has:
- High cardinality: many distinct values, so data can spread over many shards.
countryis a bad shard key;user_idis a good one. - Even load: no value gets a disproportionate share of reads or writes.
- Alignment with the main queries: the hottest queries include the shard key, so they touch one shard.
- Co-location of data that changes together: so the important transactions stay on one shard. Shard orders and order items both by
order_id(or both bycustomer_id), not one by each.
Worked examples:
- Chat messages: shard by
conversation_id. "Load the last 50 messages of this chat" hits one shard, sorted by message time. Sharding bysender_idwould scatter every conversation across shards. - Ride-sharing trips: shard active trips by
trip_idfor updates, and keep a separate geospatial index for "drivers near me" (/system-design/ride-sharing). - URL shortener: shard by the short code; every lookup includes it (/system-design/url-shortener).
- Multi-tenant SaaS: shard by
tenant_id, so a tenant's data and transactions stay together. Big tenants may need their own shard.
Don't just name a shard key. Name the query it makes fast and the query it makes slow, and say how you handle the slow one. "Sharding tweets by
user_idmakes user timelines one-shard reads; search by keyword becomes a scatter-gather, so we put search in Elasticsearch instead."
Hot Spots and Skew
Even with a perfect hash, load follows popularity, not keys. A celebrity's account, a viral post, or a flash-sale product puts most of the traffic on one key and therefore on one shard. Hashing can't help, because every request for that key hashes to the same place.
Remedies, roughly in order of preference:
- Cache hot reads. Most hot-key problems are read problems, and a cache in front (with request coalescing so a miss doesn't stampede the database) absorbs them (/system-design/caching).
- Split the hot key. Append a random suffix (
post:123#0topost:123#9) so writes spread across 10 shards, and have readers read all 10 and combine. This works well for counters (/system-design/likes-counter), at the cost of more expensive reads. - Buffer and batch writes. Aggregate increments in memory or in a stream processor, and write the total every second.
- Isolate the hot tenant on dedicated hardware using a directory-based mapping.
Secondary Indexes
Sharding by user_id makes lookups by user_id fast. What about "find all users with email X" or "all listings in Seattle under $200"? There are two ways to index a sharded table by something other than its shard key:
Local indexes (document-partitioned). Each shard indexes only its own data. Writes are cheap, since the index update happens on the same shard in the same transaction. But a query by the indexed field must ask every shard and merge the results. Elasticsearch, MongoDB and Cassandra's secondary indexes work this way. Scatter-gather is fine for a handful of shards and moderate QPS; with 100 shards, every query's latency is the latency of the slowest of 100, and one slow shard slows everyone.
Global indexes (term-partitioned). The index itself is sharded by the indexed value. All users with emails starting a are indexed on one index shard, say. A lookup by email hits one index shard. But a single write to the users table now updates an index that lives on a different shard, which is either a distributed transaction or (more commonly) asynchronous, meaning the index is briefly stale. DynamoDB's global secondary indexes are updated asynchronously for this reason.
The practical interview answer is often a third option: keep a separate lookup table keyed by the secondary field (email → user_id), sharded by that field, maintained in the write path or via change data capture. Or send the query to a search system built for it.
Rebalancing
Over time data grows, machines are added, and load shifts. Moving data between shards is called rebalancing, and the naive approach is a trap.
Don't use hash(key) mod N. If you go from 10 to 11 shards, a key's shard changes unless hash mod 10 == hash mod 11, which is true for only about 1 in 11 keys. Roughly 90% of your data moves at once. Three better approaches:
- Fixed number of partitions. Create many more partitions than machines from day one, say 4,096 partitions on 16 machines, 256 each. Keys map to partitions with
hash mod 4096, which never changes. Adding a machine means moving some whole partitions to it, and a key's partition never changes. Elasticsearch shards, Kafka partitions, Redis Cluster's 16,384 hash slots and Couchbase vBuckets all work this way. The catch is choosing the count up front: too few and partitions become huge; too many and per-partition overhead adds up. - Consistent hashing. Place nodes and keys on a hash ring; each key belongs to the next node clockwise. Adding a node only takes keys from its neighbors, about
1/Nof the data. Virtual nodes (each machine owns many points on the ring) smooth out the distribution. Cassandra and Dynamo use this. See /system-design/consistent-hashing. - Dynamic splitting. Start with one range per table; when a range grows past a size threshold, split it in two, and move halves to balance load. HBase regions, CockroachDB ranges (split around 512 MB by default) and DynamoDB partitions (which split as tables grow, with each partition holding roughly 10 GB) work this way. It adapts to the data automatically, which is why most newer systems prefer it.
Rebalancing should be gradual and throttled: copy the partition in the background while it still serves traffic, catch up on changes, then switch ownership. Fully automatic rebalancing can make bad situations worse: a node that's slow because it's overloaded gets declared dead, its data starts moving, and the copying overloads the rest of the cluster. Many systems therefore make rebalancing automatic but rate-limited, or require an operator to approve it.
Routing Requests
Once data is spread out, something has to know which shard holds which key. Three patterns:
- Routing tier: a proxy layer that knows the mapping and forwards requests. Vitess for MySQL (VTGate), MongoDB's
mongosand Twemproxy work this way. Clients stay simple. - Any node forwards: the client contacts any node, which forwards to the right one. Cassandra's coordinator node does this.
- Smart client: the client library caches the mapping and talks directly to the right shard. Redis Cluster clients and the DynamoDB SDK's endpoint routing work this way. Lowest latency, but clients must handle "moved" responses when the mapping changes.
The mapping itself is critical metadata, often kept in a consensus-backed store like ZooKeeper or etcd (/system-design/zookeeper-etcd), or gossiped between nodes (/system-design/gossip-protocol).
Putting Them Together
A typical large-scale relational setup: data sharded by user_id into 64 logical shards, placed on 16 primary servers, each primary with two followers in other availability zones. A routing layer maps user_id → shard → current primary. Writes go to the primary; reads that can tolerate lag go to followers; reads of a user's own data go to the primary.
Distributed SQL databases (Spanner, CockroachDB, TiDB, YugabyteDB) do all of this internally: they split tables into ranges, replicate each range with Raft or Paxos, split and move ranges automatically, and run distributed transactions across them. Choosing one of them is a way of buying sharding and replication without operating them yourself (/system-design/database-selection).
Sharding and Replication in an Interview
What to Say When
- Reads are the bottleneck: add read replicas and a cache before sharding. Address replication lag and read-your-writes.
- Writes or storage are the bottleneck: shard. Show the arithmetic that says one machine isn't enough.
- Availability requirement: replicate across availability zones, semi-synchronously, with automated failover backed by consensus.
- Multi-region writes: multi-leader with a home region per record, or a distributed SQL database, and say how you handle conflicts.
- High write throughput with simple access by key, tolerance for eventual consistency: leaderless (Cassandra) or DynamoDB, which handle sharding and replication for you.
Common Follow-ups
- "What's your shard key, and why?" Name it, the query it serves, and the one it hurts.
- "What happens when a shard gets hot?" Cache, split the key, batch writes, or isolate the tenant.
- "How do you add a shard?" Fixed partitions or consistent hashing, never
mod N; copy in the background, then cut over. - "How do you query by a field that isn't the shard key?" A local index with scatter-gather if shards are few; otherwise a separate lookup table or a search index.
- "The primary just died. What's lost?" With async replication, the last writes not yet shipped; with semi-sync, nothing acknowledged. Explain how failover avoids split brain.
- "Why not just use R + W > N for strong consistency?" Because concurrent writes, partial failures and sloppy quorums still break linearizability. For compare-and-set, use consensus.
Summary
Replication keeps copies of the same data for fault tolerance and read scale; sharding splits data so each machine handles a fraction of the writes and storage. Most systems at scale use both: shard first by a key that matches the main queries, then replicate each shard.
For replication, single-leader is the default, with semi-synchronous followers for durability and an explicit plan for replication lag (read-your-writes, monotonic reads) and for safe failover. Multi-leader is for multi-region or offline writes and needs a conflict story. Leaderless quorums give high availability and tunable consistency, but not linearizability.
For sharding, pick range partitioning when you need scans and hash partitioning when you need even load, and often combine them with a compound key. Choose a high-cardinality shard key aligned with your hottest queries, plan for hot keys, decide between local and global secondary indexes, and rebalance with fixed partitions, consistent hashing or range splitting rather than mod N. And before all of that, do the arithmetic: often one primary and a couple of replicas is still the right answer.