Lesson 8 of 38Building blocks
Consistency and CAP
Explain CAP and PACELC honestly, pick a consistency model, do quorum math, resolve conflicts, and make retries safe with idempotency.
Once your data lives on more than one machine, a hard question appears: when two copies disagree, which one does a user see? A bank and a social feed answer it differently, and both answers are correct for their product. This lesson gives you the vocabulary (CAP, PACELC, consistency models, quorums) to make that choice on purpose, and the tool (idempotency) that keeps retries from charging someone twice.
CAP, in honest terms
The CAP theorem talks about three properties of a replicated system:
- Consistency (C): every read sees the most recent write, as if there were only one copy. (This is a stricter idea than the C in ACID.)
- Availability (A): every request to a working node gets a real answer, not an error.
- Partition tolerance (P): the system keeps running when the network between nodes drops messages.
The popular summary "pick two of three" is misleading. Networks between machines and data centers do fail, so partition tolerance is not optional. The honest version is: when a partition happens, you must choose between consistency and availability. When there is no partition, you can have both.
Step through a partition between two data centers.
Normal day: Ada sets the stock of an item to 0. The US replica copies it to the EU replica within milliseconds.
Which is right depends on the product. A bank balance or a seat reservation should prefer C: an error is better than selling the same seat twice. A like count, a feed, or a shopping cart usually prefers A: a slightly old answer beats an error page.
None picked yet
PACELC: the part CAP leaves out
Partitions are rare. What you pay for consistency every day is latency. PACELC says: if there is a Partition, choose A or C; Else (normal operation), choose Latency or Consistency. Waiting for a replica in another region to confirm every write gives consistency but adds a cross-region round trip (80+ ms) to every write.
| System | During a partition | Normal operation |
|---|---|---|
| Cassandra, DynamoDB (default settings) | Available | Low latency (eventual consistency) |
| Google Spanner, CockroachDB | Consistent | Consistent (pays latency for it) |
| Postgres with async replicas | Leader stays consistent; replicas may be stale | Low latency; replicas lag |
Many systems are tunable: Cassandra and DynamoDB let you ask for a strongly consistent read on a per-request basis, paying more latency for that one read.
PACELC in practice: what the else branch costs
The "else" branch is where you spend your engineering time, because it applies to every request on every normal day. The trade is simple to state: a write that waits for more replicas is safer and slower. A write is only as fast as the slowest replica it has to wait for.
Press Run (⌘ Enter) to see what happens.The jump from 3 ms to 65 ms is the moment the write has to leave the region. That cliff is why most systems keep a synchronous quorum inside one region (three availability zones are close enough to wait for) and replicate asynchronously across regions. Systems that promise strong consistency across regions, like Spanner and CockroachDB multi-region tables, pay a cross-region round trip on writes and design hard to hide it (placing leaders near the writers, letting reads be served locally).
Real knobs you will meet:
- DynamoDB: reads are eventually consistent by default.
ConsistentRead=truegives a strongly consistent read, at twice the read capacity cost and not on global secondary indexes. - Cassandra: consistency level per query:
ONE,QUORUM,LOCAL_QUORUM(a quorum within the local data center only, the usual production choice),ALL. - Postgres:
synchronous_commitdecides what a commit waits for, fromoff(not even the local disk flush) throughon(a synchronous standby has flushed it) toremote_apply(a standby has applied it, so a read there sees it). It can be set per transaction, so a payment can wait and a page-view log can not.
Consistency models
"Consistent" comes in strengths. From strongest to weakest:
- Strong consistency (linearizability): once a write completes, every later read anywhere sees it. Feels like one machine.
- Read-your-writes: you always see your own writes, though others may briefly see older data.
- Monotonic reads: you never see data go backwards in time (seeing a comment, refreshing, and the comment vanishing).
- Eventual consistency: if writes stop, all copies eventually agree. Until then, reads may return anything recent.
Here is eventual consistency breaking read-your-writes, the most common complaint users actually notice.
POST comment 'Great post!'
And the fix: route the writer's next reads to the leader (or to a replica that has caught up).
POST comment 'Great post!'
Linearizability vs serializability
These two words sound alike and get swapped constantly, including by experienced engineers. They answer different questions.
Linearizability is about one object and real time. Once a write to x completes, every read that starts afterwards, from any client on any replica, returns that value or a newer one. The system behaves as if there is a single copy and every operation takes effect at one instant between its start and its end. It is the "C" in CAP. Leader election, distributed locks, and "is this username taken?" checks need it.
Serializability is about transactions touching many objects. The outcome of running transactions concurrently equals the outcome of running them one at a time in some order. Nothing says that order matches real time. It is the "I" (isolation) in ACID, and it protects invariants that span rows, like "at least one doctor is on call".
| Linearizability | Serializability | |
|---|---|---|
| Scope | Single object (a key, a register) | Transactions over many objects |
| Guarantee | Respects real-time order | Equivalent to some serial order |
| Belongs to | Distributed systems, CAP's C | Databases, ACID's I |
| Classic failure without it | Reading a stale value from a lagging replica | Write skew, lost updates |
| Example systems | etcd, ZooKeeper (for writes), a single-leader read | Postgres SERIALIZABLE, MySQL SERIALIZABLE |
The combination of both is strict serializability: transactions appear to run one at a time, in real-time order. Spanner calls this external consistency, and it is what CockroachDB and FoundationDB aim for too.
The practical traps:
- Postgres's default is Read Committed, and MySQL InnoDB's is Repeatable Read. Neither default is serializable. Postgres Repeatable Read is snapshot isolation: it prevents phantoms but still allows write skew. Two doctors each check "is someone else on call?", both see yes, both go off call, and nobody is on call. Only
SERIALIZABLE(or explicit locking such asSELECT ... FOR UPDATE) stops it. - A serializable primary with async read replicas is not linearizable for reads: a replica can return a value that was overwritten a second ago. Each transaction is still correctly isolated; it is just reading the past.
Match each guarantee to what it promises.
Session guarantees in practice
Full linearizability is expensive, but users rarely need it. What they need is for the system to make sense from their own point of view. Four session guarantees describe exactly that, scoped to one user's session:
- Read-your-writes: after I write, my reads see it.
- Monotonic reads: once I have seen a value, I never see an older one. Without this, a comment appears, you refresh, it vanishes, you refresh, it is back, because each refresh hit a different replica.
- Monotonic writes: my writes are applied in the order I made them.
- Writes-follow-reads: if I reply to a comment I read, my reply is ordered after that comment everywhere.
Three ways teams implement them, from simplest to most precise:
- Sticky to the primary after a write. Set a short-lived cookie or session flag on write ("wrote at 12:00:05"), and route that user's reads to the leader for the next few seconds, longer than your normal replication lag. Easy, but you have to guess the window, and a lag spike beats the guess.
- Pin each user to one replica. Hash the user id to choose a replica. Their reads may be stale, but never go backwards, which gives monotonic reads for free. If the replica fails, they move and may see a jump.
- Carry a session token. After a write, return the leader's log position (in Postgres, the WAL LSN from
pg_current_wal_lsn()). The client sends it with later reads. The router sends the read to any replica whose replayed position (pg_last_wal_replay_lsn()) is at least that far, or waits briefly, or falls back to the leader. MongoDB's causally consistent sessions and Azure Cosmos DB's session consistency level do this for you with a token the driver passes along.
The token approach is the one to describe in an interview: it is precise (no guessing a time window), keeps most reads on replicas, and works across any number of replicas.
Quorums: R + W > N
Leaderless databases keep N copies of each item. A write is sent to all N and succeeds when W of them confirm. A read asks R replicas and takes the newest version among the answers.
If R + W > N, every read set and every write set share at least one replica, so a read always includes at least one copy of the latest write.
Write x = 7 (version 2). The coordinator sends it to all 3 replicas.
Check the overlap rule by brute force: this tries every possible set of writers against every possible set of readers.
Press Run (⌘ Enter) to see what happens.Tuning W and R trades latency and availability between reads and writes. W = N, R = 1 makes reads fast but a write fails if any replica is down. W = 1, R = 1 is fast and highly available but only eventually consistent. N = 3, W = 2, R = 2 is the common balanced choice: it tolerates one replica down for both reads and writes.
Conflict resolution: LWW, vector clocks, and CRDTs
Multi-leader and leaderless systems accept writes in more than one place. During a partition, or just through bad timing, two replicas can each accept a different write to the same key. When they sync, the system needs a rule for what the value becomes.
Last write wins (LWW). Attach a timestamp to every write and keep the one with the highest. Cassandra does this per column by default. It is simple, it always converges, and it silently throws away data. Two users each add an item to a shared cart at the same moment; the later write replaces the whole cart, and one item is gone. Worse, "later" is decided by wall clocks on different machines, which drift. A server whose clock runs 2 seconds fast wins every conflict for 2 seconds, even against writes that really happened after it. LWW is fine when writes are whole replacements and losing one is acceptable (the latest GPS position of a delivery van). It is wrong for anything that accumulates.
Vector clocks (and their cousins, version vectors) detect conflicts instead of hiding them. Each replica keeps a counter, and every version of a value carries the set of counters it has seen, like {us: 3, eu: 1}. If one version's counters are all greater than or equal to the other's, it is newer and wins. If each is ahead on a different counter, the writes were concurrent, and the system keeps both as siblings for the application (or the next reader) to merge. The original Dynamo paper used this for Amazon's shopping cart: merging two siblings meant taking the union of the items. Correct, but you have pushed merge logic into every client.
CRDTs (conflict-free replicated data types) are data types designed so that any two replicas can always merge automatically, in any order, any number of times, and end up identical. The trick is a merge function that is commutative, associative, and idempotent. The simplest is a G-counter (grow-only counter): each replica increments only its own slot, and merge takes the maximum of each slot. The value is the sum.
Press Run (⌘ Enter) to see what happens.LWW reports 14 and quietly loses the 3 US likes. The G-counter reports 17, and merging again changes nothing, which is why retries and repeated syncs are harmless. Other CRDTs build on the same idea: a PN-counter is two G-counters (increments and decrements), an OR-set lets items be added and removed concurrently, and sequence CRDTs power collaborative editors (Automerge and Yjs are popular libraries). Riak and Redis's active-active geo-replication use CRDTs under the hood.
CRDTs are not free. Metadata grows with the number of replicas and with deletes, and they only work for operations that can be made to commute. "Withdraw $50 only if the balance stays positive" cannot: it needs coordination, which brings you back to a leader or consensus.
Three replicas hold these G-counter states. What value does the counter show after all three are merged?
a = {"r1": 5, "r2": 2, "r3": 0}
b = {"r1": 3, "r2": 4, "r3": 1}
c = {"r1": 5, "r2": 1, "r3": 6}
merged = {r: max(a[r], b[r], c[r]) for r in a}
print(sum(merged.values()))Idempotency: making retries safe
Networks fail in the worst way: a request can succeed on the server but the response gets lost. The client sees a timeout and retries. If the request was "charge $30", the user is now charged twice.
An operation is idempotent if doing it twice has the same effect as doing it once. PUT /users/42 {name: "Ada"} and DELETE /items/7 are naturally idempotent. POST /payments and "add 1 to the counter" are not.
The standard fix is an idempotency key: the client generates a unique id for each logical operation and sends it with every attempt. The server stores the key with the result, and if it sees the same key again, it returns the stored result instead of doing the work again. Stripe's API works exactly this way with an Idempotency-Key header.
POST /charges, Idempotency-Key: 8f3a
Press Run (⌘ Enter) to see what happens.Without idempotency, a $30 charge is retried twice after timeouts (three attempts, all reached the server). Starting balance 100?
balance = 100 for attempt in range(3): balance -= 30 print(balance)
- CAP
- During a network partition, a replicated system must choose consistency (refuse) or availability (answer, maybe stale).
- PACELC
- If partitioned, choose A or C; else, choose low latency or consistency.
- eventual consistency
- Replicas may disagree for a while but converge once writes stop.
- read-your-writes
- A user always sees their own updates, even if others briefly do not.
- quorum
- Reads ask R of N replicas, writes wait for W. If R + W > N, reads always see the latest write.
- idempotency key
- A unique id per operation so retries return the stored result instead of repeating the side effect.
- linearizability
- Single-object guarantee: once a write completes, every later read anywhere sees it, as if there were one copy.
- serializability
- Transaction guarantee: concurrent transactions end as if they ran one at a time in some order.
- session token
- A log position returned after a write that later reads carry, so they only hit replicas that have caught up.
- vector clock
- Per-replica counters attached to each version, used to tell a newer write from a concurrent one.
- CRDT
- A data type whose replicas can always merge automatically, in any order, and converge to the same value.