11. CAP & Consistency

Where this fits: You have databases, replicas, caches, and maybe shards. Data now lives in multiple places. This lesson explains the trade-offs when those places disagree β€” and how to choose the right consistency for each product feature.


Learning goals

By the end of this lesson, you should be able to:

  • Explain consistency vs availability in plain English with everyday examples
  • Name common consistency models (strong, eventual, read-your-writes) and when each fits
  • State CAP theorem at a beginner level without treating it as gospel
  • Use PACELC as a lightweight extension (latency vs consistency)
  • Map product features to appropriate consistency choices
  • Build intuition for quorum reads/writes (Dynamo-style)
  • Connect replication lag to consistency guarantees
  • Speak confidently about trade-offs in HLD interviews

The everyday problem β€” two copies, one update

You run a notes app with database replicas in US and Europe. A user in New York edits a note at 3:00:00 PM.

At the exact same moment, the network link between US and Europe fails (a partition).

Questions:

  1. Should a reader in Paris immediately see the edit?
  2. If Paris cannot reach New York, should the app refuse to respond or show the old note?

There is no free lunch. This tension β€” correctness vs staying online β€” is what this chapter is about.

Everyday analogy β€” two whiteboards in different offices:

Company policy lives on a whiteboard. Office A updates "Vacation policy: 20 days." Office B's whiteboard still says "15 days" until someone syncs them.

  • Consistency-first: Office B says "I can't answer β€” my board might be wrong." (refuse read)
  • Availability-first: Office B says "15 days" β€” might be stale, but at least you got an answer.

Consistency models β€” practical definitions

Consistency answers: When I read data, how sure am I that I'm seeing the latest (or an acceptable) version?

ModelPlain EnglishReal-world example
Strong consistencyAfter a write succeeds, every read sees that write immediatelyATM balance after withdrawal
Eventual consistencyReads may be stale for a while; replicas converge laterYouTube view count; Instagram like count
Read-your-writesYou always see your own updates; others might lagEdit profile β†’ you see new name; friend might not yet
Monotonic readsOnce you see version V, you never see an older version in same sessionTimeline doesn't "undo" posts you already saw
Causal consistencyRelated operations appear in cause-effect orderReply appears after parent comment (harder at scale)

Strong consistency β€” when wrong is unacceptable

User transfers $100:
  1. Debit account A
  2. Credit account B
  3. COMMIT

Any read of A or B before commit completes β†’ must not show partial state
Any read after commit β†’ must show new balances

Cost: Often requires coordination β€” talking to multiple nodes, locks, or reading from primary. Higher latency, lower availability during failures.

Eventual consistency β€” when "soon enough" is fine

Post gets 1,000 likes in 10 seconds:
  - Exact count of 1,000 vs 997 vs 1,003 β†’ nobody cares
  - System stays fast and available
  - Counts merge asynchronously

Benefit: Fast writes, high availability, geographic spread.
Cost: Temporary disagreement between replicas.

Read-your-writes β€” the UX sweet spot

Users are most confused when their own action doesn't appear.

Bad UX:
  User: "I changed my avatar."
  App:  (shows old avatar from replica)
  User: "It didn't work!" β†’ support ticket

Fix:
  After user's write β†’ route their reads to primary (or invalidate their cache)
  Other users can still read from slightly stale replicas

CAP theorem β€” plain English version

CAP describes a trade-off during a network partition (nodes can't talk reliably):

LetterMeaning
C β€” ConsistencyEvery read returns the latest write (or the system errors)
A β€” AvailabilityEvery request gets a response (not an error), even if data might be stale
P β€” Partition toleranceThe system continues operating when network links break between nodes

The theorem (simplified): In a distributed system, when a partition happens, you cannot fully have both C and A. You must lean toward one.

Why P is not optional in the cloud

Partitions will happen:

  • Router misconfiguration
  • Availability zone outage
  • Undersea cable damage
  • GC pause causing timeout
  • Misconfigured security group

Real systems assume P and choose between C and A during trouble.

CAP is intuition, not a product label

Don't do thisDo this instead
"We're CP so we're always consistent""During partition, we prefer consistency for payments β€” we may return errors rather than wrong balances"
"We're AP so CAP doesn't apply""Like counts are eventually consistent; checkout uses stronger guarantees"
Memorize CA / CP / AP badgesExplain per-feature trade-offs

Everyday analogy: CAP is like choosing between closing the store during a supply truck strike (consistent inventory records) vs selling what you think is on shelf and fixing discrepancies later (available but maybe wrong count).


PACELC β€” a lighter extension

PACELC (same author, extended idea):

If Partition: choose A or C
Else (normal operation): choose Latency (L) or Consistency (C)

Even without a network partition, waiting for all replicas to agree adds latency.

System biasNormal operationDuring partition
Dynamo-style (AP-ish)Fast writes, async replicateStay available, stale reads OK
Traditional RDBMS (CP-ish)Strong on single nodeMay block/fail cross-node
Spanner / CockroachStrong with higher latencyConsistency prioritized
Write to 3 replicas:
  Wait for 1 ACK  β†’ fast, less consistent
  Wait for 3 ACKs β†’ slow, stronger consistency

You don't need to cite PACELC in every interview β€” but it helps you say: "Consistency isn't binary; we tune how many replicas must agree."


Quorum intuition β€” Dynamo-style (N, W, R)

For N replicas of a key:

  • W = number of replicas that must acknowledge a write
  • R = number of replicas read during a read

Rule of thumb: If W + R > N, reads and writes overlap on at least one node β†’ stronger consistency.

Example: N = 3

WRW + R > 3?Behavior
11No (2)Fastest; likely stale reads
22Yes (4)Read sees latest committed write (with caveats)
31Yes (4)Slow writes; safer reads
13Yes (4)Slow reads; fast writes

Everyday analogy β€” homework grading:

Three teachers have copies of your essay. W=2 means two must receive your revision before it's "submitted." R=2 means two teachers are consulted for the grade. If W+R > 3, at least one teacher who saw the latest draft also grades you.

Caveats for beginners: Quorums handle many cases but not all (conf concurrent writes need version vectors / last-write-wins / conflict resolution β€” advanced topic).


Product feature β†’ consistency choice

FeatureTypical choiceWhy
Bank transfer / paymentStrongWrong balance = money lost, legal liability
Inventory checkout (last item)Strong / transactionalOverselling causes refunds and angry customers
Seat booking (airline)StrongDouble-booking is catastrophic
URL redirect mappingStrong enough / tiny lag OKWrong link breaks trust; easy to cache + single-key
User profile (self-view)Read-your-writesUser must see own edits immediately
User profile (public view)EventualFriend sees new avatar 2 sec late β€” fine
Like / view countersEventualApproximate counts acceptable
News feed / timelineEventual"Fresh enough" beats perfectly ordered globally
Chat messagesDurable + ordered per conversationMessages must not disappear or reorder wildly
Analytics dashboardEventualMinutes-old metrics OK
Search indexEventualNew post searchable seconds later OK
Leaderboard (gaming)Eventual / periodic flushExact real-time rank less critical
Feature flagsRead-your-writes / short TTLOps needs changes to propagate quickly

Replication lag β€” consistency in disguise

From lesson 09: read replicas lag behind primary.

Read fromConsistency level
PrimaryStrong (for that node)
Replica (0 lag)Strong-ish
Replica (2 sec lag)2 sec stale β€” eventual
Cache (5 min TTL)Up to 5 min stale

Mitigations recap:

1. Read-your-writes: user's reads β†’ primary after write
2. Monotonic reads: sticky session to same replica
3. Synchronous replication: wait for replica ACK (slower writes)
4. Version numbers: client detects stale and retries

Worked examples

Example 1: Instagram-like count

Architecture:
  Write path:  POST /like β†’ increment counter in Redis β†’ async flush to DB
  Read path:   GET /likes β†’ read Redis (maybe Β± few counts off)

Consistency: Eventual
Why OK:      Users expect approximate social proof, not audit-grade counts

Example 2: Ticketmaster-style booking

Architecture:
  BEGIN TRANSACTION
    SELECT seats WHERE id = 7 FOR UPDATE   -- lock row
    IF available: UPDATE status = 'sold'
  COMMIT

Consistency: Strong (pessimistic locking)
Why:         Two users cannot buy same seat

> **Go deeper:** [18. Transactions & Isolation](18-transactions-isolation-concurrency.md) β€” `FOR UPDATE`, isolation levels, and conditional UPDATE patterns.

Example 3: Multi-region notes app

Option A (CP-ish):  Writes go to one region; reads from local replica
                    During partition β†’ reject writes in minority region

Option B (AP-ish):  Writes accepted locally; merge conflicts later
                    "Last write wins" or CRDT merge

Product choice:     Personal notes β†’ AP often OK
                    Shared legal docs β†’ CP required

Consistency vs caching (connecting lesson 10)

LayerStaleness window
Strong DB read (primary)Minimal
Read replicaReplication lag (ms–sec)
Redis cacheTTL (sec–min)
CDNMinutes–hours
Browser cacheUser-controlled

Stacked staleness: A cached value on a replica can be double stale. Design invalidation carefully.


Common mistakes

MistakeReality
"We need strong consistency everywhere"Kills latency and availability; expensive
"Eventual consistency means data is random"Replicas converge; staleness is bounded by design
Ignoring read-your-writes in UX#1 user confusion after profile edits
Treating CAP as three checkboxesIt's a trade-off during partition, not a brand
Strong consistency without transactionsLabeling alone doesn't fix race conditions
Quorum without conflict resolutionConcurrent writes to same key still conflict
Same consistency for reads and writesOften writes are strong, reads are relaxed

How to talk about this in HLD interviews

Use feature-specific sentences:

"Checkout inventory decrement runs in a Postgres transaction with row-level lock β€” strong consistency."

"Like counts are eventually consistent: we increment in Redis and batch-persist; displaying 1,003 vs 1,000 is fine."

"After profile update, we invalidate cache and route that user's reads to the primary for read-your-writes."

"Cross-region, we accept seconds of lag on public timelines; payment service stays in a single region with sync replication."

That sounds senior β€” because it is specific, not buzzword soup.


Visual summary

(Diagram is illustrative β€” real systems tune per feature, not one dot per company.)


Check your understanding

Questions

  1. In plain English, what tension does CAP describe?
  2. Can a system be strongly consistent, fully available, and partition-tolerant all at once during a network split?
  3. What's the difference between strong consistency and eventual consistency? Give one example of each.
  4. What does read-your-writes protect against?
  5. Why are like counts often eventually consistent?
  6. In quorum terms, why does W=2, R=2, N=3 give stronger reads than W=1, R=1?
  7. Should checkout inventory use strong or eventual consistency? Why?
  8. What does the "ELC" part of PACELC remind you to consider during normal (non-partition) operation?

Answers

Click to reveal answers
  1. When the network breaks between nodes, you often must choose between returning possibly stale data (availability) vs refusing or blocking until data is correct (consistency).

  2. No β€” during a partition, you effectively sacrifice either C or A (while assuming P). You cannot guarantee both perfect consistency and always getting a response.

  3. Strong: every read sees latest write immediately (bank balance). Eventual: replicas may disagree temporarily but converge (YouTube view count).

  4. It prevents users from seeing their own outdated data immediately after they make an update β€” e.g., editing profile and still seeing old name.

  5. Exact real-time like count rarely matters to users; high availability and speed matter more. Off-by-a-few is acceptable.

  6. W+R=4 > N=3, so at least one node participating in the read also received the latest write β†’ overlap increases freshness. W=1,R=1 has no overlap guarantee.

  7. Strong β€” selling the same last item twice causes refunds, fraud, and customer anger. Overselling is a correctness bug with monetary impact.

  8. Latency vs consistency β€” even without partitions, waiting for more replicas to agree slows responses. Normal operation still involves trade-offs.


Quick reference card

Strong         β†’ always latest; slower; may error during partition
Eventual       β†’ stale OK temporarily; converges; fast + available
Read-your-writes β†’ you see your edits; others may lag
CAP            β†’ during partition: pick C or A (P assumed)
PACELC         β†’ else: latency vs consistency
Quorum         β†’ W + R > N β†’ read/write overlap β†’ stronger
Per-feature    β†’ payments strong; likes eventual; profile RYW

Next: 12. Queues & Async Processing β€” when the user shouldn't wait for the whole job to finish.