CAP Theorem
CAP concerns what a distributed system can guarantee while communication is partitioned.
What, why, when and how
What is it?
CAP describes a limit for distributed read/write systems during a network partition: linearizable consistency and availability for every operation at non-failing nodes cannot both be guaranteed.
Why is it needed?
It exposes a real product decision when replicas cannot communicate: return possibly stale information or refuse an operation that requires current shared state.
When should I use it?
Use it to specify behavior for individual operations during a partition, then define reconciliation after communication returns.
When should I choose something else?
Do not use CAP as a blanket database label or as a claim that a healthy system must always choose only two properties. Normal-operation latency needs separate analysis.
How do I use it?
Define the consistency promise, mark the broken communication link, and trace a completed write followed by a later read on the isolated replica. State which response is permitted.
Can you show a concrete example?
A profile write changes Nia/v1 to Sam/v2 at A. If B is isolated with v1, it cannot promise a current read of v2 from its local information. The product may allow an explicitly stale profile, while an exclusive seat claim needs a stricter decision.
Read the diagram
A completes Sam/v2; B still has Nia/v1; Replication link breaks; both nodes run; B: return allowed stale data or refuse current read
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
Start with a user-visible question
Mira changes her public display name from Nia to Sam. A moment later, another user reads her profile through a different region. Must that reader see Sam, or is Nia temporarily acceptable? Now ask the same question about the last concert seat: may a second region confirm a purchase using an old copy of availability?
These are different promises. A cosmetic name can often tolerate staleness. Confirming exclusive ownership of a seat cannot tolerate two successful buyers under a no-double-booking contract. CAP helps explain what happens when the replicas needed to enforce a promise cannot communicate. It does not choose the product promise for you.
This lesson builds one profile example through healthy replication, a partition and recovery. It then applies the reasoning to ownership, sessions, quorums and an interview answer. The records, timings and policies are original exercise assumptions, not claims about a named company's implementation.
First understand replicas and replication
A replica holds a copy of some data. Replication carries updates between copies. Suppose Region A and Region B both start with profile p17, name=Nia, version=v1. Mira reaches A and submits an update. A commits name=Sam, version=v2. B learns about that committed update through replication.
In the illustrated healthy execution, A acknowledges the update, the update reaches B, and the later read at B returns Sam. Follow the actual arrows: 1 is a client write, 2 is copying state between regions, and 3 is another client's read. The users do not replicate the database themselves.
Read the diagram
1 Mira writes p17=Sam/v2 at A. 2 Replication delivers v2 to B. 3 A later reader at B receives Sam. This successful asynchronous execution alone does not guarantee every replica read is current.
There is an important limit to this picture. With asynchronous replication, A may acknowledge before B applies the update. A read during that gap can still return Nia even though the network is healthy. Seeing both replicas agree at the end of one example does not prove that every execution is strongly consistent. To promise a current read, define a read barrier, current-authority read or another complete coordination protocol. To promise replication before acknowledgment, specify which replicas must acknowledge and what they have applied or persisted.
Predict: A acknowledges v2 at 10:00:00.100; B applies it at 10:00:00.250. What may an ordinary asynchronous replica read at .150 return?
Show answer and explanation
Answer: It may return v1, Nia. Replication lag does not require a partition. A freshness guarantee needs an appropriate read protocol rather than an assumption that replicas instantly update.
Define C, A and P precisely
The CAP theorem considers a distributed shared-data system with possible communication partitions. Its formal meanings are narrower than the same words in everyday engineering.
| Term | Meaning for CAP | What it does not mean |
|---|---|---|
| Consistency, C | Operations behave like one copy with a real-time order: a read invoked after a successful completed write must respect that write or a later write | Every replica has identical bytes at every instant; every business validation rule; the C in ACID |
| Availability, A | Every operation submitted to a non-failing node eventually completes according to the object's operation contract, even when messages between partitions are lost | A particular latency deadline, a monthly uptime percentage, or merely sending an HTTP error |
| Partition tolerance, P | The guarantees are considered in executions where communication between groups of nodes can be lost | Every feature remains fully usable; database sharding; automatically choosing the right winner |
CAP's C is commonly called linearizability. Imagine a shared value that behaves as if each operation took effect at one instant between its invocation and its response. A read concurrent with a write can sometimes return the old value: the operations may be ordered either way. A read that starts after the write finishes cannot be placed before that completed write merely to justify an old result.
Availability is a termination property in the formal model; it does not supply a two-second response bound. A practical API still needs a deadline. Waiting forever for a missing region fails availability. Returning 503 cannot establish current state is an honest degradation response but does not complete the originally promised successful read of the shared value. Returning 202 queued changes a confirmed-write contract into an accepted-intent contract; it is not proof that the confirmed write succeeded.
Break the link, not the servers
Now the A–B replication link fails. Both regions are still running and reachable by their local users. Mira's update reaches A. If A continues accepting and acknowledging writes, it stores Sam/v2. B still has Nia/v1. A later reader reaches B after Mira received success. B cannot contact A to determine whether its local copy is current.
Read the diagram
Mira writes p17=Sam/v2 at A. Both servers and client paths remain alive. The inter-region link is broken; B retains Nia/v1. B either serves the explicitly permitted stale value or refuses a current-value read.
The red break belongs on the inter-region path, not on the client-to-server paths. A partition may be asymmetric, intermittent or limited to particular dependencies; it need not mean the whole Internet stopped. The theorem's difficult execution can keep that missing communication unavailable for arbitrarily long.
There are two illustrative read contracts for B. If the profile API permits stale public display data, B returns Nia and remains useful for that read, giving up the linearizable freshness promise. If the API promises a current value, B must obtain valid authority/evidence or decline that read while it cannot do so. Another design could refuse Mira's write instead. Something cannot finish successfully under the original strong contract in the problematic execution; the theorem does not dictate which region must refuse which request.
Why no clever retry removes the missing information
Consider two histories from B's point of view. In history H0, no update happened at A; the correct latest value is Nia. In H1, Mira's successful update happened at A; the correct latest value is Sam. B's stored record and received messages are identical in both histories because no cross-partition information arrives.
If B must complete its read in both histories, it cannot distinguish which value the strong contract requires. Always answering Nia is wrong in H1; guessing Sam is wrong in H0. Refusing the read or waiting for information gives up availability for that operation in this execution. Refusing the write at A avoids the completed-write history, but gives up availability for the write. This missing-information argument is the useful intuition behind the impossibility.
A retry at B is still missing the same information. Redirecting to A helps a particular client only if that client can reach A and the protocol establishes its authority; it does not guarantee completion for every client that can reach only B. Adding replicas helps some failures, but cannot guarantee that arbitrary partitions always leave every client a valid coordinating set.
Read operation histories instead of slogans
These three histories use one value, initially zero. The last row changes the API result rather than silently treating a refusal as a successful read.
| History | Operations | Interpretation |
|---|---|---|
| Completed write, then stale read | write(1) completes; later read() returns 0; no intervening write | Violates linearizability |
| Concurrent write and read | read() and write(1) overlap; the read returns 0 | May be linearizable if the read can be ordered before the write; inspect the whole history |
| Completed write, then refusal | write(1) completes; isolated reader gets unavailable | Can preserve the successful history's safety, but the read did not complete under the available-read promise |
Read the diagram
History 1: completed write(1), then read()=0 violates linearizability. History 2: overlapping read and write can allow 0. History 3: refusal preserves the strong-read boundary but sacrifices availability.
“Choose two of three” hides the condition that creates the impossibility. In a distributed system you must decide behavior when communication is partitioned. In healthy executions, CAP does not prohibit consistent successful operations. Nor does it say that a healthy system has no latency, replication or cost trade-offs. A single server avoids the inter-replica question for that object but adds its own failure and capacity boundaries; it is not a distributed system's escape from partitions.
Choose behavior for each operation
Start with a consequence, not an AP/CP label for an entire product. Which error is tolerable: an old display value, an unavailable confirmation, a duplicate owner, an invisible permission change or a lost edit? Ask the interviewer to choose the user-visible promise.
| Operation | Exercise promise | Behavior when required communication is missing |
|---|---|---|
| Public display name or movie description | Stale display is allowed under a declared freshness policy | Serve a copy; if a hard freshness limit cannot be established, apply the declared fallback |
| Confirm the last seat or decrement scarce stock | No more than the available entitlement may be committed | Coordinate at the current owner or under valid allocated rights; refuse confirmation if required authority is unavailable |
| Financial debit | Authorized atomic change with a declared overdraft rule | Preserve the invariant at its authority; a cached balance is not spending permission |
| Authorize access after revocation | Explicit revocation lifetime and security boundary | Validate current policy or a still-valid bounded capability; do not reuse cosmetic-profile staleness as an authorization rule |
| Save an offline draft | Accept divergent edits and retain enough history to merge | Save local intent/version; show pending/conflicted state until reconciliation |
| Create a match and notify users | One match identity; notification delay is allowed | Create idempotently at its owner; retry delivery separately instead of requiring both screens to update simultaneously |
Read the diagram
Two independent operation paths in one ticket product. Browse uses a permitted stale projection. Confirm requires current seat authority; missing authority cannot issue a confirmed ticket.
For ticketing, display a stale event description while a seat-confirmation path requires a current conditional change. An old “one seat left” label is an estimate, not a reservation. A provisional purchase request may remain available during an outage if the product explicitly says confirmation is pending; the app cannot present that state as a confirmed ticket.
A dating app similarly separates profile display, durable swipe intent, unique match creation and notification delivery. “Both users should see a match immediately” is a latency/product requirement, not the definition of CAP consistency. A correctly committed match can be notified later without being duplicated. For WhatsApp, durable server acceptance, recipient delivery and read receipts are separate states; CAP terminology alone does not define the messaging contract.
Compare consistency promises through observable results
These guarantees are not one simple ladder. In particular, causal ordering and session guarantees constrain different histories. Name which operations and clients receive the promise.
| Promise | Concrete test | Important limit |
|---|---|---|
| Linearizability | After write p17=v2 completes, a later read must respect v2 or a later update | Concurrent operations still need a valid ordering; durability is a separate guarantee |
| Read-your-writes | Mira's later reads do not omit her own successful update | Another user's read can remain stale; routing to an isolated replica may need waiting, refusal or another path |
| Monotonic reads | After this session sees v2, it does not later see the superseded v1 in this single-writer example | Requires a defined version/history comparison; does not make everyone globally current |
| Causal consistency | A comment that depends on post p5 is not exposed as if its prerequisite did not exist | Independent concurrent edits need not have one shared real-time order |
| Eventual convergence | After communication resumes and updates/reconciliation succeed, copies agree under the specified merge rules | No automatic maximum delay, preservation of every edit, or globally current read |
For read-your-writes, return the new representation or a session/version token after a successful edit. If Mira's next request reaches B at v1, the token tells the read path that B is not sufficient. It may route to an appropriate owner, wait within a deadline, or return an explicit outcome. That mechanism does not make B magically acquire v2 during isolation. A scalar v2 token is sufficient only under the version-order assumptions of this example; multiple writers need appropriate history metadata.
For a post and its dependent comment, record the dependency. A replica that receives the comment before the post can delay exposing it, retrieve the prerequisite when reachable, or use another declared product outcome. Wall-clock timestamps alone do not establish all causal relationships.
Read the diagram
Two separate guarantees. Session: Mira carries required v2 to replica B at v1; route, wait or refuse instead of silently omitting her write. Causal: comment c8 depends on post p5; exposing c8 needs its prerequisite.
Senior deep dive: a majority helps particular partitions
Replace the two-replica exercise with three participants, A, B and C, using a properly implemented majority-based consensus protocol. When A and B can communicate but C is isolated, the two-node group may commit new state under the protocol while C refuses operations that require current authority. It can still serve separately permitted stale display reads. When all three are isolated, no group has a majority and the strong path cannot progress.
Read the diagram
A and B can communicate and form a majority under the chosen consensus protocol. C is isolated and cannot establish current write authority. Term numbers need the complete protocol and fencing; they are not standalone proof.
For N=3, R=2 and W=2, read and write sets intersect because R+W>N. The intersection is arithmetic, not a full correctness proof. A read still needs to identify a valid committed version, concurrent writes need ordering, and a leader must establish current authority. Some quorum systems return older/conflicting values or acknowledge under different assumptions. Sloppy quorums, where temporary substitute nodes count toward responses, do not automatically have the same intersection property as a fixed replica set.
A paused former leader may resume after a new leader is elected. A lease timeout or increasing epoch is insufficient unless the destination/protocol rejects stale effects. Use the chosen protocol's authority and fencing rules. Never promote both sides merely because each timed out. A timeout cannot prove that the other side is dead rather than slow or isolated.
Read availability and write availability can differ. A cached read may complete while a quorum write cannot. A node can be healthy but unable to complete an operation safely. State where clients are routed and what a client stuck on C sees.
Staff deep dive: recover the promises you made
An availability-oriented edit API may accept writes at both regions. Suppose both begin with p17=Nia at the same base. A accepts operation a2 changing the name to Sam. B independently accepts b2 changing it to Ria. There is no causal order between those edits in this exercise. A scalar “version 2” on both sides does not tell you which write saw the other.
Read the diagram
Reconnecting permits reconciliation; it does not supply the product's conflict policy.
Retain stable operation identities and enough version/dependency information to detect concurrent edits. A deterministic winner rule can make replicas agree, but one user's requested value may be superseded. A clock-based last-write-wins policy has clock assumptions and can discard an edit; it is not the same as preserving both intentions. Alternatives include a user-visible conflict, a semantic merge for suitable data types, or an explicit authoritative decision. Explain that policy when accepting the write, not only after an incident.
For an exclusive seat, choosing one of two already confirmed owners afterward does not retroactively satisfy “never double-confirm.” Cancellation or compensation is a different contract. You can instead preallocate disjoint inventory rights to isolated regions; that changes what each region may sell without coordination. It preserves a bounded invariant within those allocated rights, but cannot make either region sell arbitrary inventory after its rights run out.
A strong-authority system also needs recovery. Rejoin an old replica by synchronizing committed state and rejecting obsolete authority before it serves the strong path. A client that timed out on a write has an unknown outcome, not proof of failure. Retry with the same operation identity, inspect authoritative state when reachable, and preserve the original result. CAP consistency does not itself prevent a duplicate payment or lost acknowledged data.
Healthy-network latency still matters
Suppose an exercise gives an inter-region round trip of 80 ms and a local processing allowance of 10 ms. A protocol needing one sequential remote round trip has at least roughly 90 ms of those costs before queueing, client transit and other work. A 30 ms end-to-end target cannot contain that 80 ms remote round trip under the stated assumptions. Place the authority nearer the workload, change the access path or renegotiate the promise. Adding a cache changes the freshness/authorization contract unless its validity is established.
The PACELC framing asks about partition-time availability versus consistency and, otherwise, latency versus consistency. It is a useful additional question, not a theorem that determines every database's fixed label. CAP also does not replace durability, transaction isolation, throughput, cost, failure recovery or security reasoning.
Connect guarantees to actual technology settings
Choose a product only after specifying the API, topology and failure behavior. “SQL is CP” and “NoSQL is AP” are too coarse to establish a guarantee.
| Technology or mechanism | What to check | What cannot be inferred from its name |
|---|---|---|
| PostgreSQL primary and standbys | Transaction isolation; commit acknowledgment; synchronous settings; standby replay visibility; failover ownership | Every standby read is current, or every committed write survives arbitrary failover |
| DynamoDB reads | Table/index type and selected read option; local versus cross-region topology | Multiple availability zones alone define an AP contract; a strong local read establishes global multi-region semantics |
| Read cache or CDC projection | Source position/version, lag, access policy and serving fallback | A derived copy automatically participates in the authority's transaction |
| Distributed transaction | Participant decision, coordinator failure, isolation and recovery | Two-phase commit alone establishes linearizable reads through every cache or stays available under every partition |
PostgreSQL's synchronous replication configuration determines which standbys a commit waits for; the documented default does not wait for replication. Also inspect synchronous_commit: waiting for remote persistence differs from waiting for replay visibility. DynamoDB supports strong reads on tables and local secondary indexes, but not global secondary indexes or streams; its read documentation distinguishes the selected option. Global-table configuration needs its own current documentation. Avoid extending a verified local guarantee to all regions or access paths.
Give a clear interview answer
Ask: Which operations must never return stale or conflicting results? What may be provisional? How long may display data be stale? What should a user on an isolated region see? Does an acknowledged write have to survive a region loss? Can clients route to another region? These questions separate safety, freshness, availability, durability and latency.
An original ticketing answer: “Browsing can use a replica within the agreed display policy. Confirming seat S requires a conditional change at the current inventory authority. If this region cannot establish that authority before the deadline, I’ll return confirmation-unavailable or the explicitly agreed pending state. I will not issue a confirmed ticket from the browse cache. A retry retains its request identity, and a timed-out operation is checked for an existing result.” Then draw the two paths and walk one race.
For foundation level, define the three terms in plain language and explain the two-region trace. For intermediate depth, distinguish normal lag, concurrent operations and an explicit stale-read contract. For senior depth, add operation-specific authority, majority failure cases, idempotent retry and user-visible SLIs. For staff depth, discuss allocated rights or merge semantics, authority changes, recovery, migration, security boundaries, cost and reversal criteria. These are teaching expectations, not a universal employer rubric.
Test the design and the explanation
Measure strong-path success and refusal separately from permitted stale-display success. Track replica lag, quorum loss, conflict/reconciliation backlog, unknown write outcomes and stale-authority rejections. A service-wide uptime average can hide a minority region where all confirmations fail. If you promise a maximum stale age, specify how it is established; a disconnected replica cannot infer unseen writes merely from a local timestamp.
| Fault or history | Evidence to collect |
|---|---|
| Cut A–B communication but leave client ingress alive | Which exact operations complete, refuse or become provisional? |
| Read after a completed write; separately read concurrently | Does the history satisfy the declared ordering guarantee? |
| Split three replicas 2:1; then 1:1:1 | Does only valid authority progress, and do minority clients see an explicit outcome? |
| Pause a writer, replace it, resume it | Are obsolete effects rejected at their destination? |
| Drop the successful write response, then retry | Is one operation identity reused and its committed result recovered? |
| Accept concurrent edits, then heal the link | Are both intents detectable and does the declared merge policy converge? |
| Revoke access while a copy is isolated | Does the serving path enforce the explicitly agreed security lifetime? |
Diagnose these histories before revealing the answer
- A write completes; B returns the old value afterward. Which promise fails?
- A read overlaps a write and returns the old value. Is that automatically a violation?
- The isolated side responds
503immediately. Is the successful-read object CAP-available there? - Two sides confirm the last seat; recovery later cancels one. Was the original no-double-confirmation promise kept?
- A public profile read may be stale. May its cached permission flag authorize a private document?
- With N=3 and a two-node majority, can the isolated node guarantee current writes?
- A timed-out debit is retried with a new identity. Does choosing strong consistency alone prevent a second debit?
- A profile converges after recovery. Does that establish read-your-writes during the partition?
Show answer and explanation
Answer: 1: Linearizability, assuming no intervening write justifies the old result. 2: No; inspect invocation/completion overlap and the complete history. 3: No for that successful-read contract, although it is an appropriate practical refusal. 4: No; compensation changes the contract. 5: No; authorization needs its own current or bounded-capability policy. 6: No; it cannot establish a valid majority by itself. 7: No; request identity and authoritative outcome handling remain necessary. 8: No; eventual agreement does not establish a session guarantee for earlier reads.
Continue with a concrete design
Apply this worksheet to Ticketmaster, WhatsApp, Dealing with Contention and Data Modeling. For each, name one authoritative operation, one derived read and one partition-time user outcome. Draw the broken communication path and record the states on both sides before choosing a technology.
Primary sources and scope
The formal definitions and impossibility are grounded in Gilbert and Lynch's CAP paper. Brewer's later discussion addresses partition behavior and recovery. The examples and drawings here are independently authored teaching exercises.
Check PostgreSQL replication settings, PostgreSQL synchronous commit, DynamoDB read consistency and Abadi's PACELC discussion for the exact boundaries. Database settings and service options evolve; the worked design does not claim a fixed universal CAP label for a product.
Shared foundation: Replication, Durability and Failover
Replication, Durability and Failover: Separate durable acknowledgement, read visibility and safe promotion through a concrete replica history. Work its failure history before extending this design.
Can both isolated replicas confirm the final seat and still guarantee that only one buyer owns it?
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.