Distributed Data — CAP, Replication & Sharding
CAP and PACELC, consistency models from linearizable to eventual, replication (single-leader, multi-leader, leaderless quorums), replication lag anomalies, failover and split brain, partitioning/sharding strategies, consistent hashing, rebalancing, hot keys, secondary indexes, and distributed transactions (2PC, sagas).
Why distribute data?
- Scalability — more data or traffic than one machine can handle.
- Availability — keep working when machines, racks or regions fail.
- Latency — keep data close to users around the world.
Two tools: replication (same data on many nodes) and partitioning/sharding (different data on different nodes). Everything else is managing the consequences.
CAP theorem
| Choose under partition | Examples | Typical use | |
|---|---|---|---|
| CP | consistency | ZooKeeper, etcd, Consul, HBase, Spanner, CockroachDB | coordination, locks, metadata, money |
| AP | availability | Cassandra, DynamoDB (default), Riak, CouchDB, DNS | carts, feeds, telemetry, sessions |
PACELC adds the everyday trade-off: Else (no partition), choose Latency or Consistency. Cross-region strong consistency costs round trips on every write.
Consistency models (strongest → weakest)
| Model | Guarantee | Cost |
|---|---|---|
| Linearizable | behaves like a single copy, real-time order | coordination on every op; unavailable under partition |
| Sequential | single total order consistent with each client's order | still coordination |
| Causal | cause-before-effect preserved everywhere | track dependencies; available under partition |
| Read-your-writes / monotonic reads | per-session sanity | session routing or version tracking |
| Eventual | replicas converge if writes stop | cheapest |
Replication
Single-leader (primary–replica)
| Mode | Leader waits for | Durability | Latency |
|---|---|---|---|
| Synchronous | all (or one designated) follower | no loss on leader failure | higher; a slow follower stalls writes |
| Semi-synchronous | at least one follower | at most tiny loss | moderate |
| Asynchronous | nothing | recent writes lost on failover | lowest |
Failover (promote a follower when the leader dies) is where things go wrong: choosing the most up-to-date follower, losing un-replicated writes, split brain (two leaders), and timeouts that are too eager (failover during a GC pause) or too slow. Use consensus-based managers (Patroni + etcd for Postgres, orchestrators, cloud-managed failover) and fencing.
Multi-leader
Several leaders accept writes (e.g. one per data centre) and replicate to each other. Good for multi-region writes and offline clients (each device is a "leader"), but write conflicts are inevitable:
| Conflict resolution | Idea | Risk |
|---|---|---|
| Last-write-wins (LWW) | highest timestamp wins | silently loses data; clock skew |
| Merge function | application-defined (union of cart items) | needs domain logic |
| CRDTs | data types that merge deterministically (counters, sets, sequences) | limited operations, metadata overhead |
| Record and ask | keep siblings, let the app/user resolve | complexity |
Leaderless (Dynamo-style)
Clients (or a coordinator) write to N replicas and read from several; quorums decide success.
Supporting mechanisms: read repair, anti-entropy with Merkle trees, hinted handoff, sloppy quorums, and version vectors to detect concurrent writes.
Partitioning (sharding)
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Range | key ranges per shard (A–F, G–M…; by date) | efficient range scans | hot spots with sequential keys (timestamps) |
| Hash | hash(key) decides | even distribution | range queries hit every shard |
| Consistent hashing | hash ring + virtual nodes | minimal movement on resize | range queries scatter |
| Directory / lookup | a service maps key → shard | flexible, move tenants individually | extra lookup; directory is critical |
| Geographic | by region/country | data residency, latency | uneven load |
| Compound | (tenant_id, hash(id)) | co-locate tenant + spread big tenants | complexity |
Consistent hashing
import bisect, hashlib
class ConsistentHashRing:
def __init__(self, nodes=(), vnodes=150):
self.vnodes = vnodes
self.ring = [] # sorted hash positions
self.owner = {} # position -> node
for n in nodes:
self.add(n)
def _h(self, s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
def add(self, node):
for i in range(self.vnodes):
p = self._h(f"{node}#{i}")
bisect.insort(self.ring, p)
self.owner[p] = node
def remove(self, node):
for i in range(self.vnodes):
p = self._h(f"{node}#{i}")
self.ring.remove(p)
del self.owner[p]
def get(self, key):
i = bisect.bisect(self.ring, self._h(key)) % len(self.ring)
return self.owner[self.ring[i]]
ring = ConsistentHashRing(["db-a", "db-b", "db-c"])
print(ring.get("user:42"))
Rebalancing
- Fixed number of partitions (create many more partitions than nodes, e.g. 1,024; move whole partitions when nodes join) — Kafka, Elasticsearch, Riak, Couchbase, Redis Cluster slots.
- Dynamic splitting — split a range when it grows too big (HBase regions, MongoDB chunks, Spanner splits, DynamoDB partitions).
- Move data in the background, throttle, then switch routing atomically; avoid automatic rebalancing storms during failures.
Hot keys and skew
A single celebrity user, viral post or popular product can overload one shard regardless of the hash. Mitigations: key salting/splitting (post:123#0..9, aggregate on read), caching in front, dedicated shards for whales, request coalescing, write buffering/aggregation (count increments in memory and flush).
Secondary indexes on sharded data
| Approach | Writes | Reads by secondary attribute |
|---|---|---|
| Local (document-partitioned) index per shard | single shard | scatter/gather to all shards |
| Global (term-partitioned) index sharded by the indexed value | multi-shard (often async) | one shard |
Cross-shard queries
Avoid in hot paths: co-locate data by tenant/user, denormalise, or maintain read models. Use scatter-gather with limits and timeouts when unavoidable; heavy analytics belong in a warehouse.
Distributed transactions
Two-phase commit (2PC)
Sagas
A saga splits a business transaction into local transactions with compensations:
| Step | Action | Compensation |
|---|---|---|
| 1 | create order (PENDING) | cancel order |
| 2 | reserve inventory | release inventory |
| 3 | charge payment | refund |
| 4 | mark order CONFIRMED | — |
- Orchestration: a central saga orchestrator sends commands and tracks state (Temporal, AWS Step Functions, Camunda) — easier to reason about.
- Choreography: services react to each other's events — looser coupling, harder to follow.
- Requirements: idempotent steps, retries, compensations that can't fail permanently, and the transactional outbox to publish events reliably.
| 2PC | Saga | |
|---|---|---|
| Atomicity | yes | eventually (via compensation) |
| Isolation | yes (locks) | no — intermediate states visible |
| Availability | blocking on coordinator failure | non-blocking |
| Latency | locks held across round trips | each step commits locally |
| Typical use | inside distributed databases | across microservices |
Consensus (preview)
Leader election, distributed locks, configuration and transaction commit in modern distributed databases rely on consensus algorithms — Raft and Paxos — that replicate a log across a majority. Covered in depth in Distributed systems.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.