Sharding and Replication: Scaling a Database Beyond One Machine
Replication scales reads and provides failover; sharding scales writes and storage. Covers replication lag, read-your-writes, shard keys, hot shards and resharding.
When a database becomes slow as usage grows, there are two fundamental techniques for scaling it: replication and sharding. They are often mentioned together, but they solve different problems.
Replication keeps copies of the same data on several machines. Sharding splits the data so that each machine holds a different part. Choosing between them starts with one question: is the bottleneck reads, writes or storage?
Diagnose first
Before adding machines, identify what is actually limiting the database.
- Too many read queries for one server: add replicas (and a cache).
- Too many writes for one server: replicas do not help, because every replica must apply every write. The data must be sharded.
- Too much data for one server's disk or memory: again sharding, since every replica stores the full dataset.
- Slow individual queries: often an indexing or query problem, not a scaling problem. Fix that first.
Replication: leader and followers
In the most common arrangement, one node is the leader (also called primary). All writes go to the leader. The leader records each change in a log and sends it to the followers (replicas), which apply the same changes in the same order. Read queries can be served by any follower.
Replication provides three things. Read capacity grows with the number of followers. Availability improves, because if the leader fails a follower can be promoted to leader; this is called failover. And copies in other locations protect against the loss of a machine or a data centre.
Synchronous versus asynchronous replication
With synchronous replication, the leader waits for a follower to confirm that it has the change before telling the client the write succeeded. No acknowledged write is lost if the leader crashes, but each write is slower, and a slow or unreachable follower can stall writes.
With asynchronous replication, the leader acknowledges the write immediately and ships the change afterwards. Writes are fast, but a follower may be slightly behind, and if the leader crashes before a change is shipped, that change can be lost. Many systems use a middle ground, where one follower is synchronous and the rest are asynchronous.
Replication lag and read-your-writes
With asynchronous replication there is a delay between a write on the leader and its appearance on a follower. This delay is replication lag. It is usually milliseconds, but it can grow to seconds under load.
The visible symptom: a user updates their profile, the page reloads, the read is served by a follower that has not yet received the change, and the user sees the old data. To the user it looks as if the update was lost.
The fix is read-your-writes consistency. After a user makes a change, that user's reads are sent to the leader for a short period, or the reads are routed to a follower only if it has caught up to the position of that write. Other users can continue reading from followers, where a small delay is harmless.
Failover and split brain
Failover has its own risks. The system must detect that the leader is truly dead and not merely slow, choose the most up-to-date follower, and redirect writes to it. If the old leader comes back and still believes it is the leader, two nodes accept writes and the data diverges. This situation is called split brain. It is prevented by requiring a majority of nodes (a quorum) to agree on who the leader is, and by fencing the old leader so that it cannot accept writes.
Other replication topologies exist. Multi-leader replication accepts writes at several nodes and must resolve conflicts. Leaderless replication, used by Dynamo-style databases, lets any replica accept writes and uses quorums on read and write.
Sharding
Sharding, also called horizontal partitioning, divides the rows of a dataset across several databases called shards. Each shard holds a subset of the data and handles the reads and writes for that subset. Write throughput and storage now grow with the number of shards. In practice each shard is itself replicated, so a production topology is several shards, each with a leader and followers.
Application
|
Shard router / proxy
shard = hash(user_id) -> shard map
+-------------------+-------------------+
v v v
Shard 0 Shard 1 Shard 2
Leader (writes) Leader (writes) Leader (writes)
| | | | | |
Follower Follower Follower Follower Follower Follower (reads, failover)Sharding strategies
- Hash-based: shard = hash(key) mod N. Spreads data evenly, but range queries across keys must touch every shard, and changing N moves most keys.
- Range-based: each shard owns a range of keys, for example user IDs 1 to 1 million. Range scans are efficient, but ranges can become uneven and recent data often concentrates on one shard.
- Directory-based: a lookup table records which shard holds each key or tenant. Very flexible, at the cost of an extra lookup and a critical dependency on the directory.
- Geographic: data is placed by region, keeping it close to users and helping with data residency rules. Regions are rarely equal in size, so load can be uneven.
Choosing the shard key
The shard key decides everything about how well sharding works. A good key has high cardinality, distributes data and traffic evenly, and matches the most common query so that a typical request touches one shard only.
For user-centric data, the user ID is usually a good shard key: all of a user's rows are on one shard, so the common query 'fetch this user's data' is a single-shard operation. A poor key is one with few distinct values or a skewed distribution, such as country, where one shard receives most of the load.
Hot shards
Even with a reasonable key, traffic may not be even. If all data for one very popular account lives on one shard, that shard receives far more traffic than the others. This is a hot shard, and it becomes the bottleneck for the whole system while other shards sit idle.
- Choose a key that spreads the hot entity, for example sharding posts by post ID instead of author ID.
- Split the hot key further by adding a suffix (key salting), so that one logical key is spread over several partitions.
- Give exceptionally large tenants a dedicated shard.
- Put a cache in front of hot reads.
Resharding
Eventually more shards are needed. With hash mod N, changing N from 4 to 5 changes the result for most keys, so almost all the data has to move between shards. On a live system that is slow and risky.
Consistent hashing solves this: adding a shard moves only about one N-th of the keys. A related technique is to create many more logical partitions than physical servers from the start (for example 1,024 partitions on 4 servers) and move whole partitions when servers are added. Consistent hashing is covered in detail later in this series.
The costs of sharding
- Cross-shard joins are not available; data must be denormalised or joined in the application.
- Transactions across shards need distributed protocols such as two-phase commit or sagas.
- Queries that do not include the shard key must be sent to every shard and merged (scatter-gather).
- Unique constraints and auto-increment IDs no longer work globally; a distributed ID generator is needed.
- Operations become harder: backups, schema changes and rebalancing all happen per shard.
Interview summary
- First ask whether the problem is reads, writes or storage.
- Reads: replication with a leader and followers.
- Writes and storage: sharding by a well-chosen shard key.
- Replication lag is handled with read-your-writes consistency.
- Watch for hot shards, and use consistent hashing so that resharding moves little data.
Summary
Replication copies the same data to several nodes to scale reads and survive failures, at the cost of replication lag. Sharding splits data across nodes to scale writes and storage, at the cost of cross-shard queries and operational complexity. The shard key determines whether load is even, and consistent hashing keeps resharding manageable. Because sharding is hard to undo, it is the last step after indexing, caching and replication.
Puneet Tiwari
Full Stack Developer
