Guide / System design Fundamentals
5. Replication, sharding, CAP and consistency
5.1 Replication#
| Model | How | Pros | Cons |
|---|---|---|---|
| Single-leader (primary-replica) | All writes to primary; replicas stream its log | Simple, no write conflicts | Primary is the write bottleneck; failover can lose async writes |
| Multi-leader | Several nodes accept writes (often one per region) | Low-latency local writes, region survival | Write conflicts: need last-write-wins, CRDTs, or app merge logic |
| Leaderless (Dynamo-style) | Client writes to W of N replicas, reads R of N | No failover needed, highly available | Conflicts, read repair, hinted handoff, sloppy quorums |
Sync vs async replication: synchronous = no data loss on failover but write latency rises and a slow replica blocks writes; asynchronous = fast but replicas lag. A common middle ground is semi-sync (one replica must ack).
Replication lag problems and fixes:
- Read-your-writes: the user updates their profile and then sees the old one from a replica → read from the primary for N seconds after a write, or route that user’s reads by session to the primary, or carry the write’s LSN and wait for a replica to catch up.
- Monotonic reads: the user sees new data, then old data from a different replica → pin the user to one replica (hash user ID).
- Consistent prefix: the answer appears before the question → keep causally related writes in the same partition.
Failover: detect the primary is dead (heartbeat timeout), promote the most up-to-date replica, repoint clients. Danger: split brain (two primaries) → use fencing (STONITH, epoch numbers) and a consensus system (etcd/ZooKeeper, Patroni for Postgres) to pick one leader.
5.2 Sharding (partitioning)#
| Strategy | How | Good | Bad |
|---|---|---|---|
| Range | user_id 1–1M → shard 1 | Range scans efficient | Hot spots (new IDs, recent dates all on one shard) |
| Hash | hash(key) mod N | Even distribution | Range queries scatter; changing N reshuffles everything |
| Consistent hashing | Keys and nodes on a ring, with virtual nodes | Adding a node moves only ~1/N of keys | Slightly more complex routing |
| Directory / lookup | A service maps key → shard | Flexible, can move tenants individually | Lookup service is a dependency to scale and cache |
| Geo | By region/country | Data residency, locality | Uneven region sizes |
Choosing the shard key is the real question: high cardinality, even load, and most queries should include it. For an e-commerce orders table, user_id makes “my orders” a single-shard query but “all orders of seller X” scatter-gather → keep a secondary copy keyed by seller_id (via CDC), or a global secondary index.
Problems sharding creates: cross-shard joins (denormalize or join in the app), cross-shard transactions (avoid, or use sagas), global unique IDs (Snowflake), hot shards (split, add a salt), resharding (consistent hashing, or pre-split into many logical shards, e.g. 4,096, mapped onto fewer physical nodes, then move logical shards). Multi-tenant SaaS (like payroll for 300 companies) usually shards by tenant_id, with big tenants on dedicated shards.
5.3 CAP theorem#
During a network Partition, a distributed system must choose Consistency (every read sees the latest write, or errors) or Availability (every request gets a non-error response, possibly stale). Partitions will happen, so the real choice is CP vs AP during a partition.
- CP examples: Spanner, etcd/ZooKeeper, HBase, MongoDB with majority writes, a Postgres primary. Use for payments, inventory reservations, leader election, config.
- AP examples: Cassandra, DynamoDB (default eventually consistent reads), Riak, DNS, CDN caches. Use for feeds, likes, view counts, product reviews, shopping cart adds.
- Mixed per feature: one system can be CP for checkout and AP for product browsing. Say this in interviews.
PACELC extends CAP: if Partition → A or C; Else (normal operation) → Latency or Consistency. DynamoDB/Cassandra are PA/EL; Spanner is PC/EC.
5.4 Consistency models (strongest to weakest)#
- Linearizable: behaves like one copy; every read sees the latest committed write. Needed for locks, leader election, unique usernames.
- Sequential / serializable: a single total order of operations (serializable is about transactions, linearizable about single objects).
- Causal: if A caused B, everyone sees A before B; concurrent operations may differ. Good for comments and chat.
- Read-your-writes, monotonic reads: session guarantees.
- Eventual: replicas converge if writes stop. Good for counters, likes, caches.
Quorums: N replicas, W write acks, R read replicas; R + W > N means read and write sets overlap, so reads see the latest write (still with edge cases under sloppy quorum and concurrent writes).
Conflict resolution: last-write-wins (simple, loses data; clock skew), version vectors (detect concurrency, let app merge), CRDTs (data types that merge automatically: G-counters, OR-sets; used in collaborative editing and shopping carts).
5.5 Multi-region architecture#
Why go multi-region: survive a region outage, lower latency for users far away, and meet data-residency laws (e.g. India’s DPDP Act, GDPR in the EU). The cost: cross-region latency (~50–250 ms), harder consistency, double infrastructure, complex operations.
| Model | How | RPO / RTO | Trade-offs |
|---|---|---|---|
| Backup & restore | Backups copied to another region | Hours / hours | Cheapest; long outage |
| Active-passive (warm standby) | One region serves; data replicated async to a standby that can be promoted | Seconds–minutes of data / minutes | Simple writes (one leader); failover must be practised; async replication loses the last few writes |
| Active-active, partitioned by user/tenant (“home region”) | Each user’s data lives in one home region; requests route there | Small / minutes for affected users | No write conflicts; good for residency; a user travelling far sees higher latency; failing over a home region still needs a replica |
| Active-active, multi-writer | Every region accepts writes for any data, replicating both ways | Near zero / near zero | Write conflicts (resolve with LWW, CRDTs or app merge); hardest to reason about |
| Globally consistent DB | Spanner, CockroachDB, Aurora DSQL-style distributed SQL with consensus across regions | Zero / automatic | Strong consistency everywhere at the cost of cross-region write latency and price |
Design steps to talk through:
- Classify data by consistency need. Money, inventory and auth → single writer (home region or globally consistent DB). Catalogue, content, likes → replicate everywhere, eventually consistent. Caches and sessions → per region.
- Routing: GeoDNS or anycast load balancers (Route 53 latency routing, Cloudflare, Global Accelerator) send users to the nearest healthy region; route writes to the data’s home region.
- Replication: DB-native cross-region replicas, Kafka MirrorMaker / cluster linking for event streams, object storage cross-region replication for blobs.
- Conflict handling if multi-writer: per-field LWW with hybrid logical clocks, CRDT counters/sets for carts and likes, or route conflicting entity types to a single writer.
- Failover: health checks + automated DNS/traffic shift, with a human-approved switch for the database leader to avoid split brain; fencing old leaders; runbooks and regular game days.
- Residency: keep regulated data (PII, payments) in-region; only send anonymized or aggregated data across borders.
Cell-based architecture: split the system into many independent “cells” (each a full copy of the stack serving a subset of users/tenants), with a thin routing layer mapping users to cells. A bad deploy or overload hits one cell, not everyone (smaller blast radius); scale by adding cells. Used by large SaaS and cloud providers. Senior-level bonus point.
Follow-ups: “What happens to in-flight writes when a region dies?” (with async replication, recent writes may be lost or delayed — reconcile when it returns; idempotency keys prevent double-processing on retry in the new region). “How do you avoid both regions thinking they’re primary?” (single source of leadership via consensus or a manual switch, plus fencing tokens/epochs).
5.6 Resharding and rebalancing#
You will outgrow your shard count. Options:
| Approach | How | Trade-off |
|---|---|---|
| Pre-shard into many logical shards | Start with e.g. 1,024 logical shards mapped onto 8 physical nodes; add nodes by moving whole logical shards | Best practice: no rehashing of keys, only moving shards |
| Consistent hashing / hash slots | Moving a few slots or ring ranges to a new node (Redis Cluster 16,384 slots, Cassandra vnodes) | Needs online migration tooling |
| Directory-based | A lookup service maps entity → shard | Flexible (move one tenant), but the directory is a critical dependency and must be cached |
| Range-based | Contiguous key ranges (HBase, Spanner, CockroachDB split and merge automatically) | Range scans work, hot ranges for sequential keys |
Online resharding procedure: (1) create target shard, (2) copy data (snapshot) while capturing changes (CDC), (3) catch up, (4) pause writes for that key range briefly or use dual-writes, (5) flip routing, (6) verify and delete the source copy. Always have a rollback and compare counts or checksums.
5.7 Cross-shard queries and transactions#
- Avoid them by design: choose a shard key that keeps related data together (
tenant_id,user_id); co-locate child tables with the parent. - Scatter-gather: query all shards and merge (top-K, counts). Latency = slowest shard; fine for admin, poor for the hot path. Maintain a global secondary index (separate table or search index) for queries by other attributes, accepting eventual consistency.
- Cross-shard transactions: two-phase commit (slow, blocking, available in Spanner/Cockroach/Vitess with limits), or sagas with compensations. Prefer designing so each business operation touches one shard.
- Global uniqueness (email unique across shards): a lookup table keyed by email on one shard, inserted first (the unique constraint decides), or a dedicated service.
- Hot shards: celebrity tenant or key → split that entity, give it a dedicated shard, or add a random suffix and fan out reads.
5.8 Replication details worth knowing#
- Sync vs async vs semi-sync: sync waits for a replica (no loss, higher latency, availability depends on the replica); async is fast but a failover can lose the last writes; semi-sync waits for at least one.
- Replication lag causes: large transactions, replica under-provisioned, long-running queries on replicas, network. Measure in seconds and bytes.
- Failover hazards: split brain (two primaries accept writes) prevented by fencing (STONITH, epoch/term numbers) and quorum; promote the most advanced replica; reconfigure clients through a proxy or DNS.
- Leaderless (Dynamo-style) quorums: N replicas, W write acks, R read acks;
R + W > Ngives read-your-latest; sloppy quorums and hinted handoff trade consistency for availability; read repair and anti-entropy converge replicas.
Most asked questions#
1. Replication vs sharding? Replication copies the same data to several nodes (availability, read scaling). Sharding splits different data across nodes (write and storage scaling). Use both.
2. How do you choose a shard key? High cardinality, even distribution, appears in most queries, rarely changes; avoid monotonically increasing keys alone.
3. Hash vs range sharding? Hash spreads load evenly but loses range scans; range supports scans but risks hot ranges.
4. Explain CAP and PACELC. In a partition choose consistency or availability; otherwise latency vs consistency.
5. What is replication lag and how do you handle it? Replicas apply changes later than the primary; route read-after-write to the primary, use session stickiness or LSN waiting, alert on lag.
6. How do you do a multi-region design? Active-passive (simple, higher RTO) or active-active (conflict handling, home-region writes, CRDTs), with data locality and replication choice per dataset.
Senior-level questions#
1. “How would you migrate from one shard key to another?” New cluster with the new key, CDC dual-write/backfill, shadow reads, gradual cutover per tenant, rollback path; it is a multi-month project, so choose keys carefully.
2. “One shard is hot even though the key is high cardinality.” Skewed usage (a power user), temporal skew (new IDs), or a hot secondary index. Split the heavy entity, salt, cache, or dedicate a shard.
3. “Failover happened and some users lost data.” Async replication; add semi-sync for critical data, track replicated LSN, reconcile from logs, and design clients to retry idempotently.
4. “How do you guarantee unique emails with sharding by user_id?” A separate unique-index table sharded by email (insert first, then user row), or a global service; sagas to clean up on failure.
5. “Design cross-region reads with a 50 ms budget.” Local read replicas or caches in each region, follower reads with bounded staleness, write forwarding to the home region, CRDT counters, and user-to-region affinity.
Quiz#
1. With N=3, which W and R give strong read-your-writes?
Any with R + W > N, for example W=2 and R=2.
2. Why pre-shard into many logical shards?
You can add machines by moving whole logical shards without rehashing keys.
3. How is split brain prevented?
Quorum-based leader election, epoch/term numbers and fencing so a stale leader’s writes are rejected.
4. Why are scatter-gather queries a hot-path problem?
Latency is bounded by the slowest shard and load multiplies by the shard count.
5. Async vs sync replication trade-off?
Async: low latency, possible data loss on failover. Sync: no loss, higher latency and dependence on replica availability.