Skip to content

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.

24 min read0/6 questions

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.

A network partition between regions
Ada (US)Ada (US)Replica USReplica USReplica EUReplica EUSam (EU)Sam (EU)writereplicateread

Normal day: Ada sets the stock of an item to 0. The US replica copies it to the EU replica within milliseconds.

1/5

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.

Quick checkPick all that apply
During a network partition, which systems should prefer consistency over availability?

None picked yet

Need a nudge? A hint rules out a wrong answer.

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.

SystemDuring a partitionNormal operation
Cassandra, DynamoDB (default settings)AvailableLow latency (eventual consistency)
Google Spanner, CockroachDBConsistentConsistent (pays latency for it)
Postgres with async replicasLeader stays consistent; replicas may be staleLow 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.

Pythonwrite_latency.py
# Round-trip time from a coordinator in us-east to each of 5 replicas, in msreplica_rtt = {"same AZ": 1, "other AZ 1": 2, "other AZ 2": 3, "us-west": 65, "eu-west": 80} def write_latency(w: int) -> int: # The write returns once the W fastest replicas have acknowledged. return sorted(replica_rtt.values())[w - 1] for w in range(1, 6): print(f"W={w}: write takes {write_latency(w):>2} ms")
Output
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=true gives 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_commit decides what a commit waits for, from off (not even the local disk flush) through on (a synchronous standby has flushed it) to remote_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.

Eventual consistency without read-your-writes
AdaLeaderReplicaPOST comment 'Great post!'201 CreatedGET /post/9/comments[] (no comment yet)replicate comment

POST comment 'Great post!'

1/5

And the fix: route the writer's next reads to the leader (or to a replica that has caught up).

Read-your-writes
AdaLeaderReplicaPOST comment 'Great post!'201 Created, wrote at log position 5012GET /post/9/comments[Great post!]

POST comment 'Great post!'

1/4

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

LinearizabilitySerializability
ScopeSingle object (a key, a register)Transactions over many objects
GuaranteeRespects real-time orderEquivalent to some serial order
Belongs toDistributed systems, CAP's CDatabases, ACID's I
Classic failure without itReading a stale value from a lagging replicaWrite skew, lost updates
Example systemsetcd, ZooKeeper (for writes), a single-leader readPostgres 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 as SELECT ... 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 the pairs0/4 matched

Match each guarantee to what it promises.

Choose an item, then its match on the other side.

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:

  1. 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.
  2. 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.
  3. 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.

Quick check
Users sometimes see a new reply appear, then disappear on refresh, then reappear. Reads go round robin across three replicas with different lag. Which guarantee is missing, and what is the cheapest fix?
Need a nudge? A hint rules out a wrong answer.

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.

Quorum write and read, N = 3, W = 2, R = 2
ClientClientCoordinatorCoordinatorReplica 1Replica 1Replica 2Replica 2Replica 3Replica 3

Write x = 7 (version 2). The coordinator sends it to all 3 replicas.

1/4

Check the overlap rule by brute force: this tries every possible set of writers against every possible set of readers.

Pythonquorum.py
from itertools import combinations def always_overlap(n, w, r): replicas = range(n) # Check every possible set of W writers against every possible set of R readers. for writers in combinations(replicas, w): for readers in combinations(replicas, r): if not set(writers) & set(readers): return False # found a read that misses the latest write return True for n, w, r in [(3, 2, 2), (3, 1, 1), (3, 3, 1), (5, 3, 3), (5, 3, 2)]: print(f"N={n} W={w} R={r} R+W>N: {r + w > n!s:<5} every read sees the write: {always_overlap(n, w, r)}")
Output
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.

Quick check
A cluster has N = 5. Writes use W = 3. What is the smallest R that guarantees every read sees the latest successful write?
Need a nudge? A hint rules out a wrong answer.

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.

Pythoncrdt_counter.py
# Two regions count likes on the same post while the link between them is down. def lww_merge(a, b): # Last write wins: keep whichever whole value has the later timestamp. return a if a["ts"] >= b["ts"] else b def gcounter_merge(a, b): # G-counter: one slot per replica, merge takes the max of each slot. return {r: max(a.get(r, 0), b.get(r, 0)) for r in sorted(a.keys() | b.keys())} # Last write wins on a plain numberus = {"value": 10, "ts": 1}eu = {"value": 10, "ts": 1}us = {"value": us["value"] + 3, "ts": 5} # 3 likes in the USeu = {"value": eu["value"] + 4, "ts": 6} # 4 likes in the EU, slightly laterprint("LWW after merge: ", lww_merge(us, eu)["value"]) # G-counter: each replica only increments its own slotus = {"us": 6, "eu": 4}eu = {"us": 6, "eu": 4}us["us"] += 3eu["eu"] += 4merged = gcounter_merge(us, eu)print("G-counter after merge:", sum(merged.values()), merged)print("merge again (no change):", sum(gcounter_merge(merged, eu).values()))
Output
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.

Predict the outputPython

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()))
Need a nudge? Hints walk you through it.

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.

Retry with an idempotency key
ClientPayments APIDatabasePOST /charges, Idempotency-Key: 8f3acharge $30, save key 8f3a + result200 OK (lost in the network)POST /charges, Idempotency-Key: 8f3akey 8f3a exists?200 OK (stored result, no new charge)

POST /charges, Idempotency-Key: 8f3a

1/6
Pythonidempotency.py
processed = {} # idempotency key -> stored response (a DB table in real life)balance = 100 def charge(idempotency_key: str, amount: int) -> str: global balance if idempotency_key in processed: return processed[idempotency_key] + " (replayed)" balance -= amount response = f"charged {amount}, balance {balance}" processed[idempotency_key] = response return response print(charge("order-981", 30))print(charge("order-981", 30)) # client retried after a timeoutprint(charge("order-982", 30))print("final balance:", balance)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.
Key terms
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.