CAP Theorem and Consistency Models

Understand CAP and PACELC, strong vs eventual consistency, quorums, and the basics of consensus and distributed transactions.

Advanced · about 5 hours · difficulty 4/5

Learn first: Scaling Databases: Replication, Partitioning and Sharding

Once data lives on several machines, networks fail and clocks disagree. This topic gives you the language to discuss those trade-offs precisely rather than hand-waving.

CAP, stated correctly

  • Consistency: every read sees the latest write (linearizability).
  • Availability: every request to a non-failed node gets a response.
  • Partition tolerance: the system keeps working despite lost messages between nodes.
  • Partitions will happen, so the real choice during a partition is CP (refuse some requests to stay consistent) or AP (answer with possibly stale data). A bank balance leans CP; a like counter leans AP.
  • PACELC adds: even without a partition, you trade latency vs consistency.

Consistency models

  • Strong / linearizable: behaves like one copy.
  • Eventual consistency: replicas converge if writes stop. Needs conflict handling (last-write-wins, version vectors, CRDTs).
  • Practical middle grounds: read-your-own-writes, monotonic reads, causal consistency.
  • Quorums: with N replicas, W write acks and R read replies, R + W > N guarantees reads overlap the latest write.

Consensus and coordination

  • Consensus algorithms like Raft and Paxos let nodes agree on a leader or a log despite failures; ZooKeeper and etcd provide this as a service (leader election, locks, config).
  • Distributed transactions: two-phase commit (2PC) is blocking and fragile; microservices often use the Saga pattern with compensating actions instead.
  • Clocks: do not rely on wall-clock ordering across machines; logical clocks exist for this.

Good enough to move on: for any feature you can state whether it should be CP or AP and why, explain R + W > N, and describe how a Saga undoes a failed multi-service order.

Key concepts

  • CAP theorem
  • PACELC
  • Strong vs eventual consistency
  • Read-your-writes and causal consistency
  • Quorums (R + W > N)
  • Leader election and Raft
  • Two-phase commit vs Saga
  • Conflict resolution and CRDTs

Mini project

Write a short design note for three features (wallet balance, shopping cart, social feed likes) choosing CP or AP for each with justification, then play the Raft visualisation and explain in your own words how a new leader is elected after a crash.

Check yourself

With 5 replicas, what R and W values give strong consistency while tolerating one slow node on both reads and writes?

Free resources