Skip to main content

CAP Theorem

1. Executive Summary​

The CAP theorem formalizes a constraint on replicated data stores in distributed systems: when the network partitions so that nodes cannot communicate, a system cannot simultaneously provide linearizable consistency (Gilbert and Lynch's C) and availability (their A) for every request. Partition tolerance (P) is not an optional third knob—it reflects the reality that networks fail; the meaningful choice during a partition is between sacrificing strong consistency or sacrificing full availability.

Eric Brewer introduced the idea as a conjecture at PODC 2000; Gilbert and Lynch (2002) proved it for asynchronous networks with atomic read/write registers. This chapter presents the formal definitions, a proof sketch, production interpretations, common misreadings, and how CAP relates to safety/liveness and system models from the prerequisite chapter on Distributed System Models.

CAP is a forcing function for architecture reviews, not a catalog of database labels. Principal architects use it to ask: During a partition, which invariant do we refuse to violate, and how do we detect, bound, and recover from that choice?

2. Why This Topic Matters​

CAP appears in nearly every senior system-design interview, yet it is one of the most misquoted results in distributed computing. Interviewers at principal level are not checking whether you can recite "pick two of three." They are checking whether you can:

  • State Gilbert and Lynch's definitions precisely (linearizability vs. other "consistency" meanings).
  • Distinguish partition-time behavior from steady-state design.
  • Connect CAP to safety and liveness: consistency as a safety property; availability as a liveness property under failure.
  • Explain why P is not optional for any system that spans multiple failure domains.
  • Avoid marketing labels ("AP database") as substitutes for explicit client guarantees.

Misunderstanding CAP leads to expensive mistakes: promising linearizable reads from a multi-region deployment without quorum coordination; assuming "we chose AP" excuses duplicate writes; or designing incident response without a defined partition behavior. This chapter gives you vocabulary that survives whiteboard scrutiny and production postmortems.

3. Problems Being Solved​

ProblemHow CAP frames it
Split-brain writesUnder partition, two sides may accept writes unless one side refuses requests (CP) or exposes divergent state (AP).
Stale reads after failoverAvailability on both sides during partition implies reads may not reflect latest committed write.
Regional isolationWAN partition is not rare at scale; CAP asks what clients observe when links fail.
Technology selectionForces explicit guarantees instead of assuming "the database handles it."
Incident communicationGives precise language: "We are CP for metadata; AP for read replicas with bounded staleness."

CAP does not solve partition recovery, conflict resolution, or client retry semantics—it bounds what is possible without additional mechanisms (fencing, version vectors, external coordination).

4. Assumptions and System Model​

Gilbert and Lynch's proof assumes:

DimensionAssumption
NetworkAsynchronous: no upper bound on message delay; messages may be lost or delayed arbitrarily.
ProcessesCrash-stop is not the focus; nodes that receive requests are non-failing for the availability definition.
Data objectA single atomic read/write register (linearizable semantics).
PartitionThe network divides nodes into two or more groups with no messages delivered between groups for some period.
Client modelClients may contact any node; requests must complete at non-failing nodes if the system is available.

This aligns with the asynchronous message-passing model from Distributed System Models. CAP is not a theorem about Byzantine faults, transactional isolation across multiple keys, or multi-object serializability unless you extend definitions explicitly.

Production caveat: Real systems are often partially synchronous (eventual bounds after stabilization). CAP's impossibility still guides worst-case partition behavior; partial synchrony helps recovery and liveness after the partition heals, not the simultaneous satisfaction of C and A during the partition.

5. Essential Terminology​

TermGilbert & Lynch (2002) definition
Consistency (C)All operations appear to execute atomically at a single instant, consistent with a sequential read/write register (equivalent to linearizability for the single-register case).
Availability (A)Every request received by a non-failing node must result in a non-error response within a finite time, without the node knowing whether other nodes agree.
Partition tolerance (P)The system continues to operate despite arbitrary message loss between nodes (network partitions are a manifestation).
Network partitionA period when messages between some pairs of nodes are not delivered.
CP (during partition)Sacrifice availability: some requests fail or time out rather than violate linearizability.
AP (during partition)Sacrifice linearizability: both sides may respond, possibly with divergent or stale data.
Brewer's conjecture (2000)Informal claim that consistency, availability, and partition tolerance cannot all hold in the large-scale distributed systems setting.
CAP theorem (proved)In an asynchronous network, a replicated read/write register cannot be C, A, and P simultaneously when a partition occurs.

Not in Gilbert & Lynch: "eventual consistency," "BASE," "strong consistency" without definition, or multi-key ACID—these are separate layers.

6. Core Mechanism​

6.1 The theorem (statement)​

Theorem (Gilbert & Lynch, 2002): In an asynchronous network, it is impossible to implement a read/write data store that provides all three of:

  1. Consistency (linearizable atomicity),
  2. Availability (every non-failing node responds successfully to every request),
  3. Partition tolerance (system operates despite lost messages between nodes),

when a network partition separates the nodes.

6.2 Proof sketch (two-node case)​

Consider two nodes D1 and D2 that replicate a register, and clients that may send reads/writes to either node.

  1. Setup: Suppose the system is linearizable, available, and partition tolerant.
  2. Partition: The network drops all messages between D1 and D2. Clients C1 and C2 can still reach D1 and D2 respectively (each side is non-failing and reachable).
  3. Write: C1 writes v1 to D1. Because the system is available, D1 must acknowledge success without coordinating with D2 (messages are dropped).
  4. Read: C2 reads from D2. Because the system is available, D2 must return some value v in finite time, again without coordinating with D1.
  5. Contradiction: Linearizability requires that if the write of v1 completed before the read began, the read must return v1. D2 never received v1; if it returns a stale value, linearizability is violated. If it blocks or errors, availability is violated.

Therefore, during a partition, C and A cannot both hold for all requests.

Figure 1: CAP impossibility core — write on one side of a partition forces read on the other side to violate C or A.

6.3 Why P is not a "choice"​

In any distributed system spanning multiple nodes or failure domains, partitions can happen. Gilbert and Lynch treat partition tolerance as the ability to continue despite message loss. You do not "choose" to be partition intolerant in production—you choose what to sacrifice when a partition occurs.

The popular "pick two of three" triangle is misleading: the real decision is CP vs AP during partition, with P as a given constraint of distribution.

Figure 2: Partition tolerance is not optional; architects choose CP or AP behavior during isolation.

6.4 Mapping to safety and liveness​

CAP letterProperty familyIntuition
C (linearizability)SafetyClients never observe an impossible sequential history.
A (always respond)Liveness (under partition)Non-failing nodes must make progress on requests even when isolated.
PartitionFailure modelMessages between groups are lost—partial failure at the network layer.

Under partition, demanding both safety (linearizability) and liveness (responses without coordination) is impossible in the async model—an instance of the broader tension covered in Safety and Liveness.

7. Step-by-Step Walkthrough​

Scenario: A global user profile service with two replicas (US-East, EU-West) and a load balancer directing clients to the nearest replica.

  1. Normal operation: Writes go to a leader or require a quorum; reads may be local or quorum-based. System is linearizable if clients use quorum reads/writes or a single leader with synchronous replication.
  2. Partition: Transatlantic link fails. US and EU replicas cannot exchange heartbeats or replication messages.
  3. CP choice: EU replica stops accepting writes (or all writes) and returns errors/timeouts until it can rejoin a quorum. Reads may also fail if they cannot verify freshness. Availability on the minority side is sacrificed; consistency is preserved for operations that succeed.
  4. AP choice: Both sides accept reads and writes. Clients in EU may read stale profiles; concurrent updates create conflicts requiring resolution (last-write-wins, version vectors, CRDTs). Availability is preserved; linearizability is not.
  5. Healing: When the partition ends, replicas reconcile. CP systems catch up logs and reject divergent epochs; AP systems merge or surface conflicts to applications.

Figure 3: Same topology before and during partition — behavior depends on CP vs AP policy, not on diagram shape.


7.1 Real-World Scenarios at Production Granularity​

The following scenarios specify what clients observe, which CAP letter is sacrificed, and what operators do — minute by minute where useful. Use them to move beyond "we picked AP."

Scenario A: Amazon Dynamo shopping cart — classic AP under partition​

Context: DeCandia et al. (2007) describe Dynamo for Amazon's shopping cart: high availability prioritized; eventual consistency with merge semantics acceptable. This is the canonical AP during partition production case.

EventClient observationCAP choice
NormalAdd item to cart; read cart from local replicaTunable quorum; often QUORUM for writes
AZ partitionCart still accepts adds in isolated AZA — responds locally
Concurrent adds on both sidesCart may show merged or LWW-resolved itemsNot C — not linearizable globally
Partition healsVector clocks / reconciliation merge divergent cartsConvergence (post-CAP)

Granular user flow:

  1. T+0: User in US-East adds "Kindle" to cart. Write goes to nodes N1, N2, N3 with W=2 quorum in East.
  2. T+30s: Transatlantic partition isolates US-East from EU-West replicas.
  3. T+31s: Same user travels (or VPN flips); request hits EU-West load balancer.
  4. T+32s: EU replica may not show Kindle yet — stale read (AP sacrifice of linearizability).
  5. T+33s: User adds "Case" in EU — write succeeds locally (A preserved).
  6. T+10min: Partition heals; anti-entropy merges — cart shows both items.

Principal signal: Shopping cart tolerates temporary divergence; payment capture is a separate CP object (see Stripe scenario). Never label the whole company "AP" — per-operation CAP choice.

See: Amazon DynamoDB Consistency scenario.


Scenario B: Stripe payment authorization — CP for money movement​

Context: Card authorization must not double-charge or show inconsistent balance. During partition, Stripe and issuers fail closed rather than guess.

PhaseCAP postureBehavior
Auth requestCP leanQuorum / leader coordination before ACK
Network timeout to issuerClient sees 502/503Sacrifice A (no fake success)
Regional isolationRoute to healthy region OR rejectNo split-brain auth without quorum

Granular timeline — issuer timeout during partition:

TimeEvent
T+0POST /charges hits US-East API
T+50msAPI begins auth; issuer connection routed via US-East
T+200msPartial partition: issuer reachable from US-West only
T+5sUS-East times out — returns 503 to merchant
T+5.1sMerchant retries with idempotency key to US-West (if routed)
T+5.3sUS-West completes auth — single linearizable outcome via idempotency + issuer dedup

What AP would look like (unacceptable): US-East returns 200 with "pending" while US-West also authorizes — duplicate hold or inconsistent state.

See: Stripe Payment Idempotency.


Scenario C: Kubernetes control plane — etcd CP during AZ partition​

Context: etcd stores cluster state (pods, services, secrets). CP by design: writes require majority quorum; minority partition unavailable for writes.

3-node etcd across 3 AZs — AZ-a isolated:

NodeAZPartition roleWrite kubectl apply
etcd-1AZ-aMinority (alone)Fails — no quorum
etcd-2AZ-bMajority with etcd-3Succeeds
etcd-3AZ-cMajority with etcd-2Succeeds

Client impact:

  • kubectl hitting API server backed by minority etcd → 503 / timeout (A sacrificed on minority side).
  • Scheduling in majority AZ continues — C preserved for successful operations.

Operator mistake (AP drift): Allowing split-brain etcd (two majorities) — violates C worse than sacrificing A. Always fence minority.

Lesson: CP does not mean "down" globally — it means minority partition sacrifices availability to preserve linearizability.


Scenario D: Cassandra inventory — tunable CAP per request​

Context: Cassandra exposes consistency level (CL) per query — architects choose C vs A per operation, not per cluster label.

Flash sale — 100 units, 10,000 buyers:

CLWrite behavior during partitionCAP
ONEWrite to nearest replicaAP — fast; may oversell
QUORUMW=2 of 3 replicasCP lean — minority rejects
ALLAll replicasCP — one down blocks all

Granular oversell scenario (CL=ONE, partition):

  1. Replica R1 (partition A) and R2 (partition B) isolated.
  2. Buyer 1 writes stock=99 to R1; Buyer 2 writes stock=99 to R2 — both read 100 locally.
  3. Both succeed — 200 OK (A on both sides).
  4. 98 units sold but only 100 existed — C violated for inventory invariant.

Mitigation: QUORUM + lightweight transactions (LWT) for inventory; or CP metadata (reservation service) + AP catalog.


Scenario E: Global DNS failover — routing vs data plane​

Context: Route 53 health checks fail US-East; traffic shifts to EU-West. CAP applies to data, not DNS alone.

LayerFailover speedCAP relevance
DNS / GSLB30s–300s TTLRoutes clients — does not fix data
ApplicationImmediateMust choose CP or AP for writes
DatabaseRPO-dependentAsync rep → stale reads in EU

Timeline — regional disaster:

TimeEventCAP
T+0Earthquake isolates US-East region
T+1minRoute 53 marks US-East unhealthyTraffic → EU
T+2minEU app serves reads from local replicaMay be stale (AP) or rejected (CP)
T+2minUser updates profile in EUIf AP: diverges from US; if CP: write fails without quorum
T+4hUS-East never returnsDR promotion decision

Principal mistake: "DNS failed over so we're fine" — routing failover ≠ consistency failover.


Scenario F: Social feed (Meta-style) — AP with bounded staleness​

Context: News feed reads tolerate seconds of staleness; AP during partition keeps app usable.

OperationTypical CAPUser sees
Read feedAP / ELSlightly old posts
Post updateAPMay delay cross-region
Ad billingCPSeparate pipeline

Partition: US users see US posts; EU users see EU posts; fan-out queues backlog. A preserved; C not global linearizability.

See: Meta News Feed scenario.


Real-world CAP posture summary​

System / use casePartition postureMechanismSacrifice during partition
Amazon Dynamo cartAPQuorum + mergeLinearizability
Stripe / bank authCPQuorum, fail closedAvailability
etcd / ZooKeeperCPMajority quorumMinority availability
Cassandra (tunable)Per CLONE vs QUORUMConfigurable
SpannerCPPaxos + TrueTimeMinority unavailable
CDN / feed readsAPLocal replicasFreshness
DNS failoverRouting onlyHealth checksN/A — data separate

7.2 CAP in Active-Passive, Active-Active, and Disaster Recovery​

Failover topology determines who answers during partition and whether two sides can both accept writes. CAP is the lens for evaluating each choice.

DR vocabulary mapped to CAP​

TermCAP interpretation
RPOMax data loss — async replication ⇒ AP reads may miss recent C
RTOMax downtime — longer RTO ⇒ longer window choosing CP or AP
Active-passiveOne write primary — single C authority; standby sacrifices A until promotion
Active-activeMultiple write paths — highest split-brain / AP risk without global quorum
Split brainTwo primaries — C destroyed unless fenced
FailbackReturning to old primary — epoch/fencing prevents stale CP leader writes

Topology 1: Single-region active-passive (hot standby)​

Architecture: Primary AZ serves all writes; standby AZ has synchronous or async replica. On primary failure, promote standby.

Normal operation (no partition):

  • All writes to Primary — linearizable if sync replication.
  • Reads from Primary or Standby (if sync: C; if async: standby may lag — ELC branch).

Failover scenario — Primary AZ lost:

StepCAP behavior
1. Detect primary failureHealth checks fail
2. Fence old primary (STONITH / revoke IAM)Prevents split-brain C violation
3. Promote standbyStandby becomes single writer
4. Clients retryA restored on new primary after promotion

Sync replication (RPO ≈ 0):

  • CP during failover: Brief write unavailability during election (sacrifice A for seconds).
  • No lost commits — C preserved.

Async replication (RPO = 30s):

  • Promotion at T+15s may lose last 15s of writes — not a CAP theorem issue but data loss.
  • Clients who received ACK for lost writes see C violated from their perspective — reconciliation required.

CAP interview answer: "Single-region active-passive is CP-lean: one authoritative writer. Failover sacrifices A briefly; async replication sacrifices C for recent data even after heal."


Topology 2: Multi-region active-passive (DR standby)​

Architecture: US-East active; EU-West warm/cold standby. Cross-region async replication. DNS/Global Accelerator routes to active only.

Planned DR failover (region disaster):

PhaseActionCAP
DetectUS-East unreachable—
IsolatePrevent US-East from accepting writes if partially aliveFence — protect C
PromoteEU-West DB promoted to primarySingle writer restored
RedirectDNS → EU-WestA for EU; US users rerouted
OperateEU serves all trafficCP if single primary; C bounded by RPO

During partition before promotion (split period):

  • If US-East still accepts writes (misconfigured) AND EU promoted → split brain — worst C failure.
  • Correct: US-East fails closed (CP) or is fenced before EU promotion.

Client experience during 10-minute promotion:

User locationBefore failoverDuring promotionAfter failover
USUS-East A+C (normal)503 / timeout (A down)EU-West (A restored; possible stale read)
EURouted to US-East (latency)503EU-West local (A; lag per RPO)

RPO = 5 minutes example:

  • Writes in last 5 minutes before promotion may not exist in EU — reads show stale/missing data — users perceive C violation until reconciliation or accept loss.

RPO = 0 (sync cross-region — rare):

  • Writes require both regions — CP; partition blocks writes globally — A sacrificed during partition (Spanner-like).

Topology 3: Multi-region active-active​

Architecture: US-East and EU-West both accept reads and writes. Bidirectional replication.

Normal operation:

  • US user writes to East; EU user reads from West — eventual consistency (EL in PACELC).
  • Cross-region read-your-writes not guaranteed without sync replication.

Partition — transatlantic link down:

SideAP choiceCP choice
US-EastAccept writes; local reads fastReject writes without quorum
EU-WestAccept writes; local reads fastReject writes without quorum
Both APBoth sides keep serving — divergent state—
Both CPBoth sides reject writes — global unavailabilityC preserved

Granular split-brain example (AP misconfiguration):

TimeUS-EastEU-West
T+0User A sets balance=$100Replicated
T+1Partition—
T+2User B withdraws $60 → $40Not visible
T+3—User C withdraws $60 → $40 (stale read of $100)
T+4HealTwo withdrawals; balance should be -$20 or one must fail

Mitigations:

StrategyCAP effect
Global quorum (Spanner)CP — minority partition unavailable
Per-user home regionReduces cross-partition writes
CRDT / commutative opsAP with convergence — not for bank balance
Leader per shardCP per key partition
Fencing + epochStale primary cannot write after promotion

Failover scenario matrix (CAP lens)​

ScenarioTopologyRiskCAP response
Single AZ failureActive-passive same regionBrief unavailabilityCP: promote standby; sacrifice A seconds
AZ partition (split)Misconfigured quorumSplit brainFence minority; CP
Region disasterActive-passive DRRPO data lossPromote DR; document C bound = RPO
DNS failover onlyAnyStale routeData plane unchanged — CAP at DB
Active-active + partitionMulti-regionDouble writesAP divergence OR CP global write stop
Failback to old primaryDRStale primary writesFence old region; epoch bump
Cold DR restore from backupBackupHours of data lossC violated for backup window
Chaos: 50% packet lossAnyGray failureTimeouts → false failover → C or A thrashing

Active-passive vs active-active — CAP decision guide​

RequirementActive-passiveActive-active
Strict linearizability for writes✓ Natural single primaryNeeds global quorum (Spanner)
Maximize write availability in partition✗ Minority/standby downAP possible — divergent
Simplest mental model✓ One writer✗ Conflict resolution
Lowest cross-region write latency✗ Single primary may be far✓ Local writes (AP)
Financial correctness✓ PreferredDangerous without CP layer
RPO = 0Sync rep to standbyVery hard cross-region

Principal recommendation:

Data typeTopologyPartition CAP
Money, inventory, leader electionActive-passive or CP quorumCP — sacrifice A on minority
Feeds, carts, analyticsActive-active or AP replicasAP — sacrifice C; merge
Config / service registryCP coordination (etcd)CP
Read-heavy catalogAP replicas + CP inventory serviceHybrid

DR drill — CAP checklist​

Before failover drill:

  • Document per-API: CP or AP during partition
  • Define RPO/RTO and map to max staleness (C bound)
  • Verify fencing prevents stale primary writes
  • Client retry policy aligned (idempotency for CP rejects)

During drill:

  • Measure write unavailability window (A sacrifice) — target RTO
  • Sample reads from promoted region — measure staleness vs RPO
  • Confirm minority partition rejects writes (CP) not accepts (split brain)

After drill:

  • Reconcile divergent rows if AP path was tested
  • Failback only after epoch/fencing confirms old primary safe
  • Update ADR with observed C and A metrics

See also: Disaster Recovery and Multi-Region, AWS S3 Multi-Region DR, Google Spanner, PACELC for normal-case latency tradeoffs.


8. Invariants and Guarantees​

What CAP guarantees (formally):

  • In an asynchronous network, no algorithm for a linearizable replicated register can be both fully available on all non-failing nodes and correct during a partition.

What CAP does not guarantee or forbid:

  • Eventual consistency after partition heals (liveness of convergence is a separate property).
  • Partial availability (e.g., majority quorum available while minority is not)—Gilbert and Lynch's A is stricter: every non-failing node responds.
  • Session or monotonic reads — weaker than linearizability.
  • Transactional multi-key atomicity — CAP as proved is about a single register.

Invariants architects should document:

  1. Partition detection — How long before a side declares itself isolated?
  2. Degradation mode — Read-only? Leader step-down? Client retry to other region?
  3. Client contract — What error codes, staleness bounds, or conflict behavior?

9. Failure Scenarios​

ScenarioCP behaviorAP behaviorOperational risk
WAN link flapFrequent leader elections; write unavailabilityDuplicate writes; conflict stormsMisconfigured timeouts amplify flapping
AZ isolationMinority partition unavailableMajority and minority both serveSplit-brain if AP without conflict handling
Misconfigured quorumFalse belief of CP while both sides accept writesData loss on heal"Zombie" nodes after recovery
Client retries to both sidesIdempotent retries safe if one side rejectsDuplicate operations without idempotency keysDouble charges, duplicate messages
Stale leader (not partition)CAP does not cover crash-recovery aloneFencing tokens still requiredModel mismatch with crash-recovery

Gray failure: Partial partitions (high loss rate but not complete isolation) stress both CP and AP designs—timeouts may cause unnecessary failover (CP) or prolonged divergence (AP).

10. Performance Characteristics​

CAP is a correctness result, not a latency benchmark. Do not cite CAP to predict millisecond-level performance.

Qualitative effects during partition:

PathRead latencyWrite latencyClient-visible errors
CPMay increase if quorum required; minority fails fastUnavailable on minority sideTimeouts, 503, redirect to healthy partition
APLow local readsLow local writesFewer errors; semantic inconsistency instead

After heal: CP systems may incur catch-up replication lag; AP systems incur merge/compaction and conflict resolution cost—often application-dependent, not fixed by the CAP label.

11. Scalability Limits​

CAP does not set a replica count limit. It states that no amount of replication removes the C-vs-A tradeoff during partition if you insist on Gilbert and Lynch's definitions.

Scaling implications:

  • More regions → higher probability of partition involving some pair; explicit per-region behavior required.
  • Quorum CP → minority partitions scale in unavailability, not in violated linearizability.
  • AP with local replicas → write scalability without cross-region sync, at consistency cost.

Sharding does not circumvent CAP: each shard faces the same tradeoff; global transactions across shards add coordination that often increases latency (see PACELC).

12. Operational Considerations​

  1. Runbooks must name partition behavior. "Database down" is insufficient—is the minority partition rejecting writes by design?
  2. Health checks: A node can be "healthy" locally but partitioned from peers; load balancers may route to inconsistent replicas in AP mode.
  3. Monitoring: Track replication lag, leader epoch, fence generation, conflict rate, and unavailable error ratio during incidents.
  4. Chaos testing: Inject network partition (iptables, tc netem, fault injection services) and verify documented CP/AP behavior.
  5. Client SDKs: Retries, hedging, and read-your-writes semantics must align with server guarantees.

SLO impact: CP systems may trade availability SLO during partition for correctness; AP systems may meet availability SLO while violating strict consistency SLOs—define both.

13. Security Considerations​

CAP addresses benign network failure, not adversarial partitions. Security interactions:

  • Split-brain with weak auth: Two sides accepting writes may amplify forgery if clients can reach both.
  • Availability pressure: Product pressure to stay "green" during partition can push teams toward AP without conflict controls—integrity risk.
  • CP with exposed minority: Rejecting writes on minority is safer for consistency but may strand admin operations—ensure break-glass procedures are audited.

Byzantine tolerance requires different replica counts and protocols (n > 3f); CAP's single-register proof does not substitute for a threat model review.

14. Cost Considerations​

ChoiceCost driver
CP with cross-region quorumWAN replication latency; higher RPO/RTO investment; fewer but costlier regions active for writes
AP with multi-masterApplication conflict resolution engineering; support cost for "wrong data" reports; possible revenue impact
Over-provisioned redundancyDoes not eliminate CAP tradeoff; may reduce partition duration probability only

Finance and product should understand consistency is not free—either as unavailable windows (CP) or as reconciliation and trust costs (AP).

15. Production Implementations​

Illustrative implementation choices (not formal CAP proofs):

SystemDocumented partition postureMechanism (high level)
etcd / ConsulCP for coordinationQuorum writes; minority unavailable
ZooKeeperCPMajority quorum; Zab
Amazon Dynamo (2007)AP for shopping cart use caseQuorum reads/writes tunable; conflict handling
CassandraTunable (often AP-leaning)ONE/QUORUM/ALL consistency levels
Google SpannerCP (external consistency)TrueTime + Paxos; unavailable without quorum
MongoDBConfigurableWrite concern + read concern determine behavior

Distinction: Marketing "AP" does not mean "no consistency options." Always read consistency level and failure behavior docs for the specific version and deployment topology.

16. Alternatives and Tradeoffs​

FrameworkWhat it adds beyond CAP
PACELCLatency vs consistency without partition
Consistency models ladderLinearizability, sequential, causal, eventual—CAP uses only linearizability
CRDTs / OTConvergence without linearizability
Fencing + leasesSafety when liveness heuristics fail (crash-recovery)
Explicit SLAsBounded staleness (max_staleness=5s) instead of binary CAP

When CP is appropriate: Financial balances, inventory deduction, leader election, global uniqueness constraints, infrastructure metadata (service registry).

When AP is appropriate: Session carts, social feeds, metrics aggregation, features with natural merge semantics and tolerant users.

Hybrid: CP metadata plane + AP data plane is common and not a CAP violation—different objects, different guarantees.

17. Common Misconceptions​

MisconceptionCorrection
"Pick two of three at design time"P is given; you choose CP vs AP when partitioned.
"CAP means NoSQL vs SQL"Storage model ≠ partition behavior; SQL clusters can be CP or AP depending on configuration.
"Consistency means ACID transactions"Gilbert & Lynch: linearizable single register.
"Availability means uptime %"G&L: every non-failing node responds to every request during partition.
"We run single-region so CAP doesn't apply"Single region reduces partition probability, not multi-node failure modes (AZ partition).
"Eventual consistency violates CAP"After partition, AP systems may be eventually consistent; CAP addresses during partition.
"CA systems exist in the cloud"Without P, you are not distributed across failure domains—often a single node or shared fate.

18. Principal Architect Perspective​

Use CAP to structure decisions, not to win arguments:

  1. Name the object — Per service, per API, per key: what is the register?
  2. Name the guarantee — Linearizable? Causal? Bounded staleness?
  3. Name partition behavior — Who fails closed? What do clients do?
  4. Name recovery — Merge, log replay, human reconciliation?
  5. Align org incentives — SRE availability metrics vs. data integrity requirements.

In architecture review, reject slides that say "we are AP" without stating what inconsistency users will see and how conflicts are resolved. Principal engineers are accountable for client-visible contracts, not triangle diagrams.

19. Architecture Review Exercise​

Prompt: A fintech startup proposes dual-active PostgreSQL in US and EU with async replication, routing users to the nearest region for reads and writes. They claim "CA within each region."

Review tasks:

  1. Identify the CAP-relevant object (account balance? transfer idempotency key?).
  2. Classify behavior during transatlantic partition under Gilbert & Lynch definitions.
  3. List three failure scenarios (split brain, duplicate transfer, stale balance).
  4. Recommend CP vs AP per operation type and mechanisms (quorum, idempotency, outbox).
  5. Draft client-facing error semantics for partition.

Deliverable: One-page ADR with explicit C/A/P definitions, partition mode, and monitoring plan.

20. Whiteboard Explanation​

Draw:

[Clients]
|
[Load balancer]
/ \
[US replica] [EU replica]
\ /
----X---- ← partition (link down)

Write v1 @ US → Read @ EU → ?

90-second script: "CAP is a theorem about asynchronous networks and a single linearizable register. When the link between US and EU drops, if EU must answer every read without talking to US, it cannot return the latest write from US—that breaks linearizability. If EU blocks or errors, we broke Gilbert and Lynch availability. So during partition we choose CP—sacrifice availability on the minority—or AP—respond with possible staleness or conflicts. Partition tolerance isn't optional in a multi-site system. CAP doesn't say eventual consistency is bad; it says you can't have full linearizability and full availability on both sides at once. For money movement I'd CP with quorum; for a shopping cart Amazon famously chose AP with merge semantics."

21. Interview Questions​

  1. State the CAP theorem using Gilbert and Lynch's definitions of C, A, and P.

    • Signals: linearizable register; non-failing nodes respond; arbitrary message loss; impossibility during partition.
  2. Why is "pick two of three" misleading?

    • Signals: P is not optional; choice is CP vs AP when partitioned.
  3. Walk through the two-node proof sketch.

    • Signals: write one side, read other, contradiction.
  4. Does CAP apply to a single-leader database in one datacenter?

    • Signals: AZ/partition still possible; reduced WAN partition probability; model matters.
  5. What is the difference between Brewer's conjecture and Gilbert & Lynch's theorem?

    • Signals: informal vs proved; async network; atomic register.
  6. Is etcd CP or AP? Justify.

    • Signals: quorum; minority unavailable; linearizable.
  7. How does CAP relate to safety and liveness?

    • Signals: consistency safety; availability liveness; partition as failure model.
  8. Can a system be "CA"?

    • Signals: not across partitions; single failure domain; marketing triangle artifact.
  9. What does availability mean in CAP vs "99.9% uptime"?

    • Signals: every request gets response from non-failing node during partition.
  10. How would you design a dual-region service for CP writes and AP reads?

    • Signals: separate guarantees; staleness bounds; not one global label.
  11. Does sharding avoid CAP?

    • Signals: per-shard tradeoff; cross-shard coordination separate.
  12. What is NOT covered by the classic CAP proof?

    • Signals: multi-key transactions, Byzantine, partial availability quorums as "available" under G&L.
  13. During active-active multi-region partition, how do you prevent double-spend?

    • Signals: global quorum CP, fencing, per-shard leader, not AP for balances.
  14. Active-passive DR with 5-minute RPO — what CAP guarantee do clients lose after failover?

    • Signals: recent writes may be missing; C bounded by RPO; not CAP theorem but data loss.
  15. Why doesn't DNS failover alone solve CAP?

    • Signals: routing ≠ data plane; stale replicas; split brain if both regions write.

22. Interview Follow-Ups​

  1. How does PACELC extend CAP? — Normal-case latency vs consistency; see PACELC chapter.
  2. What consistency level would you use in Cassandra for inventory? — Likely QUORUM or strong per-key; discuss LWT limitations.
  3. Spanner claims external consistency—is it CA? — CP when partitioned; TrueTime does not remove partition tradeoff.
  4. How do conflict-free replicated data types (CRDTs) fit CAP? — AP-friendly; convergence without linearizability.
  5. What happens to CAP under partial synchrony? — Still applies during partition; recovery differs.
  6. Design idempotency for AP retries. — Idempotency keys, dedup store, outbox pattern.
  7. Active-passive failover — CP or AP? — CP-lean; brief A sacrifice; fence stale primary.
  8. Can active-active be CP? — Only with global quorum (Spanner); else AP for writes or stop writes globally.

22A. Production Low-Level Design (Interview + Game Day)​

Per-feature CAP routing during partition—CP for money, AP for prefs. Production LLD and Game Day Standard.

Feature matrix​

FeaturePartition postureAPI behavior
Balance / paymentCPMinority region → 503 / fail closed
User prefs / themeAPServe stale; merge on heal
Catalog browseAP/ELStaleness SLO + cache TTL

Step-by-step flow:

StepDecisionUser-visible
1Network partition detectedBoth regions alive
2Route by feature classNot one global policy
3CP rejects stale sideErrors, not wrong money
4AP accepts + replicatesBrief staleness OK

SLO​

Balance path: 0 stale reads during partition (CP). Prefs path: p99 replication lag < 30s.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Cross-region partitionBlock US–EU linkRegional error rate ↑CP features fail closed on minorityNo double-spend
GD-2AP prefs under partitionDual-region writesConflict metricMerge policy firesConverged after heal
GD-3PM "100% A + C" testSimulate partitionProduct confusion drillExplain per-feature matrixADR updated

GD-1 — Partition / balance CP​

23. Strong Answer Example​

Question: "Explain CAP to a product manager who wants 100% availability and always-fresh data globally."

Answer this as a product-facing architecture conversation using the PRACTICE framework. Below is how a strong student sounds aloud—no triangle slogans; translate CAP into what users see when regions can't talk.

PRACTICE interview answer map for CAP explained to a PM

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"You're asking for two things at once worldwide: every request always succeeds (100% availability), and every read always shows the latest write (always-fresh / linearizable). Those goals collide when the network between regions fails—and multi-region products will see partitions.

CAP (Gilbert & Lynch) is the formal reason. I'm not saying 'pick two of three forever.' I'm saying: during a partition, you cannot keep answering on both sides and guarantee every read is the latest write.

Non-goals: dumping database brand names, or claiming Cassandra/Dynamo 'solves CAP.'"

R — Requirements (rephrase for the PM)​

PM askTechnical meaningHonest reframe
100% availabilityEvery non-failed node answers every request (CAP A)Aim for high SLO; during partition, some requests must fail or return possibly stale data
Always-fresh globallyLinearizable / latest-write-wins across regions (CAP C)Needs coordination; blocks or errors on the side that can't see the write
Works worldwideMultiple failure domainsP is not optional—partitions happen

"I'll ask the PM: which features cannot show stale data (money), and which can (wishlist)? We'll mix CP and AP per feature."

A — Assumptions (state in plain language)​

AssumptionWhy it matters for the PM
Users in US and EU both write/readCross-region coordination path
Link between regions can dropPartition scenario is real
"Fresh" means latest successful write everywhereStronger than "usually up to date"
"Available" means users get an answer, not a spinner foreverBlocking to stay fresh = temporary unavailability

"I'd never say 'we are CA.' That usually means 'we ignored partitions.'"

C — Capacity (user-visible tradeoff, not QPS)​

Normal day (no partition) → PACELC: latency vs freshness (separate conversation)
During US–EU partition → Must choose per feature:
CP path → Some users get errors/503 until heal (freshness preserved)
AP path → Users get answers; may be stale / conflict later
Outage length → Minutes to hours → product copy + status page matter

"This isn't about being slow forever—it's about what we show during a bad hour."

T — Topology (draw for the PM)​

CAP partition fork for product managers

Figure B: US–EU link broken. CP = refuse stale (errors). AP = answer anyway (may not be fresh). P is given.

One-sentence proof for a PM:

"If EU answers a read without talking to US, it can't know about a write that just succeeded in US—so that read isn't 'always fresh.' If EU waits or errors until it can talk to US, that user isn't 100% available during the outage."

Per-feature CAP choices in one product

Figure C: Payments CP; wishlist/cart AP; flags AP at edge; mix in one product—draft outage UX per feature.

FeatureDuring partitionWhy
Payments / ledgerCP — fail closed on minorityWrong balance worse than error
Wishlist / socialAP — serve local, merge laterStale OK; always-on matters
Feature flags (edge)Often AP with versionsPage loads must not hang
Admin config / inventory reserveUsually CPConflicting writes hurt

I — Invariants (what we refuse to break)​

"I'd write these on the whiteboard for the PM:

  1. We cannot promise 100% avail + always-fresh on both sides of a partition.
  2. P is not a product choice—multi-region implies partitions.
  3. CAP C here means linearizability-style freshness, not 'eventual consistency is fine.'
  4. We choose per feature what users see: error vs possible staleness.
  5. After heal, AP features may need merge/reconcile—budget eng + support."

C — Constraints (second C)​

ConstraintProduct response
"100% availability" SLA languageUse SLO (e.g. 99.9%); define partition behavior explicitly
Always-fresh + multi-region writesQuorum / Spanner-like cost & latency (PACELC: pay latency when healthy too)
Marketing "strong consistency"Name which API is CP vs AP
Incident commsStatus page scripts: "payments unavailable in region X" vs "wishlist may lag"

E — Evolution (what I'd deliver next)​

Phased conversation / deliverables:

PhaseDeliverable
NowOne-pager: feature → CP/AP + user-visible outage behavior
M1Payments path: fail closed minority; fencing / single writer
M2Soft features: AP with merge rules and UX copy
M3Game day: simulate region partition; record screenshots for PM
M4ADR + support runbooks; revisit triggers (error rate, conflict rate)

Also mention PACELC briefly:

"Even on a healthy day, always-fresh usually costs latency (PACELC). CAP is the partition story; PACELC is the normal-day latency vs freshness story."


Closing line (interview)​

"So I'd tell the PM: those two goals fight during a regional network failure. CAP says we pick errors to stay fresh (CP) or answers that might be stale (AP)—we don't get both on both sides. P isn't optional. I'll map payments to CP, softer features to AP, and write down exactly what users see in an outage—not a slogan about picking two of three."

Scoring signals​

StrongWeak / red flag
Partition scenario in plain English"Pick two of C/A/P" triangle
Gilbert & Lynch-style C and ADatabase brand as answer
Per-feature CP/AP mixOne label for whole product
User-visible outage UX"Strong consistency is just slow"
P not optional"We are CA"
PACELC as follow-onIgnores normal-day latency tradeoff

Compact outline (if time-boxed to 2 minutes)​

"100% available + always-fresh globally conflict when US–EU can't talk. If both sides answer, one side may miss the latest write (lose freshness). If we refuse stale, some users get errors (lose availability). Partitions happen. Payments: CP fail closed. Wishlist: AP merge later. Draft per-feature outage UX. Don't say pick two of three."

24. Weak Answer Example​

Question: "Explain CAP to a product manager who wants 100% availability and always-fresh data globally."

"CAP says you pick two: consistency, availability, or partition tolerance. We pick AP because we use Cassandra and need uptime. Strong consistency is too slow anyway."

Why weak / red flags: Triangle memorization; database name as justification; conflates latency with CAP; no partition scenario; no Gilbert & Lynch definitions; implies consistency is always slow without context.

25. Hands-On Exercise​

Lab: Observe CP vs AP under partition

  1. Deploy a 3-node etcd cluster (or use a CAP simulation tool).
  2. Baseline: Write a key; read from all members; verify linearizable behavior.
  3. Partition: Isolate one follower with network rules; attempt writes on majority and minority.
  4. Document: Which operations fail? Does minority ever accept writes?
  5. Optional: Repeat with Cassandra or a tunable store at ONE vs QUORUM.
  6. Write ADR: Map observations to Gilbert & Lynch C, A, P.

Success criteria: Written explanation of one operation that violated availability to preserve consistency, and one that preserved availability at consistency cost.

26. Knowledge Check​

  1. Define C, A, and P per Gilbert and Lynch.
  2. Why does a write on one side and read on the other force a CAP violation?
  3. Is partition tolerance optional in multi-AZ cloud deployments?
  4. How does CAP's "availability" differ from an uptime SLA?
  5. What failure model does CAP assume for the network?
  6. Name one production system that is CP by design for coordination.
  7. What property does an AP system typically sacrifice during partition?
  8. Does CAP forbid eventual consistency after heal?
  9. What object type does the classic proof use?
  10. How does CAP relate to safety and liveness?
  11. During active-active partition, why can two regions both accept writes only under AP?
  12. What is split brain in CAP terms? (Two primaries — C violated unless fenced.)
  13. How does RPO relate to consistency after DR failover? (Max lost writes = staleness/C bound.)

27. Flashcards​

FrontBack
CAP (proved result)Async network: linearizable C and full A cannot both hold during partition
Consistency in CAPLinearizable atomic read/write register (Gilbert & Lynch)
Availability in CAPEvery non-failing node responds successfully to every request
Partition toleranceSystem operates despite arbitrary message loss between nodes
Brewer (2000)Conjecture at PODC; popularized CAP tradeoff
Gilbert & Lynch (2002)Formal proof for async atomic register
CP during partitionSacrifice availability; preserve linearizability
AP during partitionSacrifice linearizability; keep responding
"Pick two of three"Misleading — P is given; choose CP vs AP
CAP proof coreWrite one partition side, read other — contradiction
CAP not aboutMulti-key ACID, Byzantine faults, uptime % alone
Recovery after partitionSeparate from CAP impossibility during partition
Active-passiveCP-lean; single writer; A sacrificed briefly on failover
Active-activeAP risk for writes unless global quorum (CP)
Split brainTwo primaries — C destroyed; fence with epoch/STONITH
RPOMax data loss — consistency bound after DR promotion
DNS failoverRouting only — does not fix data-plane CAP

28. Cheat Sheet​

GILBERT & LYNCH DEFINITIONS
C = linearizable (atomic) single register
A = every non-failing node responds, finite time
P = arbitrary message loss (partitions)

THEOREM
During partition in async network: NOT (C ∧ A ∧ P)

PRACTICAL
P is given → choose CP or AP when partitioned
CP = errors / block minority
AP = respond; stale / conflicts possible

HA/DR
Active-passive → CP lean; fence on failover
Active-active → AP write risk OR global quorum CP
RPO = max C loss after promotion
Split brain = worst C failure

NOT CAP
latency tuning, eventual merge, SQL vs NoSQL

INTERVIEW
proof sketch + definitions + production example

30. References​

Primary sources (formal guarantees)​

  • Gilbert, S., & Lynch, N. A. (2002). Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services. ACM SIGACT News, 33(2). [CAP theorem proof — asynchronous network, atomic register]
  • Brewer, E. A. (2000). Towards Robust Distributed Systems. PODC keynote. [Original conjecture — informal]
  • Herlihy, M. P., & Wing, A. V. (1990). Linearizability: A Correctness Condition for Concurrent Objects. ACM TOPLAS. [Consistency (C) as linearizability]
  • Lynch, N. A. (1996). Distributed Algorithms. Morgan Kaufmann. [Asynchronous network model]

Books and synthesis​

  • Kleppmann, M. (2017). Designing Data-Intensive Applications. O'Reilly. [Chapters 5, 7, 9 — replication, consistency, CAP critique]
  • Martin, K. (2012). Notes on CAP and PACELC. Blog post. [Practical critique of triangle misreadings — implementation-oriented]

Implementation-oriented (engineering practice)​

  • DeCandia, G., et al. (2007). Dynamo: Amazon's Highly Available Key-value Store. SOSP. [AP-oriented production design]
  • Corbett, J., et al. (2012). Spanner: Google's Globally-Distributed Database. OSDI. [CP with TrueTime and Paxos]
  • etcd documentation: https://etcd.io/docs/ [Quorum CP coordination]

Distinction​

  • Formal guarantees — Gilbert & Lynch impossibility under stated async model and register semantics.
  • Implementation choices — Dynamo, Cassandra consistency levels, etcd quorum behavior.
  • Operational experience — Partition drills and incident patterns; verify in your environment rather than citing generic outage narratives.