{}DSA Atlas

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).

Advanced10 interview questions

Why distribute data?

  1. Scalability — more data or traffic than one machine can handle.
  2. Availability — keep working when machines, racks or regions fail.
  3. 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

Side A Side B replica 1: x = 5 replica 2: x = 5 network partition client writes x = 7 here client reads x here CP choicereject/block the write or readuntil the partition heals AP choiceanswer x = 5 (stale);reconcile later
During a partition, a replica must either refuse (stay consistent) or answer with possibly stale data (stay available).
Choose under partitionExamplesTypical use
CPconsistencyZooKeeper, etcd, Consul, HBase, Spanner, CockroachDBcoordination, locks, metadata, money
APavailabilityCassandra, DynamoDB (default), Riak, CouchDB, DNScarts, 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)

ModelGuaranteeCost
Linearizablebehaves like a single copy, real-time ordercoordination on every op; unavailable under partition
Sequentialsingle total order consistent with each client's orderstill coordination
Causalcause-before-effect preserved everywheretrack dependencies; available under partition
Read-your-writes / monotonic readsper-session sanitysession routing or version tracking
Eventualreplicas converge if writes stopcheapest

Replication

Single-leader (primary–replica)

clients Leaderall writes Follower 1 (sync) Follower 2 (async) Follower 3 (async) writes reads (may be stale) WAL / binlog stream
All writes go to the leader, which streams its log to followers. Reads can be spread across followers.
ModeLeader waits forDurabilityLatency
Synchronousall (or one designated) followerno loss on leader failurehigher; a slow follower stalls writes
Semi-synchronousat least one followerat most tiny lossmoderate
Asynchronousnothingrecent writes lost on failoverlowest

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 resolutionIdeaRisk
Last-write-wins (LWW)highest timestamp winssilently loses data; clock skew
Merge functionapplication-defined (union of cart items)needs domain logic
CRDTsdata types that merge deterministically (counters, sets, sequences)limited operations, metadata overhead
Record and askkeep siblings, let the app/user resolvecomplexity

Leaderless (Dynamo-style)

Clients (or a coordinator) write to N replicas and read from several; quorums decide success.

write v2, W=2 read, R=2 replica A: v2 replica B: v2 replica C: v1 W + R = 4 > N = 3 → the read set always includes a replica with v2; C is fixed by read repair
Overlapping quorums: at least one replica in every read set has the latest acknowledged write.

Supporting mechanisms: read repair, anti-entropy with Merkle trees, hinted handoff, sloppy quorums, and version vectors to detect concurrent writes.

Partitioning (sharding)

StrategyHowProsCons
Rangekey ranges per shard (A–F, G–M…; by date)efficient range scanshot spots with sequential keys (timestamps)
Hashhash(key) decideseven distributionrange queries hit every shard
Consistent hashinghash ring + virtual nodesminimal movement on resizerange queries scatter
Directory / lookupa service maps key → shardflexible, move tenants individuallyextra lookup; directory is critical
Geographicby region/countrydata residency, latencyuneven load
Compound(tenant_id, hash(id))co-locate tenant + spread big tenantscomplexity

Consistent hashing

A B C A′ B′ C′ k1 k2 How it works • hash nodes and keys onto the same ring • a key is owned by the next node clockwise (k1 → B, k2 → B′) • each node appears many times (virtual nodes) → even load; a failed node's keys spread out Adding a node moves ~1/N of keys with modulo hashing (key % N), going from N=4 to N=5 moves ~80% of keys Used by: Dynamo, Cassandra, Riak, CDNs, memcached clients, load balancers (Maglev)
Primes mark virtual nodes of the same physical server.
Python
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

ApproachWritesReads by secondary attribute
Local (document-partitioned) index per shardsingle shardscatter/gather to all shards
Global (term-partitioned) index sharded by the indexed valuemulti-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)

Coordinator Orders DB Payments DB 1. PREPARE1. PREPARE vote YES (locks held, durable)vote YES 2. all YES → COMMIT; any NO → ABORT coordinator crash after PREPARE → participants are stuck holding locks (blocking)
2PC gives atomicity across nodes at the cost of blocking and latency.

Sagas

A saga splits a business transaction into local transactions with compensations:

StepActionCompensation
1create order (PENDING)cancel order
2reserve inventoryrelease inventory
3charge paymentrefund
4mark 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.
2PCSaga
Atomicityyeseventually (via compensation)
Isolationyes (locks)no — intermediate states visible
Availabilityblocking on coordinator failurenon-blocking
Latencylocks held across round tripseach step commits locally
Typical useinside distributed databasesacross 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

0 / 10 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.