ayushsalampuriya.xyzRevise

HLD · Theory

CAP Theorem & Consistency Models

Trade-offs when a distributed system faces network partitions.

1. CAP theorem (correct framing)

During a network partition, a distributed data store cannot simultaneously provide all three:

In practice P is mandatory (networks fail). So you choose CP or AP during a partition.

Interview correction: CAP is not "pick 2 of 3 always" — it's specifically under partition. In normal operation you can have all three to a degree.

2. CP vs AP examples

ChoiceBehavior on partitionExample systems
CPReject writes/reads to avoid stale dataZooKeeper, etcd, HBase, traditional RDBMS with sync replication
APAccept reads/writes; reconcile laterCassandra, DynamoDB (configurable), DNS

Bank balance: Prefer CP — better to error than show wrong balance. Social like count: AP acceptable — eventual consistency OK.

3. Consistency models (spectrum)

4. PACELC extension

If Partition → choose A or C. Else (normal operation), choose Latency or Consistency.

Example: DynamoDB — AP under partition; in normal ops tunable (strong vs eventual read).

5. Quorum reads/writes (Dynamo-style)

N replicas. Write succeeds if W nodes ack; read consistent if R nodes read and W + R > N.

Example: N=3, W=2, R=2 → tolerate 1 node failure with strong-ish consistency.

6. Real interview scenario

Design a shopping cart across 2 data centers:

  1. Cart is per-user — route user to home DC (geo-DNS) for read-your-writes
  2. Cross-DC async replication for disaster recovery (eventual)
  3. Checkout hits payment service with strong consistency on inventory (CP, single leader)

Quick revision

  • CAP: Under partition, choose CP (consistent) or AP (available).
  • P is not optional in distributed systems.
  • Models: Strong → eventual; know read-your-writes for UX.
  • Quorum: W + R > N for read-write overlap.
  • Match product: Money = CP; likes/views = AP/eventual.