The CAP theorem and consistency models
MediumDistributed systemsCAPConsistency
What does the CAP theorem say, and what consistency models do distributed systems offer?
TL;DR
CAP says that when a network partition happens (and in distributed systems it will), a system must choose between Consistency (every read sees the latest write, or gets an error) and Availability (every request gets a response, possibly stale). You can't give up partition tolerance, so the real choice is CP vs AP during a partition. PACELC adds the everyday trade-off: else, when there's no partition, you trade latency vs consistency.
Key points
- CP examples: etcd, ZooKeeper, a single-leader SQL database, Spanner. They refuse some requests during a partition to stay correct.
- AP examples: Cassandra and DynamoDB (by default), DNS. They keep answering and reconcile later.
- Consistency models, from strong to weak:
- Linearizable (strong): behaves like one copy; every read sees the latest write.
- Read-your-writes: you always see your own updates. Essential for user-facing UX.
- Monotonic reads: you never see time go backwards.
- Eventual: replicas converge if writes stop.
- Quorums tune it: with N replicas, reads from R and writes to W where R + W > N overlap, giving up-to-date reads.
- Pick per feature: payments and inventory need strong consistency; like counts and feeds can be eventual.
Example
- A user changes their profile name, refreshes, and sees the old name because the read hit a lagging replica. Fix with read-your-writes: route that user's reads to the leader for a few seconds, or read by a version token.
Common follow-ups
- Is a single PostgreSQL server CP or AP? CAP describes distributed systems; a single node has no partitions. With async replicas, reading from replicas gives eventual consistency.
- How do AP systems resolve conflicts? Last-write-wins timestamps, vector clocks, or CRDTs that merge automatically.
What interviewers look for
Tip
State CAP correctly (the choice only bites during a partition), mention PACELC, and choose consistency per feature with an example.
- Red flag: "pick any two of C, A and P" as if dropping P were an option.