Ankit KanojiyaAdvanced
Evergreen guide by Ankit Kanojiya · Advanced · System Design
Database Replication and Sharding for Scale
How to scale a database beyond one machine: replication for read scaling and availability, sharding for write scaling, and the hard trade-offs of each, including replication lag and cross-shard queries.
- Databases
- Replication
- Sharding
- Scalability
- Consistency
- PostgreSQL
A single database is the most common hard limit in a scaling system. Application servers add cheaply; the database holds authoritative state and cannot simply be cloned. Two techniques push past the single-machine ceiling, and they solve different problems: replication scales reads and improves availability, while sharding scales writes and storage.
Replication
Replication keeps copies of the same data on multiple machines. The usual arrangement is one primary that accepts writes and one or more replicas that receive a stream of changes.
writes --> Primary --replication--> Replica 1 (reads)
\-------------> Replica 2 (reads)
- Reads spread across replicas, multiplying read capacity.
- If the primary fails, a replica can be promoted, improving availability.
Synchronous vs asynchronous
- Asynchronous replication acknowledges a write as soon as the primary has it. Fast, but a replica may lag, and a primary crash can lose recent writes.
- Synchronous replication waits for a replica to confirm before acknowledging. Safer, but slower and vulnerable to stalling if a replica is slow.
Many systems use semi-synchronous: wait for at least one replica, let the rest catch up asynchronously.
Replication lag
The defining hazard of read replicas is lag. A user who writes and then immediately reads may not see their own change if the read hits a lagging replica. This is called read-your-writes inconsistency. Mitigations:
- Route reads that follow a write to the primary for a short window.
- Pin a session to the primary after it writes.
- Track a write position and only read from replicas that have caught up to it.
Sharding (horizontal partitioning)
Replication does not help write throughput: every replica still applies every write. When writes or dataset size exceed one machine, you shard, splitting data across independent databases, each holding a subset.
users 0-99k -> shard A
users 100-199k -> shard B
users 200-299k -> shard C
Each shard is its own database (often with its own replicas), so writes and storage scale with the number of shards.
Choosing a shard key
The shard key determines which shard owns a row, and it is the single most consequential decision:
- Range-based: partition by ranges of the key. Simple and good for range scans, but prone to hot spots if traffic clusters in one range.
- Hash-based: hash the key to choose a shard. Spreads load evenly, but destroys range queries.
- Directory-based: a lookup service maps keys to shards. Flexible and allows rebalancing, but the lookup is another component to keep available.
A good shard key spreads load evenly and keeps data that is queried together on the same shard. A poor key creates hot shards or forces expensive cross-shard queries.
The costs of sharding
Sharding trades a hard scaling limit for a large increase in complexity:
- Cross-shard queries: a query spanning shards must fan out and merge results in the application. Joins across shards are painful or impossible.
- Transactions: atomic writes across shards require distributed transaction protocols, which are slow and complex. Design so that a transaction stays within one shard.
- Rebalancing: adding a shard means moving data. Consistent hashing reduces how much data moves when the shard count changes.
- Unique IDs: auto-increment per shard collides. Use UUIDs or a dedicated ID generation scheme.
-- easy: single-shard query (shard key present)
SELECT * FROM orders WHERE user_id = 42;
-- hard: no shard key, must hit every shard
SELECT * FROM orders WHERE status = 'refunded';
Combining both
Production systems usually layer the two. Each shard is a primary with its own replicas:
Router (by shard key)
/ | \
Shard A Shard B Shard C
P + replicas P + replicas P + replicas
This gives write scaling from sharding and read scaling plus availability from replication within each shard.
Order of operations
Reach for these tools in order of increasing cost:
- Optimize first: indexes, query tuning, and connection pooling often remove the pressure entirely.
- Add a cache to absorb hot reads.
- Add read replicas when reads dominate.
- Shard only when writes or data size genuinely exceed one machine.
Sharding is powerful and nearly irreversible once live, so it should be the last resort, not the first instinct. Many systems serve very large workloads on a well-tuned primary with replicas and a cache, and never shard at all.