Handbooks / System Design / Chapter 6
Databases, Replication and Sharding
7 pages · ~5 min✓ Reviewed
Builds on Caching. Next up: Storage: Blobs, Files and Search.
Replication and Partitioning Mental Model
1. Two Different Tools
| Replication | Partitioning | |
|---|---|---|
| Data | Same data copied on many nodes | Different slice on each node |
| Scales | Reads, availability | Writes, storage |
- Real systems combine both: every partition is replicated
- So one node holds several partitions' replicas
2. What Each One Fixes
| Fixes | Does NOT fix | |
|---|---|---|
| Replication | Read throughput, fault tolerance | Data or write rate beyond one machine |
| Partitioning | Dataset size, write throughput | Cross-partition joins, transactions, global secondary indexes |
3. Pick by Bottleneck
readswrites / sizeall three
Leader-Follower Replication
1. How Writes Flow
- Client writeleader only
- Leaderappends WAL / binlog
- Log shippedto every follower
- Followersapply in order
- Followers apply the log in order, so they match the leader
2. Sync, Async, Semi-sync
| Ack when | Win | Risk |
|---|
Read Replicas and Replication Lag
1. Replicas and Lag
- Replicas serve SELECT only; writes go to the leader
- Split reads and writes in a proxy or in app code
- Replication lag = delay from leader commit to follower visibility
- Async replicas give eventual consistency
- App
- Proxyread/write split
- Leaderwrites
- ReplicasSELECTs
2. Lag Anomalies
Multi-Leader Replication
1. What and Why
- Many nodes accept writes and replicate to each other
- Used for multi-datacenter, offline-capable clients, collaborative editing
- Benefit: local-latency writes per region; survives a datacenter outage
- Cost: write conflicts
2. Write Conflicts
- Leader Asets x=1
- Leader Bsets x=2
- Replicateeach to the other
- Conflictsame key, two values
Partitioning, Sharding and Consistent Hashing
1. Range vs Hash
| Range | Hash mod N | |
|---|---|---|
| Layout | Contiguous key ranges | hash(key) mod N |
| Good | Fast range scans | Even load |
| Bad | Timestamps make a hot partition | No range queries; new N remaps almost every key |
Replication and Sharding Cheat Sheet
1. Pick the Tool
| Bottleneck | Pick |
|---|---|
| Reads | Add read replicas |
| Writes or data size | Shard (partition) |
| Multi-region writes | Multi-leader or leaderless, with conflict handling |
2. Sync Modes and Lag
Check yourself
Async replication. The leader acks a write, then crashes before shipping it. A follower is promoted. Is the write there?
- No: the write is lost, though the client was told it succeeded
- Sync or semi-sync replication keeps one up-to-date copy
A user posts a comment, reloads, and it is missing. Another reload shows it. Name the anomaly and the fix.
- Read-your-writes violation: the read hit a lagging replica
- Read a user's own recent writes from the leader