Skip to content

CAP Under a Real Partition, CP vs AP, PACELC & Tunable Consistency ​

"The "2 of 3" formulation was always misleading because it tended to oversimplify the tensions among properties." — Eric Brewer, CAP Twelve Years Later: How the "Rules" Have Changed, IEEE Computer, February 2012 (InfoQ reprint)

Summary: When the network between replicas fails, every operation that needs both sides must either wait or answer without the other side; CAP names that choice, PACELC adds the price of consistency on a normal day (latency), and tunable consistency lets you pay it per request instead of per database. Focus: What Brewer conjectured in 2000 and what Gilbert and Lynch proved in 2002 (C = linearizability, A = every non-failing node answers, P = arbitrary message loss), what CAP does not say (the CA myth, "pick two", no partition means no choice), Brewer's partition lifecycle (detect, partition mode, recovery, compensation), CP and AP behaviour with the exact knobs of etcd, ZooKeeper, Consul, Cassandra, DynamoDB, MongoDB, PostgreSQL, Kafka, Spanner and CockroachDB, PACELC (PA/EL, PC/EC, PA/EC, PC/EL), quorums and R + W > N, sloppy quorums, hinted handoff and read repair, harvest and yield, split brain and fencing, and deciding per data item, with Go and Laravel code and a lab. Learning goal: For any data item in a design, say what happens to its reads and writes on each side of a partition and on a normal day, pick the product knob that gives that behaviour, write the partition-mode and recovery rules (including compensation), and explain why "the database is CP" is not a sufficient answer.

This chapter opens the Consistency & Distributed Data group. It owns the system-level decision: which guarantee each operation needs during a partition and on a normal day, and which knob delivers it. The models themselves (linearizability vs serializability, causal, read-your-writes) are taught in Consistency Models; the engines' replication mechanics in Eventual Consistency in Database Systems, Replication, Read Replicas & Failover and Distributed SQL, Consensus & 2PC; topologies and conflict resolution in Replication Topologies; repair internals in Merkle Trees, Read Repair, Anti-Entropy & Tombstones; leases and fencing in Distributed Locking and Leader Election; mergeable data in CRDTs; the user experience of eventual consistency in Event-Driven Architecture; ACID vs BASE in ACID vs BASE.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why a partition forces a choice at allWhy it exists
Fox and Brewer 1999, Brewer 2000, Gilbert and Lynch 2002, Abadi 2012, Kleppmann 2015Where it comes from
The exact statement and its three definitionsCAP, Linearizability, Availability, Partition
"CA systems" and "pick two"What CAP does not say
What to do while partitioned and afterPartition mode, Compensation
Which products refuse and which divergeCP in products, AP in products, Split brain and fencing
The latency half of the trade-offPACELC
R + W > N, Cassandra levels, sloppy quorumsQuorums, Cassandra levels, Sloppy quorums
Product knobs one by oneetcd/ZooKeeper/Consul, MongoDB, PostgreSQL, Kafka, Spanner/CockroachDB, DynamoDB
Partial answers instead of errorsHarvest and yield
Money vs likesDeciding per data item, Eventual-consistency UX
Formulas, knobs, error messagesMechanics
CodeGo, Laravel
Classic incidents and fixesSolving the classic problems
Which setting whenChoosing
From one process to many regionsIn architecture
Run it yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The theorem, with its real definitions (Gilbert and Lynch 2002).

LetterMeans in the proofDoes not mean
C (consistency)Linearizability (atomic consistency): one total order of operations, each taking effect at an instant between its call and its return; a read that starts after a write finished returns that write or a later oneThe C of ACID (constraints), or "data is not corrupted"
A (availability)"every request received by a non-failing node in the system must result in a response""High availability", 99.99% uptime, or "some node answers"
P (partition tolerance)Correct behaviour even when "the network will be allowed to lose arbitrarily many messages sent from one node to another"An option you can switch off: networks do lose messages
The resultDuring a partition, an operation that needs both sides cannot be both linearizable and answered by every live node"You may pick any two of C, A and P at all times"

The partition decision in real products (default or most common setting, then the knob that moves it).

ProductDuring a partition, by defaultKnob
etcdMajority side serves; minority returns etcdserver: request timed out / no leader (CP)--consistency=s (serializable) reads answer on the minority, possibly stale
ZooKeeperWrites need a majority (CP); reads are served by the connected server, not linearizablesync() before a read; read-only mode lets the minority serve reads
ConsulHTTP API default mode needs the leader; DNS uses stale mode?consistent (extra quorum round trip) or ?stale
CassandraDepends on the consistency level per request: ONE answers (AP), QUORUM may fail with UnavailableException (CP-like)ONE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL, SERIAL
DynamoDBEventually consistent reads (default); global tables MREC replicate asynchronously, last writer winsConsistentRead=true; MRSC global tables (three Regions)
MongoDBPrimary on the majority side; { w: "majority" } is the usual default; minority has no primarywrite concern w, wtimeout; read concern local/majority/linearizable; read preference
PostgreSQLAsynchronous streaming replication by default: primary keeps committing, standbys lagsynchronous_standby_names + synchronous_commit (remote_apply, on, remote_write, local, off)
Kafkaacks=all (producer default) waits for the ISR; ISR may shrink to the leader alone (min.insync.replicas=1 default)min.insync.replicas=2; unclean.leader.election.enable=false (default)
Spanner, CockroachDBPaxos/Raft majority per range or split: minority side unavailable (CP)Replica placement; follower/stale reads trade freshness for locality

PACELC classification (Abadi 2012, default settings).

ClassDuring a partitionElse (normal operation)Examples from the paper and docs
PA/ELStay availableLow latency over consistencyDynamo, Cassandra and Riak defaults; DynamoDB eventually consistent reads
PC/ECStay consistentConsistency over latencyVoltDB/H-Store, Megastore, BigTable, HBase; Spanner, CockroachDB, etcd (by their docs)
PA/ECStay available (old primary's writes roll back later)Consistent reads and writesMongoDB, as classified by Abadi in 2012
PC/ELNo extra loss of consistency, availability dropsLatency over consistencyYahoo PNUTS
One partition, two answers: CP refuses on the minority side, AP accepts and divergesCP: R=2, W=2 (majority)AP: R=1, W=1, hintsn0n1n2n0n1n2partitionpartitionwrite "left": ok (2 of 3)read: "left"write: unavailableread: unavailable(alive, refuses)write "left": okread: "left"write "right": okread: "right"(diverged)heal: n2 catches up (anti-entropy)replicas = left, left, leftnothing acknowledged is lostheal: hints + anti-entropy, last write winsreplicas = right, right, right"left" was acknowledged, now discarded

The picture is the whole theorem in one experiment: three replicas, a cut between n0/n1 and n2. With majority quorums the minority node refuses (it is alive but not available in the CAP sense); with single-replica reads and writes both sides answer, diverge, and on heal one acknowledged value is thrown away by last-write-wins. The Go simulation in Go reproduces exactly this.

Why it exists ​

Replication exists so that data survives a machine and is close to its users. The moment there are two copies, an update must reach both, and the network between them is not reliable: links fail, switches are misconfigured, a GC pause or a full queue delays a heartbeat until it looks like a failure. A replica that cannot hear from its peers has two honest options for a request that depends on them: wait (or refuse) and stay correct, or answer from what it has and risk being wrong. There is no third option that is both.

Prefer consistency (CP for this operation)Prefer availability (AP for this operation)
Minority side returns errors or times outEvery live replica answers
Every answer is linearizableAnswers may be stale; concurrent writes conflict
Invariants (balance ≥ 0, unique username) hold automaticallyInvariants must be restored after the partition (compensation)
Needs a majority, a leader or a leaseNeeds conflict resolution: last-write-wins, merge, CRDT
Costs latency every day (quorum round trips)Costs reconciliation work and UX design
Good for money, stock, locks, configuration, unique namesGood for carts, likes, feeds, presence, telemetry

The everyday picture used through this page: two bank branches that share one account book by telephone. When the line is cut, each branch can either stop paying out cash until the line is back (consistent, not available), or keep paying out against its own copy of the book and sort it out later (available, not consistent). Brewer's real ATM answer is in between: pay out up to a small limit, write everything down, and charge an overdraft fee if the books do not add up later. That in-between answer, partition mode plus compensation, is what real systems do.

Three common misunderstandings, up front ​

  1. "Pick two of three." You do not pick P; partitions happen to you. And when there is no partition, CAP allows both C and A. Brewer 2012: "because partitions are rare, there is little reason to forfeit C or A when the system is not partitioned."
  2. "Our database is CP, so we are consistent." Most real configurations are neither CP nor AP in the strict sense. Kleppmann shows single-leader replication with follower reads is "neither CAP-consistent nor CAP-available", and ZooKeeper by default does not give linearizable reads. Classify operations and settings, not products.
  3. "Eventual consistency is the price of availability." Many systems are eventually consistent on a normal day for latency, not because of partitions. Abadi: "it is wrong to assume that DDBSs that reduce consistency in the absence of any partitions are doing so due to CAP-based decision-making." That is the ELC half of PACELC.

Where it comes from ​

text
     Year   Who / what                                   What it added
1    1999   Fox & Brewer, "Harvest, Yield, and            "Strong CAP Principle ... Pick at most 2"; harvest vs yield
            Scalable Tolerant Systems" (HotOS)
2    2000   Brewer, PODC keynote (July 19)                "You can have at most two of these properties for any
                                                          shared-data system"; ACID vs BASE as a spectrum
3    2002   Gilbert & Lynch, SIGACT News                  Formal proof: asynchronous model, atomic (linearizable)
                                                          object, availability, arbitrary message loss
4    2007   DeCandia et al., Dynamo (SOSP)                (N,R,W) quorums, sloppy quorum, hinted handoff, (3,2,2)
5    2010   Abadi, blog "Problems with CAP"               Latency/consistency trade-off named; PACELC first sketched
6    2012   Brewer, "CAP Twelve Years Later"              Partition mode, recovery, compensation; CA is probabilistic
6    2012   Abadi, IEEE Computer                          PACELC: PA/EL, PC/EC, PA/EC, PC/EL
6    2012   Gilbert & Lynch, "Perspectives on CAP"        CAP as one case of safety vs liveness
7    2015   Kleppmann, blog and arXiv "A Critique of      "Please stop calling databases CP or AP"; delay-sensitivity
            the CAP Theorem"
8    2017   Brewer, "Spanner, TrueTime & the CAP Theorem" "technically a CP system", "effectively CA"

Fox and Brewer (1999). The first written form: "Strong CAP Principle. Strong Consistency, High Availability, Partition-resilience: Pick at most 2." In the same paper they already soften it ("a Weak CAP Principle which we have yet to characterize precisely") and introduce harvest and yield as the engineering answer: give a partial answer instead of no answer.

Brewer at PODC 2000. The keynote slide titled "The CAP Theorem" reads "Theorem: You can have at most two of these properties for any shared-data system", with examples per corner: single-site and cluster databases for "forfeit partitions", distributed databases, distributed locking and majority protocols for "forfeit availability" ("Make minority partitions unavailable"), Coda, web caching and DNS for "forfeit consistency". The talk also framed ACID vs BASE ("Basically Available, Soft-state, Eventual consistency") and said "But I think it's a spectrum".

Gilbert and Lynch (2002). They turned the conjecture into a theorem with precise definitions (see CAP) and proved it by a two-group argument: if all messages between groups G1 and G2 are lost, a write in G1 followed by a read in G2 cannot return the write. They also proved the partially synchronous version and noted, for quorum systems, "if certain failure patterns occur, then the liveness condition is weakened and the service no longer returns responses."

Abadi (2010 blog, 2012 article). Observed that the systems usually cited as "AP" give up consistency all the time, not only during partitions, and that the reason is latency. PACELC adds the "else" branch.

Brewer (2012). Rewrote the advice for practitioners: CAP is about the timeout ("a partition is a time bound on communication"), partitions should be managed explicitly ("detect the start of a partition", "enter an explicit partition mode", "initiate partition recovery"), and mistakes made in partition mode are fixed by compensation.

Kleppmann (2015). Showed that the strict definitions classify almost nothing cleanly and proposed reasoning about how operation latency depends on network delay instead. His blog post is the shortest correction to "CP vs AP" marketing.

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline or request flow, real scenarios, what products do, and the fix.

CAP, stated precisely Must-know ​

In plain words: if the replicas cannot talk, a replica that receives a request needing the other side must either wait or answer without it. Waiting forever is unavailability; answering without it can be wrong.

Common misunderstanding: "CAP says a distributed database can only have two of three properties, always." The theorem is a statement about executions in which messages are lost. With no loss, a system can be both consistent and available (Gilbert and Lynch, section 3.2.2: "If there are no partitions, it is clearly possible to provide atomic, available data").

Definition: Gilbert and Lynch, Theorem 1: it is impossible in the asynchronous network model to implement a read/write data object that guarantees availability and atomic consistency in all fair executions, including those in which messages are lost. Theorem 2 repeats the result for a partially synchronous model where nodes have clocks: "It is still impossible to have an always available, atomic data object when arbitrary messages may be lost". Corollary 1.1 is the subtle one: because a node cannot tell a lost message from a slow one, you cannot even promise consistency only in executions without loss while staying always available.

text
     The proof in four lines (two groups G1 = {n0, n1}, G2 = {n2}; every message between them is lost)
1    client A -> n0: write(x = 1)       n0 must answer (availability), so it acknowledges without G2
2    client B -> n2: read(x)            starts after step 1 finished
3    n2 cannot have heard of the write  all G1 -> G2 messages were lost
4    n2 must answer (availability)      it returns the old value: not linearizable. Contradiction.

Real scenario: a payment service across two availability zones loses the inter-zone link for 40 seconds; a Kubernetes control plane loses a node from the etcd majority; a mobile app works offline (an infinitely long partition between the phone and the server); a multi-region database during a cable cut.

What products do: every replicated product chooses per operation. Majority-based systems (etcd, ZooKeeper writes, Consul, Spanner, CockroachDB, MongoDB primaries) refuse on the minority side; Dynamo-style stores at low levels (Cassandra ONE, Riak r=1) answer on both sides.

Fix / how to use it: in a design document, write for each operation: "during a partition, on the minority side, this operation (a) waits up to N ms then fails, (b) answers from local data, or (c) answers with a bounded risk". Then pick the knob.

Consistency in CAP is linearizability Must-know ​

In plain words: the system behaves as if there were one copy of the data and every operation happened at one instant between its start and its end. Once any client has seen a value, nobody may see an older one.

Common misunderstanding: "CAP consistency is the C in ACID" or "serializable transactions are CAP-consistent". ACID consistency means constraints hold; serializability is about transactions being equivalent to some serial order, not necessarily the real-time one. Kleppmann: "Consistency in CAP actually means linearizability, which is a very specific (and very strong) notion of consistency." PostgreSQL's SSI gives serializability, not linearizability (Kleppmann). Gilbert and Lynch's footnote makes the same distinction.

Definition: Gilbert and Lynch 2.1: "there must exist a total order on all operations such that each operation looks as if it were completed at a single instant." Consequence: "any read operation that begins after a write operation completes must return that value, or the result of a later write operation." The full family of models is in Consistency Models.

text
     Client A                         Client B                        Linearizable?
1    write(x = 2) starts
2    write(x = 2) returns ok
3                                     read(x) starts and returns 1    NO: the read began after the write completed
     ---- versus ----
1    write(x = 2) starts
2                                     read(x) starts and returns 1    yes: the write had not completed
3    write(x = 2) returns ok

Real scenario: a leader lease stored in etcd (two leaders if a stale read says the lease is free); a unique username check; a seat map where two people must not book the same seat; a config flag that must be off everywhere once the API says it is off.

ProductLinearizable pathNot linearizable by default
etcdEvery operation except watch ("etcd ensures linearizability for all other operations by default")--consistency=s reads; watches
ZooKeeperWrites; reads preceded by sync()Plain reads (served by the connected server)
MongoDBreadConcern: "linearizable" on the primary, single document, plus w: "majority" writeslocal, majority (majority-committed but may be behind)
CassandraLightweight transactions (IF conditions) with SERIAL / LOCAL_SERIALQuorum reads and writes (Kleppmann: sloppy quorums and read repair edge cases)
SpannerEvery read-write transaction and strong read (external consistency)Stale reads with a timestamp bound
PostgreSQLReads on the primaryReads on a standby (unless remote_apply and careful routing)

Fix / how to use it: require linearizability only for operations that need it (locks, uniqueness, balances, leader election), and use the product's explicit linearizable path for exactly those calls.

Availability in CAP Must-know ​

In plain words: every live node that receives a request gives an answer, eventually, even if it cannot talk to anyone.

Common misunderstanding: "Our cluster has 99.99% uptime, so it is available in the CAP sense." CAP availability is far stronger in one way (every non-failing node, not just "the service") and far weaker in another (no deadline at all). Kleppmann: "Many so-called "highly available" (i.e. low downtime) systems actually do not meet this definition of availability." Any single-leader database fails it: a client partitioned from the leader cannot write.

Definition: Gilbert and Lynch 2.2: "every request received by a non-failing node in the system must result in a response." They add that "it puts no bound on how long the algorithm may run before terminating". Brewer 2012 brings back the deadline: the partition decision happens at a timeout.

text
     Three replicas, partition {n0, n1} | {n2}, client talks to n2
1    t=0      client -> n2: write(x)
2    t=0+     n2 sends to n0, n1; messages are lost
3    t=500ms  n2's timeout fires
4    CP choice: n2 returns an error            -> not CAP-available (node is alive and refused)
5    AP choice: n2 stores x and returns ok     -> available; consistency is now at risk

Real scenario: a shopping cart that must accept "add to cart" during any failure (Dynamo's motivation: "customers should be able to view and add items to their shopping cart even if disks are failing, network routes are flapping, or data centers are being destroyed by tornados"); a status page; a telemetry ingest endpoint.

Fix / how to use it: state availability as an SLO with a deadline and a scope ("p99 under 300 ms from any region with one region lost"), not as a CAP letter; see SLAs, SLOs, SLIs & Error Budgets.

Partitions: what they really are Must-know ​

In plain words: a partition is any situation in which some replicas cannot get messages to others in time. A cable cut, a misconfigured firewall, a crashed switch, an overloaded node that answers after the timeout, a GC pause: from the outside they look the same.

Common misunderstanding: "Partitions are rare events where the network splits cleanly in two." They are often partial (A sees B, B sees C, A does not see C), one-sided (A's messages reach B but not the reverse), and short. Brewer: "there is no global notion of a partition, since some nodes might detect a partition, and others might not." And "a partition is a time bound on communication": if you lower your timeout, you will see more partitions.

Definition: Gilbert and Lynch model it as message loss: "any pattern of message loss can be modeled as a temporary partition separating the communicating nodes at the exact instant the message is lost." In practice a node declares a partition when a timeout fires.

text
     A one-sided partition (A -> B works, B -> A is dropped by a firewall rule)
1    A: heartbeat -> B           B receives it, thinks A is fine
2    B: ack -> A                 dropped
3    A: no ack within 1 s        A declares B dead, B does not declare A dead
4    A (if leader) steps down; B keeps sending writes to A      -> each side has a different view

Real scenario: an AWS availability zone with packet loss but not total loss; a long GC pause on a ZooKeeper leader that makes followers elect a new one; Kubernetes nodes losing the API server while their pods keep serving; a WAN link at 100% utilisation. How common is it? Brewer 2017 reports, for Spanner's incident causes, "The Network category, under 8%, is where partitions and networking configuration problems appear."

Fix / how to use it: treat timeouts as the partition detector and set them deliberately per operation (see Timeouts, Retries & Jitter); design for partial and one-sided partitions, not only clean splits; test them (Chaos Engineering).

What CAP does not say: the CA myth and "pick two" Must-know ​

In plain words: you cannot choose "CA" for a distributed system, because you cannot choose to have no partitions. You choose what happens when one occurs.

Common misunderstanding: "A single-site relational cluster is a CA system." Fox and Brewer listed "CA without P" (distributed transactions "can only do so in the absence of a network partition"), but Brewer 2012 corrects it: "If the choice is CA, and then there is a partition, the choice must revert to C or A. It is best to think about this probabilistically: choosing CA should mean that the probability of a partition is far less than that of other systemic failures."

Definition: "CA" is meaningful only as a probability statement: partitions are rare enough, inside one datacenter or on Google's private network, that users can ignore them. Brewer 2017 on Spanner: "It is technically a CP system", but it can justify an "effectively CA" claim because its availability is high enough ("better than 5 9s" internally).

text
     The "pick two" story vs what actually happens in a CA-labelled system
1    Normal day: two-node cluster, synchronous replication     looks C and A
2    Link between nodes fails
3    Option 1: both keep accepting writes                      now AP (split brain risk)
4    Option 2: one stops (quorum, fencing, manual)              now CP
5    There is no option 3                                       "CA" just meant "we had not decided"

Real scenario: a two-node PostgreSQL pair with automatic failover and no witness, which promotes the standby while the old primary is still accepting writes; a two-datacenter active-active MySQL with "CA" in the architecture slides; a Redis primary/replica pair behind Sentinel with only two Sentinels.

Fix / how to use it: never write "CA" in a design for a multi-node system; write which side keeps working (majority, a witness, a designated primary region) and what the other side does. Use an odd number of voters or a witness (DynamoDB MRSC uses "two replicas and one witness").

The partition lifecycle: detect, partition mode, recovery Must-know ​

In plain words: treat a partition as a mode your system enters on purpose, with its own rules, and leaves with a clean-up procedure.

Common misunderstanding: "CP or AP is a static property; nothing to design." Brewer's main advice in 2012 is the opposite: "The key idea is to manage partitions very explicitly, including not only detection, but also a specific recovery process and a plan for all of the invariants that might be violated during a partition."

Definition: three steps (Brewer 2012): "detect the start of a partition", "enter an explicit partition mode that may limit some operations", and "initiate partition recovery when communication is restored". In partition mode the two strategies are to "limit some operations, thereby reducing availability" or to "record extra information about the operations that will be helpful during partition recovery". Recovery has two jobs: make the state consistent again, and compensate for mistakes made while partitioned.

A partition has a lifecycle: detect, partition mode, recovery with compensationState Snormal operationpartition startsdetected (timeout)Side A: state S1partition mode, log opsSide B: state S2partition mode, log opslink restoredState S'merged from logscompensate brokeninvariants (fees, refunds)normalpartition mode: limit risky ops, record extra infopartition recoveryno global notion of a partition:each node decides by its own timeout
text
     ATM example (Brewer 2012), balance 100, stand-in limit k = 200
1    t0   ATM -> bank: authorise(150)       normal mode: bank says ok, balance 100 is not enough -> refused
2    t1   link fails; ATM times out          partition detected -> stand-in (partition mode)
3    t2   withdraw 150                       net withdrawn 150 <= 200 -> approved, logged
4    t3   withdraw 100                       150 + 100 > 200 -> refused (bounded risk)
5    t4   deposit 20                         always allowed (cannot break balance >= 0), logged
6    t5   link restored                      recovery: replay log, balance 100 - 150 + 20 = -30
7    t6   invariant broken                   compensation: overdraft fee, repayment request

Real scenario: ATMs and card terminals (offline floor limits); point-of-sale systems in shops with flaky connections; airline check-in that overbooks and compensates at the gate (Brewer's overbooking example); offline-first mobile apps that queue edits; a warehouse system that keeps picking orders during a WAN outage and reconciles stock later.

Product / patternPartition mode feature
Riak, CassandraAccept writes on both sides; record versions (vector clocks in Riak, timestamps in Cassandra)
DynamoDB global tables MRECEach Region keeps accepting writes; "last writer wins" on reconciliation
CouchDB-style sync, offline appsLocal writes with revision history; conflicts exposed after sync
Payment terminals, ATMsFloor limit / stand-in limit, local log, batch upload
SagasCompensating transactions (Saga Pattern)

Fix / how to use it: for each invariant, decide "keep during partition (limit the operation)" or "risk it and restore later (log and compensate)". The Go atm package is this exact procedure.

Compensation and invariants Important ​

In plain words: if you let both sides keep working, some rules will be broken; compensation is the business action that repairs the damage after the fact: a refund, a fee, an apology email, cancelling a duplicate.

Common misunderstanding: "Last-write-wins or a CRDT merge solves conflicts, so there is nothing to compensate." Merging fixes the state; it does not undo externalised actions (cash given out, an email sent, a seat promised). Brewer: "Recovering from externalized mistakes typically requires some history about externalized outputs."

Definition: a compensating operation restores an invariant or reverses an effect; it is defined by the business, not by the database. Brewer: "designers must create compensating operations that both restore an invariant and more broadly correct an externalized mistake." Commutative operations make state convergence automatic ("Restoring state is easy because the operations are commutative"), compensation handles what convergence cannot.

text
     Duplicate order during a partition (Brewer's example, as a sequence)
1    Side A: order #A1 for user 7, charge card         externalised (money moved)
2    Side B: order #B1 for user 7, same cart, charge    externalised again
3    Recovery: logs merged, two orders with identical content within 30 s
4    Decide: intentional or duplicate? (idempotency key would have told us)
5    Compensate: cancel #B1, refund, email "we charged you twice by mistake and refunded"

Real scenario: airline overbooking; double-charged cards after a retry storm; two warehouses shipping the last unit; two users registering the same username in two regions (rename one); a feature flag flipped differently on each side.

Fix / how to use it: delay externalised actions until the truth is known when you can ("This is another reason to delay risky operations"); give every operation an idempotency key so duplicates are detectable (API Idempotency); keep an operation log, not just state; and write the compensation alongside the feature.

CP behaviour in real products Must-know ​

In plain words: a CP setting keeps working only where a majority (or the leader, or the lease holder) is reachable; everywhere else it returns errors rather than possibly wrong answers.

Common misunderstanding: "CP means the system goes down during a partition." Only the minority side does, and only for operations that need the majority. The majority side keeps serving. Fox and Brewer: "replicas and majority voting to get PC (the minority is unavailable)."

Definition: an operation is CP-configured when it needs acknowledgements from a quorum that intersects every other quorum (majority, Raft/Paxos, or R + W > N with strict membership) and fails when it cannot get them.

text
     etcd, 3 members, partition {m1, m2} | {m3}, client on m3
1    client -> m3: put /lock/leader = svc-b
2    m3 is a follower; it forwards to the leader m1             lost
3    after the request timeout                                  "etcdserver: request timed out" (gRPC Unavailable)
4    client -> m3: get /lock/leader (default linearizable)      needs consensus -> fails or times out
5    client -> m3: get /lock/leader --consistency=s             answers from m3's local store: possibly stale

Real scenario: Kubernetes API servers keep working against the etcd majority, nodes in a cut-off zone cannot change cluster state; a Kafka topic with min.insync.replicas=2 rejects writes when only the leader is left (NOT_ENOUGH_REPLICAS); a MongoDB replica set where the old primary steps down on the minority side; CockroachDB ranges whose Raft majority sits on the other side of the cut.

ProductQuorum ruleMinority-side behaviourError you see
etcdRaft majorityWrites and linearizable reads failetcdserver: request timed out, etcdserver: no leader
ZooKeeperMajority (ZAB) for writesWrites fail; reads still served from the local serverconnection loss / session expiry in client
ConsulRaft majoritydefault and consistent reads fail; stale worksHTTP 500 "No cluster leader" (typical)
MongoDBMajority elects a primaryNo primary; writes fail; primaryPreferred/secondary reads workNotWritablePrimary (10107), PrimarySteppedDown (189)
KafkaISR, min.insync.replicasWrites with acks=all rejected when ISR too smallNOT_ENOUGH_REPLICAS (19)
CockroachDBRaft majority per rangeRanges without majority unavailablestatement hangs, then retry/timeout errors
SpannerPaxos majority per splitSplits without majority unavailableUNAVAILABLE / deadline exceeded (typical gRPC)
PostgreSQL sync repNamed synchronous standbysCommits wait for the standby, possibly forevercanceling wait for synchronous replication due to user request when cancelled

Fix / how to use it: put an odd number of voters across three failure domains so that any one domain can be lost; give clients timeouts and a clear error to show ("temporarily unavailable, try again"); route clients to the majority side when you can (Load Balancing).

AP behaviour in real products Must-know ​

In plain words: an AP setting answers from whatever replicas are reachable and fixes disagreements later.

Common misunderstanding: "AP means no consistency at all." AP settings usually give eventual consistency plus specific session guarantees, and converge through hinted handoff, read repair and anti-entropy; what they cannot give is linearizability during the partition.

Definition: an operation is AP-configured when it succeeds with acknowledgements from any reachable replica (R or W of 1, sloppy quorums, local reads), accepting divergence and resolving conflicts by a rule (last write wins, siblings, CRDT merge).

text
     Cassandra RF=3, partition {r1, r2} | {r3}, writes at ONE on both sides
1    client X -> r1: UPDATE cart SET items = items + {'book'}   ONE: r1 acks; r2 gets it; r3 gets a hint later
2    client Y -> r3: UPDATE cart SET items = items + {'pen'}    ONE: r3 acks
3    client Y -> r3: SELECT items (ONE)                         {'pen'}       (does not see 'book')
4    heal: hints replayed, read repair, repair                  {'book','pen'} set elements merge per element
5    but for a plain column: last write wins by timestamp       one of two values is gone

Real scenario: Amazon's shopping cart (Dynamo: "an 'add to cart' operation is never lost", deleted items may resurface); likes and view counters; presence ("online" dots); IoT telemetry ingest; DNS (Brewer listed it under "forfeit consistency").

ProductAP settingConvergence mechanismConflict rule
Dynamo (paper)Sloppy quorum, (3,2,2) common, W=1 for highest availabilityHinted handoff, Merkle-tree anti-entropyVector clocks; client merges siblings
CassandraONE, LOCAL_ONE, ANYHints, read repair, nodetool repair (Merkle trees)Last write wins per column by timestamp
Riak KVr, w below quorum; sloppy quorum by default (PR = PW = 0)Hinted handoff, read repair, active anti-entropyVector clocks / siblings or LWW
DynamoDBEventually consistent reads; MREC global tablesInternal replication "typically within a second or less""last writer wins" across Regions
Consul?stale reads and DNSRaft log catch-upn/a (reads only)
ZooKeeperRead-only mode (since 3.4.0) on the minorityRejoin the quorumn/a (reads only)

Fix / how to use it: make AP data mergeable (sets, counters, CRDTs: CRDTs); avoid read-modify-write on AP data; show staleness in the UI; and run repair on a schedule (Merkle Trees, Read Repair, Anti-Entropy & Tombstones).

Split brain and fencing Important ​

In plain words: split brain is two nodes both believing they are the leader and both accepting writes. Fencing is how the old one is stopped from doing damage.

Common misunderstanding: "Leader election guarantees one leader." It guarantees at most one leader per term as seen by a majority; an old leader that has not heard the news can still act. MongoDB documents it: "two nodes in a replica set may transiently believe that they are the primary, but at most, one of them will be able to complete writes with { w: "majority" } write concern."

Definition: fencing attaches a monotonically increasing token (term, epoch, lease revision) to every write so that storage rejects writes from an older token; or it cuts the old node off physically (STONITH). Details in Distributed Locking and Leader Election.

text
     Old primary P1 on the minority side, new primary P2 elected on the majority
1    P1 (term 5) still believes it is primary     accepts write w=1 from a client on its side
2    P2 (term 6) accepts writes on majority side
3    with w:majority, P1 cannot get 2 of 3 acks   the client gets a write concern error or timeout
4    with w:1, P1 acknowledges                    the write is later rolled back when P1 rejoins
5    storage with fencing: rejects any write tagged term 5 after it has seen term 6

Real scenario: two PostgreSQL primaries after a failover tool promoted a standby without fencing the old primary; a Redis Sentinel failover where clients still write to the old master; a cron "leader" that runs the nightly billing twice; Kafka's unclean leader election electing an out-of-sync replica.

Fix / how to use it: majority writes (w: "majority", acks=all + min.insync.replicas, Raft) so a stale leader cannot acknowledge; fencing tokens on external side effects; leases shorter than the failure detector's timeout; an odd number of voters.

PACELC: the trade-off when nothing is broken Must-know ​

In plain words: CAP only talks about bad days. On normal days, consistency still costs something: waiting for other replicas. PACELC asks both questions.

Common misunderstanding: "If partitions are rare, CAP does not matter and we can have everything." Partitions are rare, but replication latency is constant. Abadi: CAP "is only relevant in the arguably rare case of a network partition", while the latency trade-off "is present at all times during system operation".

Definition: Abadi 2012: "if there is a partition (P), how does the system trade off availability and consistency (A and C); else (E), when the system is running normally in the absence of partitions, how does the system trade off latency (L) and consistency (C)?" Abadi notes the ELC part "only applies to systems that replicate data".

PACELC: if Partition, A or C; Else, L or C (defaults; per-request knobs move a system)1. Is the network partitioned (P)?PA: stay available2. else (E): L or C?PC: stay consistent2. else (E): L or C?PA/ELDynamo (paper)Cassandra, Riak defaultsDynamoDB eventual readsDynamoDB global tables MRECPA/ECMongoDB(Abadi 2012: consistentreads normally; old primaryrolls back after a split)PC/ELYahoo PNUTS(local master, asyncremote copies; no extraloss when partitioned)PC/ECSpanner, CockroachDBetcd, ZooKeeper writesVoltDB, BigTable, HBaseDynamoDB MRSCTunable systems change box per request: Cassandra QUORUM or LOCAL_QUORUM, DynamoDB ConsistentRead=true,MongoDB w:majority + readConcern linearizable, etcd serializable reads. Classify operations, not databases.
text
     Same write, no partition, replicas in Frankfurt (coordinator), Frankfurt, Virginia
1    EL setting (W=1)       ack after the local replica writes        ~1 ms
2    EC setting (W=2 of 3)  ack after the second Frankfurt replica   ~2 ms
3    EC setting, if the second-nearest replica is in Virginia        ~85 ms (one transatlantic round trip)
4    EC setting (W=3)       ack after every replica                   ~90 ms, and fails if any one is down

Real scenario: a global user-profile store (PA/EL is fine: profile pictures may be a second old); a bank ledger (PC/EC); a social feed (PA/EL); a configuration store (PC/EC); PNUTS: master copy near the user, remote copies asynchronous (PC/EL).

ClassAbadi's classification (2012)What it means for your design
PA/EL"The default versions of Dynamo, Cassandra, and Riak are PA/EL systems"Fast and available; design merges and staleness UX
PC/EC"Fully ACID systems such as VoltDB/H-Store and Megastore are PC/EC"; BigTable, HBasePay quorum latency every day and minority unavailability
PA/EC"MongoDB can be classified as a PA/EC system"Consistent normally; on a split, writes acknowledged by an old primary can roll back
PC/EL"PNUTS is a PC/EL system"Fast normally, does not get worse when partitioned; availability drops instead

Fix / how to use it: classify each operation twice ("partitioned: refuse or answer?", "normal: wait for whom?") and attach numbers to the E branch from Latency Budgets & Tail Latency. The Go pacelc package computes the E-branch latency per Cassandra level.

Tunable consistency and quorums: R + W > N Must-know ​

In plain words: with N copies, if a write waits for W of them and a read asks R of them, and R + W is larger than N, then every read set shares at least one replica with every write set, so the read can see the latest acknowledged write.

Common misunderstanding: "R + W > N gives linearizability." It gives overlap, not linearizability: concurrent writes, sloppy quorums, failed writes that partially applied, and read repair races can still produce non-linearizable histories. Abadi: Dynamo-style systems "cannot achieve full consistency as defined by Gilbert and Lynch, even if R + W > N". Kleppmann lists resurrected deletes and replica counts falling below W as causes.

Definition: Dynamo: "R is the minimum number of nodes that must participate in a successful read operation. W is the minimum number of nodes that must participate in a successful write operation. Setting R and W such that R + W > N yields a quorum-like system." Latency "is dictated by the slowest of the R (or W) replicas". The common Dynamo configuration was (N,R,W) = (3,2,2).

Strict quorums overlap (R + W > N); sloppy quorums trade that overlap for availabilityABCwrite set W=2read set R=2N=3, R+W=4 > 3B is in both sets:read sees the newest,read repair updates CABC (down)D (stand-in)hint: for Chinted handoffwhen C returnsSloppy quorum (Dynamo, Riak; Cassandra stores hints but counts only real replicas)"all read and write operations are performed on the first N healthy nodes from the preference list"W is met by A, B, D; a read from A, B, C after C returns but before handoff can miss the write.Riak PR/PW > 0 turns this back into a strict quorum (fails instead of using stand-ins).
text
     N=3. Which (R, W) pairs overlap, and what each survives
1    R=1 W=1   1+1=2  not > 3   fastest; reads may miss writes            survives 2 down (each op)
2    R=1 W=3   1+3=4  > 3       fast reads; every write needs all three   writes fail with 1 down
3    R=3 W=1   4      > 3       fast writes; reads need all three         reads fail with 1 down
4    R=2 W=2   4      > 3       balanced; the usual QUORUM/QUORUM         survives 1 down for both
5    R=1 W=2   3      not > 3   majority writes, local reads: stale reads possible on the minority

Real scenario: Cassandra QUORUM/QUORUM for user accounts; ONE writes and ALL reads for a write-heavy log you rarely read; LOCAL_QUORUM in each region for a globally deployed service; Riak buckets with n_val: 5, r: 3, w: 3.

Fix / how to use it: pick R and W from the operation's needs and failure budget: Survives(N, k) = N − k replicas may be missing for an operation needing k acknowledgements. For anything that needs real linearizability (compare-and-set, uniqueness), use a consensus path (Cassandra LWT with SERIAL, etcd, a SQL primary).

Cassandra consistency levels Must-know ​

In plain words: instead of choosing R and W numbers, every Cassandra request names a level such as ONE or QUORUM, and the coordinator waits for that many replica responses.

Common misunderstanding: "ONE writes only to one replica." Cassandra docs: "Write operations are always sent to all replicas, regardless of consistency level. The consistency level simply controls how many responses the coordinator waits for before responding to the client."

Definition: Cassandra's levels "are a version of Dynamo's R + W > N consistency mechanism". With replication factor RF per datacenter:

LevelResponses requiredTypical use
ONE"Only a single replica must respond."Fast reads/writes of mergeable data
TWO, THREETwo / three replicasRare; extra durability without majority
QUORUM"A majority (n/2 + 1) of the replicas must respond" across all datacentersSingle-region strong-ish reads and writes
LOCAL_QUORUMMajority of the replicas in the coordinator's datacenterMulti-region services: "reads are guaranteed to see the latest write from within the same datacenter"
EACH_QUORUMMajority in each datacenterWrites that must be in every region before acknowledging
ALLEvery replicaAlmost never; one replica down fails the request
LOCAL_ONEOne replica, never in a remote datacenterLowest latency local reads
ANYOne replica "or the coordinator may store a hint"; writes onlyMaximum write availability, weakest durability
SERIAL / LOCAL_SERIALPaxos phase of lightweight transactions (IF conditions)Compare-and-set, uniqueness
text
     Two datacenters, RF eu=3 us=3 (6 replicas), coordinator in eu; no failures (output of the Go pacelc package)
1    LOCAL_ONE     needs 1 -> waits 1ms,  survives 5 replicas down
2    LOCAL_QUORUM  needs 2 -> waits 2ms,  survives 4 replicas down (but not the loss of 2 eu replicas)
3    QUORUM        needs 4 -> waits 85ms, at least one transatlantic response
4    EACH_QUORUM   needs 4 -> waits 88ms, 2 in eu and 2 in us
5    ALL           needs 6 -> waits 90ms, survives 0 replicas down

Real scenario: a messaging app writing at LOCAL_QUORUM in each region and reading at LOCAL_QUORUM (read-your-writes for users homed in a region); a fraud flag that must be in every region before payment (EACH_QUORUM); INSERT ... IF NOT EXISTS for usernames (LWT with SERIAL).

Fix / how to use it: cqlsh> CONSISTENCY LOCAL_QUORUM; for a session, per statement in drivers (gocql gocql.LocalQuorum), and keep QUORUM out of multi-region hot paths unless you accept the cross-region round trip. Deep dive: Cassandra & ScyllaDB.

Sloppy quorums, hinted handoff and read repair Important ​

In plain words: when a home replica for a key is unreachable, a sloppy quorum lets another node accept the write on its behalf with a note ("this belongs to C"); when C returns, the note-holder hands it over. Read repair fixes stale replicas noticed during reads.

Common misunderstanding: "Sloppy quorums still guarantee R + W > N overlap." They do not: the W acknowledgements may come from stand-ins, and a later read from the home replicas can miss the write until the hint is delivered. That is the price of availability.

Definition: Dynamo: it "does not enforce strict quorum membership and instead it uses a "sloppy quorum"; all read and write operations are performed on the first N healthy nodes from the preference list". The stand-in keeps the hinted replica "in a separate local database that is scanned periodically" and delivers it when the target recovers. Riak calls the failover "sloppy quorum" and turns it off with PR/PW: "Setting PR and/or PW to non-zero values produces a mode of operation called strict quorum." Cassandra stores hints but counts a hint toward the consistency level only for ANY. Read repair and anti-entropy are best-effort ("These techniques are only best-effort", Cassandra docs); Merkle-tree repair guarantees convergence.

text
     Dynamo-style N=3, preference list for key k: A, B, C, D ...; C is down
1    put(k, v): coordinator sends to A, B and D (first 3 healthy)    W=2 met by A and B (or A and D)
2    D stores v with hint "for C"
3    get(k) with R=2 from A, C (C just came back, hint not yet sent)  if A is slow, R could be C + B ... C is stale
4    D detects C is up, sends v, deletes its copy                    hinted handoff
5    a read that sees different versions writes back the newest       read repair

Real scenario: a shopping cart that must accept writes during a rack failure; IoT ingestion during rolling restarts; Riak buckets with pw=2 for orders (strict) and default sloppy for sessions.

Fix / how to use it: keep hints for a bounded window (Cassandra max_hint_window, three hours by default) and run full repair within the tombstone grace period; prefer strict quorums for data that is read-modify-written; see Merkle Trees, Read Repair, Anti-Entropy & Tombstones.

Linearizable vs serializable reads in etcd, ZooKeeper and Consul Important ​

In plain words: coordination services are CP for writes, but most of them let you choose, per read, between "ask the majority" (correct, slower, fails on the minority) and "ask the node I am connected to" (fast, works on the minority, may be stale).

Common misunderstanding: "ZooKeeper is CP, so reads are linearizable." ZooKeeper reads are served by the server the client is connected to. The docs warn that clients may assume "Simultaneously Consistent Cross-Client Views" and that ZooKeeper does not provide them; "Client B should call the sync() method from the ZooKeeper API method before it performs its read."

Definition: etcd: "By default, Range is linearizable; it reflects the current consensus of the cluster. For better performance and availability, in exchange for possible stale reads, a serializable range request is served locally without needing to reach consensus with other nodes in the cluster." Note the vocabulary: etcd's "serializable read" means member-local, possibly stale, not SQL's serializable isolation. Consul's three modes: default ("strongly consistent in almost all cases"), consistent ("requires that a leader verify with a quorum of peers that it is still leader"), stale ("allows any server to handle the read regardless of whether it is the leader"; "Consul DNS queries use stale mode by default").

text
     etcd, partition {m1, m2} | {m3}, value /cfg/flag changed to "on" on the majority side
1    etcdctl --endpoints=m3 get /cfg/flag                      timeout (needs consensus)
2    etcdctl --endpoints=m3 get /cfg/flag --consistency=s      "off"   (stale, but answered)
3    etcdctl --endpoints=m1 get /cfg/flag                      "on"
4    watch on m3                                               no events until m3 rejoins
ServiceLinearizable readFast / available readStaleness bound
etcddefault (--consistency=l)--consistency=s, clientv3.WithSerializable()none stated
ZooKeepersync() then readplain read; read-only mode on the minority"tens of seconds" (Timeliness guarantee)
Consul?consistent?stale (and DNS by default)"generally consistent to within 50 milliseconds of the leader, though there is no upper limit"

Fix / how to use it: linearizable reads for locks, leader checks and anything followed by a write decision; serializable/stale reads for dashboards, service discovery caches and DNS; and never use a stale read to decide who holds a lock.

MongoDB write concern and read concern Must-know ​

In plain words: write concern says how many members must have a write before you are told "ok"; read concern says how committed the data you read must be. Together they decide whether MongoDB behaves CP for your operation.

Common misunderstanding: "w: "majority" alone makes reads consistent." A read at the default local level can return data that is later rolled back, and a majority read can still be behind your own latest write if it goes to a lagging secondary. Linearizability needs w: "majority" writes and "linearizable" reads on the primary.

Definition: MongoDB docs: "{ w: "majority" } is the default write concern for most MongoDB deployments" (w:majority; the default becomes { w: 1 } in some arbiter layouts). wtimeout bounds the wait: without it, "the write operation will block indefinitely" if the concern is unachievable, and with it the write returns a write concern error "even if the required write concern will eventually succeed" (the data is not undone). Read concern levels: local, available, majority, linearizable, snapshot. Linearizable: primary only, single document by a unique filter, and "Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable."

text
     3-member replica set P-S-S; P is cut off with one client
1    client -> P: insert {w: 1}                ok (acknowledged by P alone)
2    majority side elects S1 as new primary
3    P steps down when it notices it lost the majority
4    P rejoins: its unreplicated write is rolled back (written to the rollback directory)
5    same with {w: "majority", wtimeout: 2000}: P cannot reach 2 of 3 -> write concern error after 2 s
6    find({_id: 5}).readConcern("linearizable").maxTimeMS(10000) on P -> MaxTimeMSExpired, never stale
SettingPromisePartition behaviour
w: 1Primary has itAcknowledged writes can roll back after a split
w: "majority" (+ j: true)Majority has it (journaled when writeConcernMajorityJournalDefault is true)Old primary cannot acknowledge
readConcern: "local"Whatever this member hasCan read data that later rolls back
readConcern: "majority"Majority-committed data at the member's majority-commit pointNever rolled back; may be stale
readConcern: "linearizable"Reflects all majority writes acknowledged before the read beganFails (with maxTimeMS) instead of answering stale
read preference nearest / secondaryAny memberAnswers on the minority, stale (maxStalenessSeconds ≥ 90)

Fix / how to use it: majority writes with wtimeout everywhere money or state machines are involved; linearizable reads with maxTimeMS only on the few reads that decide something; causally consistent sessions for read-your-writes; nearest for feeds. The Laravel MongoLedger does the CP version.

PostgreSQL synchronous_commit and synchronous replication Must-know ​

In plain words: by default a PostgreSQL primary says "committed" without waiting for any standby. Synchronous replication makes COMMIT wait for one or more named standbys, and synchronous_commit chooses how far they must have got.

Common misunderstanding: "Synchronous replication means standbys always show the latest data." With synchronous_commit = on the standby has flushed the WAL but may not have applied it, so a read on the standby can still be stale; only remote_apply waits for visibility. And synchronous replication makes the primary CP for writes: if the standbys are unreachable, commits wait.

Definition: synchronous_commit: "Valid values are remote_apply, on (the default), remote_write, local, and off." With synchronous_standby_names set, on waits for standby flush, remote_write for the standby's OS write, remote_apply until the change is "visible to queries on the standby(s)" ("In simple cases, this allows for load balancing with causal consistency"), local only for the local flush, off not even that (crash may lose recent commits, never corrupts). synchronous_standby_names accepts FIRST num_sync (...) (priority) and ANY num_sync (...) (quorum). The warning: commits "may never be completed if any one of the synchronous standbys should crash" when you require all of them.

sql
-- Primary: quorum commit, any 1 of 2 standbys must confirm
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)';
SELECT pg_reload_conf();

-- Which standbys are synchronous right now?
SELECT application_name, state, sync_state, replay_lag
FROM pg_stat_replication;

-- Per transaction: money waits for visibility on a standby, likes do not wait at all
BEGIN;
SET LOCAL synchronous_commit TO 'remote_apply';
UPDATE wallets SET balance = balance - 80 WHERE id = 7 AND balance >= 80;
COMMIT;

BEGIN;
SET LOCAL synchronous_commit TO OFF;
INSERT INTO post_likes (post_id, user_id, created_at) VALUES (42, 7, now()) ON CONFLICT DO NOTHING;
COMMIT;
text
     synchronous_standby_names = 'standby_a' (one required), standby_a is partitioned away
1    client: COMMIT                                       primary flushes locally, waits for standby_a
2    ... waits ...                                        CP: no acknowledgement without the standby
3    operator cancels the query (pg_cancel_backend)       WARNING: canceling wait for synchronous replication due to user request
4                                                         DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.
5    the transaction is NOT rolled back                   cancelling the wait is not an abort

Real scenario: a payments database with ANY 1 (a, b) across two zones; read-your-writes on standbys with remote_apply for a profile service; analytics writes with synchronous_commit = off; a single-standby setup that froze all writes when the standby's disk filled.

Fix / how to use it: always name more candidate standbys than you require (ANY 1 (a, b)), monitor pg_stat_replication.sync_state, set synchronous_commit per transaction by data item, and remember that cancelled waits leave committed-but-unreplicated data.

Kafka acks, min.insync.replicas and unclean leader election Important ​

In plain words: a Kafka producer chooses how many replicas must have a record before "sent"; the topic chooses the minimum number of in-sync replicas below which it refuses writes; the cluster chooses whether an out-of-date replica may become leader when all good ones are gone.

Common misunderstanding: "acks=all means all replicas." It means all in-sync replicas, and the in-sync set can shrink to the leader alone. With the default min.insync.replicas=1, acks=all can be acknowledged by one broker.

Definition: producer acks: 0, 1, all (= -1, the default); all "guarantees that the record will not be lost as long as at least one in-sync replica remains alive." min.insync.replicas (default 1): when "the current ISR set contains fewer than min.insync.replicas members, then the producer will raise an exception (either NotEnoughReplicas or NotEnoughReplicasAfterAppend)". The documented recipe: "replication factor of 3, set min.insync.replicas to 2, and produce with acks of "all"." unclean.leader.election.enable (default false): electing a non-ISR replica "may result in data loss"; the design docs call it "a simple tradeoff between availability and consistency".

text
     Topic RF=3, min.insync.replicas=2, producer acks=all; brokers b1 (leader), b2, b3
1    b2 and b3 partitioned from b1; ISR shrinks to {b1}
2    producer -> b1: produce                 rejected: NOT_ENOUGH_REPLICAS (19) -> CP for writes
3    with min.insync.replicas=1              accepted by b1 alone; lost if b1 dies before b2/b3 catch up
4    b1 dies; b2 was not in ISR
5    unclean.leader.election.enable=false    partition offline until an ISR member returns (C over A)
6    unclean.leader.election.enable=true     b2 becomes leader; records only b1 had are gone (A over C)

Real scenario: an order-events topic that must not lose records (RF 3, min.insync.replicas=2, acks=all, idempotent producer); a metrics topic that prefers uptime (acks=1); a cluster that lost two brokers and an operator deciding whether to enable unclean election.

Fix / how to use it: RF 3, min.insync.replicas=2, acks=all, enable.idempotence=true, unclean election off for business events; deep dive in Kafka in Depth and Delivery Guarantees.

Spanner, TrueTime and CockroachDB: "effectively CA" Important ​

In plain words: Spanner and CockroachDB are CP: each piece of data lives in a consensus group, and the side without a majority stops. Spanner adds very accurate clocks so that strong reads and global ordering are cheap, and Google's network makes partitions rare enough that users treat it as always available.

Common misunderstanding: "Spanner beat CAP." Brewer 2017: "The purist answer is "no" because partitions can happen and in fact have happened at Google, and during (some) partitions, Spanner chooses C and forfeits A. It is technically a CP system."

Definition: TrueTime gives each server a time interval with bounded uncertainty; Spanner assigns every transaction "a timestamp that reflects the instant at which Spanner considers it to have occurred" and waits out the uncertainty (commit wait) so that timestamps respect real-time order: external consistency, under which "the system behaves as if all transactions run sequentially". The CockroachDB team summarises: "In Spanner's case, Google mentions an upper bound of 7ms", whereas NTP gives "somewhere between 100ms and 250ms"; so "While Spanner always waits after writes, CockroachDB sometimes retries reads" (uncertainty restarts), and "If the configured maximum offset is exceeded by any node, it self-terminates." CockroachDB replication: "The number of failures that can be tolerated is equal to (Replication factor - 1)/2."

text
     Spanner commit with TrueTime (simplified)
1    TT.now() = [earliest, latest], width ~ a few ms
2    assign commit timestamp s = latest
3    Paxos: replicate to a majority of the split        (minority side: unavailable)
4    commit wait: until TT.now().earliest > s          then release locks and acknowledge
5    any transaction that starts after the ack gets a larger timestamp -> external consistency

Real scenario: global financial ledgers and inventories where a few milliseconds of commit wait beat multi-region conflict handling; CockroachDB multi-region tables with REGIONAL BY ROW locality to keep the consensus group near its users; follower reads for analytics.

Fix / how to use it: place replicas so that the majority for hot data is in one metro (low EC latency) while surviving a zone; use stale/follower reads where freshness does not matter; treat clock synchronisation as a production dependency in CockroachDB. Engine details: Distributed SQL, Consensus & 2PC.

DynamoDB: ConsistentRead, global tables MREC and MRSC Important ​

In plain words: within one Region you choose per read between cheap eventually consistent reads and strongly consistent reads; across Regions you choose per table between asynchronous replication with last-writer-wins and synchronous three-Region replication.

Common misunderstanding: "DynamoDB is AP." Single-Region strongly consistent reads exist (ConsistentRead=true), and MRSC global tables give "strongly consistent read operations on any MRSC replica always return the latest version". The default, however, is eventual: "Eventually consistent is the default read consistent model for all read operations."

Definition: eventually consistent reads "are half the cost of strongly consistent reads"; reads from GSIs and streams are always eventually consistent. MREC (default for global tables): asynchronous replication "typically within a second or less", conflicts resolved by "last writer wins". MRSC: "must be deployed in exactly three Regions", three replicas or two replicas and a witness; a write to an item being modified elsewhere fails with ReplicatedWriteConflictException and can be retried; RPO zero; higher write and strong-read latency.

text
     Global table, user 7 updates profile in eu-west-1, reads in us-east-1 500 ms later
1    MREC: write acked in eu-west-1 (local latency)
2    MREC: us-east-1 strongly consistent read           may return the old profile (Region-local strong only)
3    MREC: concurrent edit in us-east-1                 last writer wins; one edit silently lost
4    MRSC: write waits for another Region                higher latency (PC/EC)
5    MRSC: concurrent edit elsewhere                    ReplicatedWriteConflictException -> retry

Real scenario: a session store on MREC (losing one edit is fine); an entitlement or balance table on MRSC; a product catalogue read with eventually consistent reads at half cost.

Fix / how to use it: ConsistentRead: true (ConsistentRead *bool in the AWS SDK for Go v2) only on reads that must see the latest write; MREC plus idempotent, commutative updates for globally replicated sessions and carts; MRSC for data that must never diverge across Regions.

Harvest and yield Important ​

In plain words: instead of "answer or error", answer with part of the data. Yield is how many requests get an answer; harvest is how complete each answer is.

Common misunderstanding: "Availability is binary." Fox and Brewer: "In the presence of faults there is typically a tradeoff between providing no answer (reducing yield) and providing an imperfect answer (maintaining yield, but reducing harvest)."

Definition: "yield, which is the probability of completing a request, and harvest, which measures the fraction of the data reflected in the response, i.e. the completeness of the answer to the query." Example from the paper: "in a 100-node cluster a single-node fault reduces the harvest by 1%". Some applications cannot accept reduced harvest (a binary sensor reading); search, recommendations and aggregates can.

text
     Search over 100 shards, 3 shards on the far side of a partition
1    Option yield-first:   return results from 97 shards, flag "partial": harvest 97%, yield 100%
2    Option harvest-first: wait/timeout for all 100, return 503: harvest 100% of nothing, yield drops
3    Option per item:      orders page = must be complete (harvest 100%), recommendations = 97% is fine

Real scenario: Elasticsearch partial results when shards fail ("timed_out": true, _shards.failed); a dashboard that shows panels from reachable regions and greys out the rest; a product page that drops the "people also bought" widget; Dean and Barroso's "good-enough" results (Latency Budgets & Tail Latency).

Fix / how to use it: decompose a response into required and optional parts; give optional parts a short deadline; mark partial responses explicitly; graceful degradation patterns in Bulkheads & Graceful Degradation.

Deciding per data item: money vs likes Must-know ​

In plain words: one application has many kinds of data with different costs of being wrong. Choose CP or AP, EC or EL, for each kind, not once for the whole database.

Common misunderstanding: "We chose Cassandra, so we are AP" (or "we chose PostgreSQL, so we are consistent"). Brewer: "the choice between C and A can occur many times within the same system at very fine granularity; not only can subsystems make different choices, but the choice can change according to the operation or even the specific data or user involved."

Definition: for each data item, the deciding questions are: what does one wrong answer cost, can the operation be merged or compensated, is the action externalised, and what latency can the user tolerate.

text
     One checkout request touching four items, during a cross-zone partition
1    cart contents          AP: accept on the local side, merge as a set           user keeps shopping
2    stock reservation      CP: needs the majority; minority -> "try again"        no overselling
3    payment                CP + idempotency key; externalised -> never guess      no double charge
4    "recently viewed"      AP/EL: local replica, may be a minute old              nobody notices
Data itemPartition choiceElse choiceKnob examplesWhy
Wallet balance, ledgerPCECPG remote_apply, Mongo w: "majority" + linearizable, SpannerWrong answer = lost money
Stock, seats, ticketsPC (or bounded AP with a reservation limit)ECCassandra LWT SERIAL, SQL FOR UPDATEOverselling is visible and expensive
Username / email uniquenessPCECUnique index on the primary, etcd txnDuplicates need human compensation
Locks, leader, configPCECetcd linearizable, ZooKeeper sync()Two leaders corrupt everything
Profile, settingsPA with read-your-writesELLaravel sticky, PreventStaleDatabaseReads, LOCAL_QUORUMAuthor must see their own edit
Shopping cartPAELDynamo/Cassandra sets, CRDTLosing an add-to-cart loses revenue
Likes, views, countersPAELONE, PG synchronous_commit = off, sharded countersApproximate is fine
Feeds, recommendationsPA (harvest < 100%)ELReplica reads, cacheFreshness of seconds is fine

Fix / how to use it: keep this table in the design doc; encode it once in code (the Laravel ConsistencyPolicy does) so every new data item needs an explicit decision.

"Eventually consistent is fine": the UX it needs Important ​

In plain words: eventual consistency is fine only if the user interface is designed for it; otherwise users see their own edit disappear, click twice, and file bugs.

Common misunderstanding: "Replication lag is milliseconds, nobody will notice." The user who just wrote is exactly the one who will read immediately, and lag spikes during load, failover and partitions. Brewer: partition mode "gives rise to a fundamental user-interface challenge, which is to communicate that tasks are in progress but not complete."

Definition: the UX patterns: read-your-writes for the author (sticky sessions, primary reads for a window, causal tokens), optimistic UI with pending state, "tentative" markers (Brewer: Bayou showed tentative entries in a different color), idempotent retries, and explicit "approximate" labels on counts. More in Event-Driven Architecture.

text
     Without UX design vs with it (profile name change, replica lag 3 s)
1    POST /profile name=Sara          primary: ok
2    redirect GET /profile            replica: name=Sarah (old)     user: "it did not save", edits again
     ---- with read-your-writes ----
1    POST /profile name=Sara          primary: ok; session marks "wrote at t"
2    GET /profile within 5 s          routed to the primary         user sees Sara
3    GET /profile after 5 s           replica (caught up)

Real scenario: Facebook's approach described by Brewer: after an update, "the update goes to the master copy directly as do all the user's reads for a short time" and "After 20 seconds, the user's traffic reverts to the closer copy"; Laravel's PreventStaleDatabaseReads does the same per session (2 seconds by default).

Fix / how to use it: in Laravel, 'sticky' => true plus PreventStaleDatabaseReads::for(5); in MongoDB, causally consistent sessions; in Cassandra, LOCAL_QUORUM both ways for users homed in a region; show pending states for writes that go through queues.

Mechanics ​

Quorum and failure arithmetic ​

QuantityFormulaN=3N=5
Majority⌊N/2⌋ + 123
Overlap conditionR + W > N2 + 23 + 3
Failures a majority operation survivesN − majority = ⌊(N−1)/2⌋12
Write-write overlap (no two conflicting writes both succeed)W > N/2W ≥ 2W ≥ 3
Latency of an operation needing k acksk-th fastest replica RTT2nd fastest3rd fastest
CockroachDB failures tolerated(RF − 1)/212
Riak defaultsn_val 3, PR = PW = 0 (sloppy)

The knobs, product by product ​

ProductKnobValues (default first or marked)Effect on CAP/PACELC
Cassandraconsistency level per statementONE, TWO, THREE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL, LOCAL_ONE, ANYMoves each request between PA/EL and PC/EC
Cassandraserial consistencySERIAL, LOCAL_SERIALPaxos phase of LWT (linearizable CAS)
DynamoDBConsistentReadfalse (default), trueStrong reads cost double, tables and LSIs only
DynamoDB global tablesconsistency modeMREC (default), MRSCMRSC: three Regions, RPO 0, higher latency
MongoDBwrite concernw: "majority" (implicit default in most deployments), w: 1, w: n, j, wtimeoutMajority = no rollback of acknowledged writes
MongoDBread concernlocal (default), available, majority, linearizable, snapshotlinearizable refuses rather than goes stale
MongoDBread preferenceprimary (default), primaryPreferred, secondary, secondaryPreferred, nearest, maxStalenessSeconds (≥ 90)Secondary reads answer during partitions, stale
PostgreSQLsynchronous_commiton (default), remote_apply, remote_write, local, offPer transaction; needs synchronous_standby_names for remote levels
PostgreSQLsynchronous_standby_namesempty (async, default), FIRST n (...), ANY n (...)Commits wait for standbys: CP for writes
Kafkaproducer acksall (default), 1, 0Durability of the acknowledgement
Kafkamin.insync.replicas1 (default)≥ 2 makes acks=all refuse when the ISR is too small
Kafkaunclean.leader.election.enablefalse (default)true = availability over consistency
etcdread consistencylinearizable (default), serializable (--consistency=s, WithSerializable())Serializable answers on the minority
ZooKeepersync(), read-only modeoff by defaultsync() = linearizable read; read-only = AP reads
Consulread modedefault (HTTP), stale (DNS default), consistentstale works without a leader
Riak KVn_val, r, w, pr, pw, dwn_val 3, pr/pw 0pr/pw > 0 = strict quorum
CockroachDBreplication factor, cockroach start --max-offsetRF 3; --max-offset "Default: 500ms"Failures tolerated = (RF − 1)/2; "If observed clock offsets exceed this limit, servers will crash"
Laravelsticky, PreventStaleDatabaseReads, usingWritePdooff unless configuredRead-your-writes on replicated MySQL/PostgreSQL

Error messages you will actually see ​

ProductMessage or code (verbatim)Meaning
CassandraCannot achieve consistency level QUORUM. Required 2 but only 1 alive. (UnavailableException)Coordinator knows too few replicas are up: refused before trying
CassandraOperation timed out - received only 1 responses. (read/write timeout)Replicas were thought alive but did not answer in time; write may have partially applied
KafkaNOT_ENOUGH_REPLICAS (19): "Messages are rejected since there are fewer in-sync replicas than required."ISR below min.insync.replicas
KafkaNOT_ENOUGH_REPLICAS_AFTER_APPEND (20): "Messages are written to the log, but to fewer in-sync replicas than required."Outcome uncertain; retry with idempotence
KafkaNOT_LEADER_OR_FOLLOWER (6)Leadership moved; client refreshes metadata
etcdetcdserver: no leader, etcdserver: request timed out (gRPC Unavailable)Member lost the quorum or the leader
MongoDBWriteConcernTimeout (64, write concern error)Majority not reached within wtimeout; write NOT undone on the primary
MongoDBMaxTimeMSExpired (50)Linearizable read could not confirm a majority in time
MongoDBNotWritablePrimary (10107), PrimarySteppedDown (189)Write sent to a member that is not (or no longer) primary
PostgreSQLWARNING: canceling wait for synchronous replication due to user request + DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.Sync rep wait cancelled; the commit stands
DynamoDBReplicatedWriteConflictExceptionMRSC: item being modified in another Region; retry

Go ​

The module academy/cap-pacelc uses only the standard library. register is the 3-node replicated register with partition injection, atm is Brewer's partition mode with compensation, pacelc is the quorum and latency arithmetic, cmd/capsim prints the lab output.

Before ​

A wallet replicated to two sites that checks the invariant against the local copy and replicates later, as if partitions did not happen ("CA"). The test documents the overdraft, it does not hide it.

go
// Package before shows the design CAP warns about: a wallet replicated to
// two sites that accepts withdrawals on whichever replica the request reaches,
// assuming the network never splits ("CA"). It is not broken code; it is the
// common default of "read local, write local, replicate later".
package before

import "errors"

// ErrInsufficientFunds is returned when the local replica sees too little money.
var ErrInsufficientFunds = errors.New("insufficient funds")

// Site is one replica of the wallet (for example one datacenter).
type Site struct {
	Balance int64
	outbox  []int64 // deltas not yet shipped to the peer
}

// Wallet holds two replicas and a flag that says whether they can talk.
type Wallet struct {
	Sites     [2]*Site
	Connected bool
}

// New creates a wallet whose two replicas both start with balance.
func New(balance int64) *Wallet {
	return &Wallet{Sites: [2]*Site{{Balance: balance}, {Balance: balance}}, Connected: true}
}

// Withdraw checks the invariant (balance >= amount) against the LOCAL replica
// only, applies the change locally and queues it for the peer. During a
// partition both sites can approve withdrawals against the same money.
func (w *Wallet) Withdraw(site int, amount int64) error {
	s := w.Sites[site]
	if s.Balance < amount {
		return ErrInsufficientFunds
	}
	s.Balance -= amount
	s.outbox = append(s.outbox, -amount)
	if w.Connected {
		w.flush()
	}
	return nil
}

// Reconnect ships every queued delta to the other site. Nothing checks the
// invariant again, so the merged balance can be negative.
func (w *Wallet) Reconnect() {
	w.Connected = true
	w.flush()
}

func (w *Wallet) flush() {
	for i, s := range w.Sites {
		peer := w.Sites[1-i]
		for _, d := range s.outbox {
			peer.Balance += d
		}
		s.outbox = nil
	}
}
go
package before

import "testing"

// The test documents the failure, it does not hide it: two sites approve
// 80 each against a balance of 100 while partitioned.
func TestPartitionOverdraws(t *testing.T) {
	w := New(100)
	w.Connected = false // the link between the sites fails

	if err := w.Withdraw(0, 80); err != nil {
		t.Fatalf("site 0: %v", err)
	}
	if err := w.Withdraw(1, 80); err != nil {
		t.Fatalf("site 1: %v", err)
	}
	w.Reconnect()

	for i, s := range w.Sites {
		if s.Balance != -60 {
			t.Fatalf("site %d balance = %d, want -60 (invariant silently broken)", i, s.Balance)
		}
	}
}

func TestConnectedIsFine(t *testing.T) {
	w := New(100)
	if err := w.Withdraw(0, 80); err != nil {
		t.Fatal(err)
	}
	if err := w.Withdraw(1, 80); err != ErrInsufficientFunds {
		t.Fatalf("err = %v, want ErrInsufficientFunds", err)
	}
}

After ​

A replicated register whose CAP behaviour is a configuration. CP (R = W = 2 on three nodes, read repair) is the ABD quorum register: the write first learns the highest stamp from the replicas it reaches, so stamps never go backwards, and the minority returns ErrUnavailable. AP (R = W = 1, hinted handoff) answers everywhere; Heal replays hints, runs last-write-wins anti-entropy and reports every acknowledged value it discarded, because the application has to compensate for those.

go
// Package register simulates a single replicated register on N nodes with
// partition injection. The same code behaves as a CP system or as an AP
// system depending only on Config: how many replicas must answer a read (R),
// how many must acknowledge a write (W), and whether the coordinator keeps
// hints for unreachable replicas.
//
// Operations are applied synchronously inside one process, so the only source
// of disagreement between replicas is the partition itself. That isolates the
// CAP decision from every other effect.
package register

import (
	"errors"
	"fmt"
	"sort"
	"sync"
)

// ErrUnavailable is what a CP configuration returns on the minority side:
// the node is alive, but it cannot reach enough replicas to answer safely.
var ErrUnavailable = errors.New("unavailable: not enough replicas reachable")

// Stamp orders versions: a Lamport-style counter, ties broken by node id.
type Stamp struct {
	Counter uint64
	Node    int
}

// Less reports whether s is older than o.
func (s Stamp) Less(o Stamp) bool {
	if s.Counter != o.Counter {
		return s.Counter < o.Counter
	}
	return s.Node < o.Node
}

// Version is a value with the stamp of the write that produced it.
type Version struct {
	Value string
	Stamp Stamp
}

// Config chooses the trade-off.
type Config struct {
	R             int  // replicas that must answer a read
	W             int  // replicas that must acknowledge a write
	HintedHandoff bool // keep writes for unreachable replicas and replay them on heal
	ReadRepair    bool // write the newest version back to stale replicas a read contacted
}

// CP: majority reads and writes on three nodes (R + W > N), with read repair,
// which together form the ABD quorum register. The minority side refuses.
var CP = Config{R: 2, W: 2, ReadRepair: true}

// AP: any single replica answers (R = W = 1), hints cover unreachable replicas.
// Both sides accept writes and diverge; Heal converges them.
var AP = Config{R: 1, W: 1, HintedHandoff: true}

type hint struct {
	holder, target int
	v              Version
}

// HealReport says what convergence had to do after the partition.
type HealReport struct {
	HintsDelivered int      // hinted writes replayed to their target
	Repaired       int      // replicas changed by anti-entropy
	Discarded      []string // acknowledged values overwritten by last-write-wins
}

// Cluster is N replicas of one register plus the network between them.
type Cluster struct {
	mu       sync.Mutex
	cfg      Config
	replicas []Version
	group    []int // nodes with the same group id can talk
	hints    []hint
	parents  map[Stamp][]Stamp // versions each write had seen (its causal past)
}

// New creates n replicas holding the empty value.
func New(n int, cfg Config) *Cluster {
	if cfg.R < 1 || cfg.W < 1 || cfg.R > n || cfg.W > n {
		panic(fmt.Sprintf("register: invalid R=%d W=%d for N=%d", cfg.R, cfg.W, n))
	}
	return &Cluster{cfg: cfg, replicas: make([]Version, n), group: make([]int, n), parents: map[Stamp][]Stamp{}}
}

// Partition splits the network. Each argument is a set of node ids that can
// still talk to each other; nodes not listed end up alone.
func (c *Cluster) Partition(groups ...[]int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	for i := range c.group {
		c.group[i] = -1 - i // alone by default
	}
	for g, nodes := range groups {
		for _, n := range nodes {
			c.group[n] = g
		}
	}
}

// reachable returns the nodes coord can talk to, coord first.
func (c *Cluster) reachable(coord int) []int {
	out := []int{coord}
	for n := range c.replicas {
		if n != coord && c.group[n] == c.group[coord] {
			out = append(out, n)
		}
	}
	return out
}

// Write stores value through coordinator coord. With W > 1 the coordinator
// first learns the highest stamp from the replicas it can reach, so its new
// stamp is larger than every acknowledged write (phase one of ABD).
func (c *Cluster) Write(coord int, value string) error {
	c.mu.Lock()
	defer c.mu.Unlock()
	reach := c.reachable(coord)
	if len(reach) < c.cfg.W {
		return fmt.Errorf("write via node %d: %w (reached %d, need W=%d)", coord, ErrUnavailable, len(reach), c.cfg.W)
	}
	consulted := reach[:1]
	if c.cfg.W > 1 {
		consulted = reach
	}
	highest := c.replicas[coord].Stamp
	var seen []Stamp
	for _, n := range consulted {
		seen = append(seen, c.replicas[n].Stamp)
		if highest.Less(c.replicas[n].Stamp) {
			highest = c.replicas[n].Stamp
		}
	}
	v := Version{Value: value, Stamp: Stamp{Counter: highest.Counter + 1, Node: coord}}
	c.parents[v.Stamp] = seen
	// Like Cassandra, the write goes to every replica it can reach; W only
	// decides how many acknowledgements the client waits for.
	for _, n := range reach {
		c.apply(n, v)
	}
	if c.cfg.HintedHandoff {
		for n := range c.replicas {
			if c.group[n] != c.group[coord] {
				c.hints = append(c.hints, hint{holder: coord, target: n, v: v})
			}
		}
	}
	return nil
}

// Read returns the value seen by R replicas reachable from coord, preferring
// coord itself. With R = 1 that is the local replica, possibly stale.
func (c *Cluster) Read(coord int) (string, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	reach := c.reachable(coord)
	if len(reach) < c.cfg.R {
		return "", fmt.Errorf("read via node %d: %w (reached %d, need R=%d)", coord, ErrUnavailable, len(reach), c.cfg.R)
	}
	asked := reach[:c.cfg.R]
	newest := c.replicas[asked[0]]
	for _, n := range asked[1:] {
		if newest.Stamp.Less(c.replicas[n].Stamp) {
			newest = c.replicas[n]
		}
	}
	if c.cfg.ReadRepair {
		for _, n := range asked {
			c.apply(n, newest)
		}
	}
	return newest.Value, nil
}

// Heal restores the network, replays hints, then runs anti-entropy: every
// replica converges to the newest stamp (last write wins). A value that is
// overwritten by a version whose writer never saw it was acknowledged on one
// side and is now lost; Heal reports it, because the application must
// compensate for it. LWW alone drops it silently.
func (c *Cluster) Heal() HealReport {
	c.mu.Lock()
	defer c.mu.Unlock()
	for i := range c.group {
		c.group[i] = 0
	}
	var rep HealReport
	lost := map[string]bool{}
	overwrite := func(n int, v Version) bool {
		old := c.replicas[n]
		if !c.apply(n, v) {
			return false
		}
		if old.Stamp != (Stamp{}) && !c.descends(v.Stamp, old.Stamp) {
			lost[old.Value] = true
		}
		return true
	}
	for _, h := range c.hints {
		if overwrite(h.target, h.v) {
			rep.HintsDelivered++
		}
	}
	c.hints = nil

	winner := c.replicas[0]
	for _, v := range c.replicas[1:] {
		if winner.Stamp.Less(v.Stamp) {
			winner = v
		}
	}
	for n := range c.replicas {
		if overwrite(n, winner) {
			rep.Repaired++
		}
	}
	for v := range lost {
		rep.Discarded = append(rep.Discarded, v)
	}
	sort.Strings(rep.Discarded)
	return rep
}

// descends reports whether the write stamped s had old in its causal past.
func (c *Cluster) descends(s, old Stamp) bool {
	stack, visited := []Stamp{s}, map[Stamp]bool{}
	for len(stack) > 0 {
		cur := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		if cur == old {
			return true
		}
		if visited[cur] {
			continue
		}
		visited[cur] = true
		stack = append(stack, c.parents[cur]...)
	}
	return false
}

// Values returns every replica's current value, by node id.
func (c *Cluster) Values() []string {
	c.mu.Lock()
	defer c.mu.Unlock()
	out := make([]string, len(c.replicas))
	for i, v := range c.replicas {
		out[i] = v.Value
	}
	return out
}

// apply stores v on node n if it is newer; reports whether it changed.
func (c *Cluster) apply(n int, v Version) bool {
	if c.replicas[n].Stamp.Less(v.Stamp) {
		c.replicas[n] = v
		return true
	}
	return false
}

The tests cover the minority refusing, AP divergence and convergence, hinted handoff alone, the R + W = N stale read, and a 2,000-operation random schedule in which CP never returns a stale value while AP does:

go
package register

import (
	"errors"
	"math/rand"
	"reflect"
	"testing"
)

// Three nodes, partition {0,1} | {2}. CP: the majority side keeps working,
// node 2 is alive but refuses (it gives up A to keep C).
func TestCPMinorityRefuses(t *testing.T) {
	c := New(3, CP)
	if err := c.Write(0, "v1"); err != nil {
		t.Fatal(err)
	}
	c.Partition([]int{0, 1}, []int{2})

	if err := c.Write(0, "v2"); err != nil {
		t.Fatalf("majority write: %v", err)
	}
	if err := c.Write(2, "x"); !errors.Is(err, ErrUnavailable) {
		t.Fatalf("minority write err = %v, want ErrUnavailable", err)
	}
	if _, err := c.Read(2); !errors.Is(err, ErrUnavailable) {
		t.Fatalf("minority read err = %v, want ErrUnavailable", err)
	}
	if got, _ := c.Read(1); got != "v2" {
		t.Fatalf("majority read = %q, want v2", got)
	}

	rep := c.Heal()
	if len(rep.Discarded) != 0 {
		t.Fatalf("CP must not discard acknowledged writes, got %v", rep.Discarded)
	}
	if got, err := c.Read(2); err != nil || got != "v2" {
		t.Fatalf("after heal read(2) = %q, %v", got, err)
	}
}

// AP: both sides accept, readers see different values, heal converges with
// last-write-wins and reports the acknowledged value it threw away.
func TestAPDivergesThenConverges(t *testing.T) {
	c := New(3, AP)
	if err := c.Write(0, "v1"); err != nil {
		t.Fatal(err)
	}
	c.Partition([]int{0, 1}, []int{2})

	if err := c.Write(0, "left"); err != nil {
		t.Fatal(err)
	}
	if err := c.Write(2, "right"); err != nil {
		t.Fatal(err)
	}
	l, _ := c.Read(1)
	r, _ := c.Read(2)
	if l != "left" || r != "right" {
		t.Fatalf("during partition reads = %q / %q, want left / right", l, r)
	}

	rep := c.Heal()
	// The hint for "left" reaches node 2 but loses (same counter, lower node
	// id); the two hints for "right" overwrite "left" on nodes 0 and 1.
	if rep.HintsDelivered != 2 {
		t.Fatalf("hints delivered = %d, want 2", rep.HintsDelivered)
	}
	if !reflect.DeepEqual(rep.Discarded, []string{"left"}) {
		t.Fatalf("discarded = %v, want [left]", rep.Discarded)
	}
	if got := c.Values(); !reflect.DeepEqual(got, []string{"right", "right", "right"}) {
		t.Fatalf("values after heal = %v", got)
	}
}

// Hinted handoff alone repairs a replica that only missed writes.
func TestHintedHandoffRepairsMissedWrites(t *testing.T) {
	c := New(3, AP)
	c.Partition([]int{0, 1}, []int{2})
	if err := c.Write(0, "only-left"); err != nil {
		t.Fatal(err)
	}
	rep := c.Heal()
	if rep.HintsDelivered != 1 || len(rep.Discarded) != 0 {
		t.Fatalf("report = %+v, want 1 hint and nothing discarded", rep)
	}
	if got := c.Values(); !reflect.DeepEqual(got, []string{"only-left", "only-left", "only-left"}) {
		t.Fatalf("values = %v", got)
	}
}

// R + W = N (1 + 2 = 3) is not a quorum system: the write succeeds on the
// majority, and a read on the minority answers, stale, without any error.
func TestRPlusWNotGreaterThanNIsStale(t *testing.T) {
	c := New(3, Config{R: 1, W: 2})
	if err := c.Write(0, "old"); err != nil {
		t.Fatal(err)
	}
	c.Partition([]int{0, 1}, []int{2})
	if err := c.Write(0, "new"); err != nil {
		t.Fatal(err)
	}
	got, err := c.Read(2)
	if err != nil || got != "old" {
		t.Fatalf("read(2) = %q, %v; want stale \"old\" and no error", got, err)
	}
}

// Random partitions and operations. CP: every successful read returns the
// last acknowledged write (operations are sequential, so that is exactly
// linearizability here). AP: the same schedule produces stale reads.
func TestRandomScheduleCPNeverStale(t *testing.T) {
	cp, ap := runSchedule(CP), runSchedule(AP)
	if cp.stale != 0 {
		t.Fatalf("CP returned %d stale reads", cp.stale)
	}
	if cp.refused == 0 {
		t.Fatalf("CP never refused; the schedule did not exercise partitions")
	}
	if ap.stale == 0 || ap.refused != 0 {
		t.Fatalf("AP: stale=%d refused=%d; want stale > 0 and refused = 0", ap.stale, ap.refused)
	}
	t.Logf("CP: refused=%d stale=%d | AP: refused=%d stale=%d", cp.refused, cp.stale, ap.refused, ap.stale)
}

type outcome struct{ refused, stale int }

func runSchedule(cfg Config) outcome {
	rng := rand.New(rand.NewSource(42))
	c := New(3, cfg)
	splits := [][][]int{nil, {{0, 1}, {2}}, {{0, 2}, {1}}, {{1, 2}, {0}}, {{0}, {1}, {2}}}
	var o outcome
	last := ""
	for i := 0; i < 2000; i++ {
		if i%50 == 0 {
			s := splits[rng.Intn(len(splits))]
			if s == nil {
				c.Heal()
			} else {
				c.Partition(s...)
			}
		}
		node := rng.Intn(3)
		if rng.Intn(2) == 0 {
			v := string(rune('a' + i%26))
			if err := c.Write(node, v); err != nil {
				o.refused++
				continue
			}
			last = v
		} else {
			got, err := c.Read(node)
			if err != nil {
				o.refused++
				continue
			}
			if got != last {
				o.stale++
			}
		}
	}
	return o
}

Partition mode with bounded risk and compensation (Brewer's ATM): online withdrawals check the ledger; offline ones are allowed up to a net limit and logged; Recover replays commutative deltas and charges a fee if the invariant broke.

go
// Package atm implements Brewer's ATM example from "CAP Twelve Years Later":
// detect the partition, enter an explicit partition mode that limits risk
// (stand-in mode: net withdrawals up to a limit), keep a log, and on recovery
// restore state and compensate for invariant violations.
package atm

import (
	"errors"
	"fmt"
)

var (
	// ErrInsufficientFunds: online, the authoritative balance is too low.
	ErrInsufficientFunds = errors.New("insufficient funds")
	// ErrStandInLimit: offline, the bounded-risk limit is used up.
	ErrStandInLimit = errors.New("stand-in limit reached; try again later")
)

// Ledger is the bank's authoritative account (the consistent side).
type Ledger struct {
	Balance int64
}

// Op is one operation recorded while partitioned. Deposits and withdrawals
// are commutative deltas, so replay order does not change the final state.
type Op struct {
	ATM    string
	Amount int64 // negative for withdrawals
}

// Compensation is the business action recovery takes for a broken invariant.
type Compensation struct {
	Reason string
	Fee    int64
}

// Report is the result of partition recovery.
type Report struct {
	Replayed      int
	FinalBalance  int64
	Compensations []Compensation
}

// ATM serves one location. Online it checks the ledger; in partition mode it
// approves withdrawals while the net amount stays within Limit.
type ATM struct {
	Name   string
	Limit  int64
	ledger *Ledger
	online bool
	netOut int64 // withdrawals minus deposits during this partition
	log    []Op
}

// New connects an ATM to the ledger.
func New(name string, ledger *Ledger, limit int64) *ATM {
	return &ATM{Name: name, Limit: limit, ledger: ledger, online: true}
}

// LinkDown is called when the ATM detects the partition (a timeout talking to
// the bank). It switches to partition mode.
func (a *ATM) LinkDown() { a.online = false }

// Online reports whether the ATM is in normal mode.
func (a *ATM) Online() bool { return a.online }

// Withdraw dispenses cash. The externalised action (cash leaving the machine)
// is exactly why the offline path bounds the risk instead of trusting a guess.
func (a *ATM) Withdraw(amount int64) error {
	if a.online {
		if a.ledger.Balance < amount {
			return ErrInsufficientFunds
		}
		a.ledger.Balance -= amount
		return nil
	}
	if a.netOut+amount > a.Limit {
		return fmt.Errorf("%s: %w (net %d of %d)", a.Name, ErrStandInLimit, a.netOut, a.Limit)
	}
	a.netOut += amount
	a.log = append(a.log, Op{ATM: a.Name, Amount: -amount})
	return nil
}

// Deposit is always accepted: it cannot violate balance >= 0.
func (a *ATM) Deposit(amount int64) {
	if a.online {
		a.ledger.Balance += amount
		return
	}
	a.netOut -= amount
	a.log = append(a.log, Op{ATM: a.Name, Amount: amount})
}

// Recover ends partition mode for every ATM given: it replays their logs into
// the ledger (state convergence) and then checks the invariant once, with the
// truth known (compensation). overdraftFee is the bank's chosen compensation.
func Recover(ledger *Ledger, overdraftFee int64, atms ...*ATM) Report {
	var rep Report
	for _, a := range atms {
		for _, op := range a.log {
			ledger.Balance += op.Amount
			rep.Replayed++
		}
		a.log, a.netOut, a.online = nil, 0, true
	}
	if ledger.Balance < 0 {
		rep.Compensations = append(rep.Compensations, Compensation{
			Reason: fmt.Sprintf("overdrawn by %d during partition; fee charged, repayment requested", -ledger.Balance),
			Fee:    overdraftFee,
		})
		ledger.Balance -= overdraftFee
	}
	rep.FinalBalance = ledger.Balance
	return rep
}
go
package atm

import (
	"errors"
	"testing"
)

func TestOnlineEnforcesInvariant(t *testing.T) {
	l := &Ledger{Balance: 100}
	a := New("A", l, 200)
	if err := a.Withdraw(150); !errors.Is(err, ErrInsufficientFunds) {
		t.Fatalf("err = %v, want ErrInsufficientFunds", err)
	}
}

// Two ATMs lose the link. Each may dispense up to its limit, so the bank's
// worst case is bounded (2 x 200), and recovery compensates.
func TestPartitionModeBoundsRiskAndRecoveryCompensates(t *testing.T) {
	l := &Ledger{Balance: 100}
	a, b := New("A", l, 200), New("B", l, 200)
	a.LinkDown()
	b.LinkDown()

	if err := a.Withdraw(150); err != nil {
		t.Fatalf("A: %v", err)
	}
	if err := b.Withdraw(100); err != nil {
		t.Fatalf("B: %v", err)
	}
	if err := a.Withdraw(100); !errors.Is(err, ErrStandInLimit) {
		t.Fatalf("A second withdrawal err = %v, want ErrStandInLimit", err)
	}
	b.Deposit(20) // deposits always work and free up stand-in room

	rep := Recover(l, 25, a, b)
	if rep.Replayed != 3 {
		t.Fatalf("replayed %d ops, want 3", rep.Replayed)
	}
	// 100 - 150 - 100 + 20 = -130, then a 25 fee.
	if rep.FinalBalance != -155 || len(rep.Compensations) != 1 {
		t.Fatalf("report = %+v", rep)
	}
	if !a.Online() || !b.Online() {
		t.Fatal("ATMs must return to normal mode after recovery")
	}
}

func TestRecoveryWithoutViolationNeedsNoCompensation(t *testing.T) {
	l := &Ledger{Balance: 500}
	a := New("A", l, 200)
	a.LinkDown()
	if err := a.Withdraw(200); err != nil {
		t.Fatal(err)
	}
	rep := Recover(l, 25, a)
	if rep.FinalBalance != 300 || len(rep.Compensations) != 0 {
		t.Fatalf("report = %+v", rep)
	}
}

PACELC arithmetic: overlap, survival, Cassandra levels across datacenters, and the no-failure latency of each level (the "else" price):

go
// Package pacelc holds the arithmetic behind tunable consistency: whether a
// read/write combination overlaps (R + W > N), how many replicas each
// Cassandra-style level needs, how many failures it survives, and what it
// costs in latency when nothing is failing (the "ELC" half of PACELC).
package pacelc

import (
	"fmt"
	"sort"
	"time"
)

// Majority is floor(n/2) + 1.
func Majority(n int) int { return n/2 + 1 }

// Overlaps reports whether every read set intersects every write set.
func Overlaps(n, r, w int) bool { return r+w > n }

// Survives is how many replicas may be down or partitioned away while an
// operation that needs k of n acknowledgements still succeeds.
func Survives(n, k int) int { return n - k }

// Topology is replicas per datacenter plus the coordinator's datacenter.
type Topology struct {
	RF    map[string]int
	Local string
}

func (t Topology) total() int {
	sum := 0
	for _, n := range t.RF {
		sum += n
	}
	return sum
}

// Required returns how many replica responses a level waits for, and per
// datacenter minimums for the levels that have them (Cassandra semantics).
func (t Topology) Required(level string) (total int, perDC map[string]int, err error) {
	switch level {
	case "ONE", "LOCAL_ONE", "ANY":
		return 1, nil, nil
	case "TWO":
		return 2, nil, nil
	case "THREE":
		return 3, nil, nil
	case "QUORUM":
		return Majority(t.total()), nil, nil
	case "ALL":
		return t.total(), nil, nil
	case "LOCAL_QUORUM":
		q := Majority(t.RF[t.Local])
		return q, map[string]int{t.Local: q}, nil
	case "EACH_QUORUM":
		perDC = map[string]int{}
		for dc, n := range t.RF {
			perDC[dc] = Majority(n)
			total += perDC[dc]
		}
		return total, perDC, nil
	}
	return 0, nil, fmt.Errorf("unknown consistency level %q", level)
}

// Replica is one copy with its round-trip time from the coordinator.
type Replica struct {
	DC  string
	RTT time.Duration
}

// Latency is the time a level takes with no failures: the coordinator waits
// for the k-th fastest response that also satisfies every per-DC minimum.
// LOCAL_ONE must be answered in the local datacenter.
func (t Topology) Latency(level string, replicas []Replica) (time.Duration, error) {
	total, perDC, err := t.Required(level)
	if err != nil {
		return 0, err
	}
	if level == "LOCAL_ONE" {
		perDC = map[string]int{t.Local: 1}
	}
	rs := append([]Replica(nil), replicas...)
	sort.Slice(rs, func(i, j int) bool { return rs[i].RTT < rs[j].RTT })
	got := map[string]int{}
	n := 0
	for _, r := range rs {
		got[r.DC]++
		n++
		if n >= total && satisfied(got, perDC) {
			return r.RTT, nil
		}
	}
	return 0, fmt.Errorf("level %s cannot be met by %d replicas", level, len(replicas))
}

func satisfied(got, need map[string]int) bool {
	for dc, k := range need {
		if got[dc] < k {
			return false
		}
	}
	return true
}
go
package pacelc

import (
	"testing"
	"time"
)

func TestOverlapAndSurvival(t *testing.T) {
	cases := []struct {
		n, r, w  int
		overlaps bool
	}{
		{3, 2, 2, true},  // QUORUM / QUORUM
		{3, 1, 3, true},  // ONE reads, ALL writes
		{3, 1, 1, false}, // ONE / ONE: fastest, may be stale
		{3, 1, 2, false}, // R + W = N is not enough
		{5, 3, 3, true},
	}
	for _, c := range cases {
		if got := Overlaps(c.n, c.r, c.w); got != c.overlaps {
			t.Errorf("Overlaps(%d,%d,%d) = %v", c.n, c.r, c.w, got)
		}
	}
	if Survives(3, Majority(3)) != 1 || Survives(5, Majority(5)) != 2 || Survives(3, 3) != 0 {
		t.Fatal("survival arithmetic wrong")
	}
}

// Two datacenters, RF 3 each (the Cassandra NetworkTopologyStrategy shape).
func TestCassandraLevels(t *testing.T) {
	topo := Topology{RF: map[string]int{"eu": 3, "us": 3}, Local: "eu"}
	want := map[string]int{"ONE": 1, "QUORUM": 4, "LOCAL_QUORUM": 2, "EACH_QUORUM": 4, "ALL": 6}
	for level, n := range want {
		got, _, err := topo.Required(level)
		if err != nil || got != n {
			t.Errorf("%s: got %d, %v; want %d", level, got, err, n)
		}
	}
}

// ELC: with no partition, the price of consistency is waiting for the
// slowest replica in the required set.
func TestLatencyIsTheElseBranch(t *testing.T) {
	topo := Topology{RF: map[string]int{"eu": 3, "us": 3}, Local: "eu"}
	replicas := []Replica{
		{"eu", 1 * time.Millisecond}, {"eu", 2 * time.Millisecond}, {"eu", 3 * time.Millisecond},
		{"us", 85 * time.Millisecond}, {"us", 88 * time.Millisecond}, {"us", 90 * time.Millisecond},
	}
	want := map[string]time.Duration{
		"LOCAL_ONE":    1 * time.Millisecond,
		"LOCAL_QUORUM": 2 * time.Millisecond,
		"QUORUM":       85 * time.Millisecond, // 4 of 6 must include a US replica
		"EACH_QUORUM":  88 * time.Millisecond, // 2 in EU and 2 in US
		"ALL":          90 * time.Millisecond,
	}
	for level, d := range want {
		got, err := topo.Latency(level, replicas)
		if err != nil || got != d {
			t.Errorf("%s: got %v, %v; want %v", level, got, err, d)
		}
	}
}

The lab driver:

go
// Command capsim prints the experiments used in the chapter's lab: the same
// three-node register under a partition with CP and AP settings, the ATM
// partition mode, and the latency cost of each Cassandra-style level.
package main

import (
	"fmt"
	"time"

	"academy/cap-pacelc/atm"
	"academy/cap-pacelc/pacelc"
	"academy/cap-pacelc/register"
)

func main() {
	for _, mode := range []struct {
		name string
		cfg  register.Config
	}{{"CP (R=2, W=2)", register.CP}, {"AP (R=1, W=1, hints)", register.AP}} {
		fmt.Printf("== %s, partition {n0,n1} | {n2}\n", mode.name)
		c := register.New(3, mode.cfg)
		_ = c.Write(0, "v1")
		c.Partition([]int{0, 1}, []int{2})
		report("write n0=left ", c.Write(0, "left"))
		report("write n2=right", c.Write(2, "right"))
		for _, n := range []int{1, 2} {
			v, err := c.Read(n)
			if err != nil {
				fmt.Printf("   read  n%d       -> %v\n", n, err)
				continue
			}
			fmt.Printf("   read  n%d       -> %q\n", n, v)
		}
		fmt.Printf("   replicas       %v\n", c.Values())
		rep := c.Heal()
		fmt.Printf("   heal           hints=%d repaired=%d discarded=%v -> %v\n",
			rep.HintsDelivered, rep.Repaired, rep.Discarded, c.Values())
	}

	fmt.Println("== ATM stand-in mode (limit 200), balance 100")
	l := &atm.Ledger{Balance: 100}
	a, b := atm.New("A", l, 200), atm.New("B", l, 200)
	a.LinkDown()
	b.LinkDown()
	report("A withdraw 150", a.Withdraw(150))
	report("B withdraw 100", b.Withdraw(100))
	report("A withdraw 100", a.Withdraw(100))
	rep := atm.Recover(l, 25, a, b)
	fmt.Printf("   recover        replayed=%d final=%d compensations=%v\n", rep.Replayed, rep.FinalBalance, rep.Compensations)

	fmt.Println("== ELC: latency per level, RF eu=3 us=3, coordinator in eu")
	topo := pacelc.Topology{RF: map[string]int{"eu": 3, "us": 3}, Local: "eu"}
	rs := []pacelc.Replica{
		{DC: "eu", RTT: 1 * time.Millisecond}, {DC: "eu", RTT: 2 * time.Millisecond}, {DC: "eu", RTT: 3 * time.Millisecond},
		{DC: "us", RTT: 85 * time.Millisecond}, {DC: "us", RTT: 88 * time.Millisecond}, {DC: "us", RTT: 90 * time.Millisecond},
	}
	for _, level := range []string{"LOCAL_ONE", "LOCAL_QUORUM", "QUORUM", "EACH_QUORUM", "ALL"} {
		need, _, _ := topo.Required(level)
		d, _ := topo.Latency(level, rs)
		fmt.Printf("   %-12s needs %d -> waits %v, survives %d replica(s) down\n", level, need, d, pacelc.Survives(6, need))
	}
}

func report(what string, err error) {
	if err != nil {
		fmt.Printf("   %s -> %v\n", what, err)
		return
	}
	fmt.Printf("   %s -> ok\n", what)
}

The Go angle ​

Go clientKnobNote
go.etcd.io/etcd/client/v3clientv3.WithSerializable() on GetDefault is linearizable; serializable is member-local
go.mongodb.org/mongo-driver/v2writeconcern.Majority(), readconcern.Majority(), readconcern.Linearizable()Set on client, database or collection options
github.com/gocql/gocqlgocql.One, gocql.Quorum, gocql.LocalQuorum, gocql.EachQuorum; Query.SerialConsistencyPer query or per session
github.com/aws/aws-sdk-go-v2/service/dynamodbGetItemInput.ConsistentRead *boolaws.Bool(true) for strong reads
github.com/jackc/pgx/v5SET LOCAL synchronous_commit TO ... inside txPer transaction choice of durability and visibility
github.com/twmb/franz-go/pkg/kgokgo.RequiredAcks(kgo.AllISRAcks())Topic still needs min.insync.replicas=2
context.WithTimeoutEvery quorum callThe timeout is your partition detector; pick it per operation
errors.Is(err, register.ErrUnavailable)Map to HTTP 503 + Retry-AfterRefusing honestly is the CP contract with the caller

Laravel ​

Before ​

One controller, one connection, every read from a replica, a check-then-update without a lock, and the same durability for money and likes:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * One consistency setting for every kind of data, and the invariant checked
 * against whatever replica the read connection happens to pick.
 *
 * - The SELECT goes to a read replica (asynchronous replication: may be stale).
 * - The check and the UPDATE are separate statements with no lock.
 * - The commit returns as soon as the primary flushed its own WAL; a failover
 *   to an asynchronous standby can lose it.
 * - After the withdrawal, the next page load reads the replica again and may
 *   show the old balance.
 */
class WalletControllerBefore
{
    public function withdraw(Request $request, int $walletId): JsonResponse
    {
        $amount = (int) $request->integer('amount');

        $balance = DB::table('wallets')->where('id', $walletId)->value('balance');

        if ($balance < $amount) {
            return response()->json(['error' => 'insufficient funds'], 422);
        }

        DB::table('wallets')->where('id', $walletId)->update(['balance' => $balance - $amount]);

        return response()->json(['balance' => $balance - $amount]);
    }
}

After ​

Connections named after the guarantee they give: PostgreSQL primary + replicas with sticky, a MongoDB "consistent" connection (w = majority, wTimeoutMS, readConcernLevel = majority, primary reads) and a "feed" connection (nearest member, w: 1, maxStalenessSeconds):

php
<?php

// config/database.php (excerpt): the consistency choice is part of the
// connection definition, so name connections after the guarantee they give.

return [

    'default' => env('DB_CONNECTION', 'pgsql'),

    'connections' => [

        // PostgreSQL primary + asynchronous read replicas. 'sticky' sends reads
        // to the write host after this request wrote (read-your-writes inside
        // one request). Synchronous replication itself is configured on the
        // server: synchronous_standby_names = 'ANY 1 (standby_a, standby_b)'.
        'pgsql' => [
            'driver' => 'pgsql',
            'read' => [
                'host' => [
                    env('DB_READ_HOST_1', 'replica-1.db.internal'),
                    env('DB_READ_HOST_2', 'replica-2.db.internal'),
                ],
            ],
            'write' => [
                'host' => [env('DB_WRITE_HOST', 'primary.db.internal')],
            ],
            'sticky' => true,
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'shop'),
            'username' => env('DB_USERNAME', 'shop'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => env('DB_SSLMODE', 'verify-full'),
        ],

        // MongoDB replica set, "consistent" profile: majority writes with a
        // bounded wait, majority reads from the primary. URI options from the
        // MongoDB PHP driver; laravel-mongodb passes 'options' through.
        'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => env('MONGODB_URI', 'mongodb://mongo-a.internal,mongo-b.internal,mongo-c.internal/?replicaSet=rs0'),
            'database' => env('MONGODB_DATABASE', 'shop'),
            'options' => [
                'w' => 'majority',
                'wTimeoutMS' => 2000,
                'journal' => true,
                'readConcernLevel' => 'majority',
                'readPreference' => 'primary',
                'retryWrites' => true,
            ],
        ],

        // Same replica set, "fast" profile for feeds and counters: the nearest
        // member answers, possibly a lagging secondary (maxStalenessSeconds
        // must be at least 90 when set).
        'mongodb_feed' => [
            'driver' => 'mongodb',
            'dsn' => env('MONGODB_URI', 'mongodb://mongo-a.internal,mongo-b.internal,mongo-c.internal/?replicaSet=rs0'),
            'database' => env('MONGODB_DATABASE', 'shop'),
            'options' => [
                'w' => 1,
                'readConcernLevel' => 'local',
                'readPreference' => 'nearest',
                'maxStalenessSeconds' => 120,
            ],
        ],
    ],
];

The decision table as code: an enum that maps each level to concrete knobs, and a policy that refuses to answer for data items nobody decided about:

php
<?php

namespace App\Support;

/**
 * What a use case needs, decided per data item, not per database.
 * Each case maps to concrete knobs in PostgreSQL and MongoDB.
 */
enum Consistency: string
{
    // Money, stock, unique usernames: refuse rather than guess (CP choice).
    case Linearizable = 'linearizable';

    // Profile edits, settings: the author must see their own write.
    case ReadYourWrites = 'read-your-writes';

    // Likes, view counts, feeds: any replica, converge later (AP choice).
    case Eventual = 'eventual';

    /** PostgreSQL synchronous_commit for writes of this kind. */
    public function synchronousCommit(): string
    {
        return match ($this) {
            self::Linearizable => 'remote_apply', // visible on the sync standby before COMMIT returns
            self::ReadYourWrites => 'on',         // durable on the sync standby
            self::Eventual => 'off',              // do not even wait for the local WAL flush
        };
    }

    /** MongoDB read concern level for reads of this kind. */
    public function mongoReadConcern(): string
    {
        return match ($this) {
            self::Linearizable => 'linearizable',
            self::ReadYourWrites => 'majority',
            self::Eventual => 'local',
        };
    }

    /** What the API does when the consistent path is not reachable. */
    public function onPartition(): string
    {
        return match ($this) {
            self::Linearizable => 'refuse with 503 and Retry-After',
            self::ReadYourWrites => 'read from the primary; refuse writes if it is gone',
            self::Eventual => 'serve the nearest replica, mark the answer as possibly stale',
        };
    }
}
php
<?php

namespace App\Support;

use InvalidArgumentException;

/**
 * The per-data-item decision table from the chapter, as code. Reviewing a new
 * feature means adding one row here and justifying it.
 */
final class ConsistencyPolicy
{
    /** @var array<string, Consistency> */
    private const ITEMS = [
        'wallet.balance' => Consistency::Linearizable,
        'inventory.stock' => Consistency::Linearizable,
        'user.username' => Consistency::Linearizable,
        'user.profile' => Consistency::ReadYourWrites,
        'user.settings' => Consistency::ReadYourWrites,
        'post.likes' => Consistency::Eventual,
        'post.views' => Consistency::Eventual,
        'feed.timeline' => Consistency::Eventual,
    ];

    public static function for(string $item): Consistency
    {
        return self::ITEMS[$item]
            ?? throw new InvalidArgumentException("No consistency decision recorded for [{$item}].");
    }

    /** @return array<string, Consistency> */
    public static function all(): array
    {
        return self::ITEMS;
    }
}

Money on PostgreSQL: SET LOCAL synchronous_commit TO 'remote_apply' inside the transaction, a row lock, an idempotency key, a CHECK constraint in the schema:

php
<?php

namespace App\Services;

use App\Support\ConsistencyPolicy;
use DomainException;
use Illuminate\Support\Facades\DB;

/**
 * Money is a CP item: the check and the change happen on the primary under a
 * row lock, and COMMIT returns only after a synchronous standby has applied
 * the change. If no synchronous standby answers, COMMIT waits: the system
 * gives up availability for this operation instead of risking a lost debit.
 */
final class WalletService
{
    public function withdraw(int $walletId, int $amount, string $idempotencyKey): int
    {
        $level = ConsistencyPolicy::for('wallet.balance');

        return DB::transaction(function () use ($walletId, $amount, $idempotencyKey, $level): int {
            // Per-transaction override; the default for the server stays 'on'.
            DB::statement("SET LOCAL synchronous_commit TO '{$level->synchronousCommit()}'");

            $done = DB::table('wallet_entries')->where('idempotency_key', $idempotencyKey)->first();
            if ($done !== null) {
                return (int) DB::table('wallets')->where('id', $walletId)->value('balance');
            }

            $wallet = DB::table('wallets')->where('id', $walletId)->lockForUpdate()->first();
            if ($wallet === null || $wallet->balance < $amount) {
                throw new DomainException('insufficient funds');
            }

            DB::table('wallets')->where('id', $walletId)->update([
                'balance' => DB::raw('balance - '.(int) $amount),
                'updated_at' => now(),
            ]);
            DB::table('wallet_entries')->insert([
                'wallet_id' => $walletId,
                'amount' => -$amount,
                'idempotency_key' => $idempotencyKey,
                'created_at' => now(),
            ]);

            return (int) $wallet->balance - $amount;
        }, 3);
    }
}

Likes on PostgreSQL: synchronous_commit off for this transaction only, idempotent insert, replica reads:

php
<?php

namespace App\Services;

use App\Support\ConsistencyPolicy;
use Illuminate\Support\Facades\DB;

/**
 * Likes are an AP/EL item: losing the last few hundred milliseconds of likes
 * in a crash is acceptable, waiting for a standby on every tap is not.
 * Reads come from a replica and may lag; the UI shows the count as approximate.
 */
final class LikeService
{
    public function like(int $postId, int $userId): void
    {
        $level = ConsistencyPolicy::for('post.likes');

        DB::transaction(function () use ($postId, $userId, $level): void {
            DB::statement("SET LOCAL synchronous_commit TO '{$level->synchronousCommit()}'");

            // Idempotent by construction: one row per (post, user).
            $inserted = DB::table('post_likes')->insertOrIgnore([
                'post_id' => $postId,
                'user_id' => $userId,
                'created_at' => now(),
            ]);

            if ($inserted === 1) {
                DB::table('posts')->where('id', $postId)->increment('likes_count');
            }
        });
    }

    public function count(int $postId): int
    {
        // Avoid stickiness on purpose: any replica is fine for this number.
        return (int) DB::table('posts')->where('id', $postId)->value('likes_count');
    }
}

Money on MongoDB: a collection handle with WriteConcern::MAJORITY (2 s wtimeout, journaled) and linearizable read concern; findOne bounded by maxTimeMS; write concern errors treated as "outcome unknown, retry with the same key":

php
<?php

namespace App\Services;

use App\Support\ConsistencyPolicy;
use Illuminate\Support\Facades\DB;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Collection;
use MongoDB\Driver\Exception\BulkWriteException;
use MongoDB\Driver\Exception\ExecutionTimeoutException;
use MongoDB\Driver\ReadConcern;
use MongoDB\Driver\WriteConcern;
use RuntimeException;

/**
 * The same CP choice on MongoDB: w:majority with a bounded wait, and a
 * linearizable read of one document by a unique key, bounded by maxTimeMS.
 * On a minority partition both calls fail instead of returning stale data.
 */
final class MongoLedger
{
    private function collection(): Collection
    {
        $level = ConsistencyPolicy::for('wallet.balance');

        return DB::connection('mongodb')
            ->getDatabase()
            ->selectCollection('wallets', [
                'writeConcern' => new WriteConcern(WriteConcern::MAJORITY, 2000, true),
                'readConcern' => new ReadConcern($level->mongoReadConcern()),
            ]);
    }

    public function credit(string $walletId, int $amount, string $idempotencyKey): void
    {
        try {
            $this->collection()->updateOne(
                ['_id' => $walletId, 'applied' => ['$ne' => $idempotencyKey]],
                [
                    '$inc' => ['balance' => $amount],
                    '$push' => ['applied' => ['$each' => [$idempotencyKey], '$slice' => -1000]],
                    '$set' => ['updated_at' => new UTCDateTime],
                ],
            );
        } catch (BulkWriteException $e) {
            // A write concern error does not undo the write on the primary:
            // the outcome is unknown, so the caller retries with the same key.
            throw new RuntimeException('credit not confirmed by a majority; retry with the same key', 0, $e);
        }
    }

    public function balance(string $walletId): int
    {
        try {
            $doc = $this->collection()->findOne(['_id' => $walletId], ['maxTimeMS' => 1000]);
        } catch (ExecutionTimeoutException $e) {
            throw new RuntimeException('no majority-confirmed primary within 1 s', 0, $e);
        }

        return (int) ($doc['balance'] ?? 0);
    }
}

The HTTP contract: CP items return 503 with Retry-After, the owner's balance is read from the primary with usingWritePdo, AP items are labelled approximate:

php
<?php

namespace App\Http\Controllers;

use App\Services\LikeService;
use App\Services\WalletService;
use DomainException;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * The HTTP face of the per-item decision: CP items refuse honestly with 503,
 * AP items answer and say the answer may be stale, read-your-writes items read
 * from the primary for the author.
 */
class WalletController
{
    public function __construct(
        private readonly WalletService $wallets,
        private readonly LikeService $likes,
    ) {}

    public function withdraw(Request $request, int $walletId): JsonResponse
    {
        $validated = $request->validate(['amount' => ['required', 'integer', 'min:1']]);
        $key = (string) $request->header('Idempotency-Key');
        abort_if($key === '', 400, 'Idempotency-Key header required');

        try {
            $balance = $this->wallets->withdraw($walletId, $validated['amount'], $key);
        } catch (DomainException $e) {
            return response()->json(['error' => $e->getMessage()], 422);
        } catch (QueryException $e) {
            // Primary unreachable or failing over: say so instead of guessing.
            return response()->json(['error' => 'temporarily unavailable'], 503, ['Retry-After' => '5']);
        }

        return response()->json(['balance' => $balance]);
    }

    public function show(int $walletId): JsonResponse
    {
        // The owner looking at their balance right after a withdrawal: read the
        // primary for this callback only, whatever stickiness says.
        $wallet = DB::connection()->usingWritePdo(
            fn ($connection) => $connection->table('wallets')->where('id', $walletId)->first(),
        );

        return response()->json(['balance' => $wallet?->balance]);
    }

    public function likes(int $postId): JsonResponse
    {
        return response()->json([
            'likes' => $this->likes->count($postId),
            'approximate' => true,
        ])->header('Cache-Control', 'public, max-age=5');
    }
}

Session-level read-your-writes with PreventStaleDatabaseReads::for(5):

php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;

// Session-level read-your-writes: for 5 seconds after a request in this
// session wrote to the default connection, its reads use the write host.
// It must run after StartSession, which the web group already includes.
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->web(append: [
            PreventStaleDatabaseReads::for(5),
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })
    ->create();

Schema and tests:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('wallets', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('balance')->default(0);
            $table->timestamps();
        });

        // The invariant lives in the database, so no code path can skip it.
        DB::statement('ALTER TABLE wallets ADD CONSTRAINT wallets_balance_non_negative CHECK (balance >= 0)');

        Schema::create('wallet_entries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('wallet_id')->constrained();
            $table->bigInteger('amount');
            $table->string('idempotency_key', 64)->unique();
            $table->timestamp('created_at');
        });

        Schema::create('post_likes', function (Blueprint $table) {
            $table->unsignedBigInteger('post_id');
            $table->unsignedBigInteger('user_id');
            $table->timestamp('created_at');
            $table->primary(['post_id', 'user_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('post_likes');
        Schema::dropIfExists('wallet_entries');
        Schema::dropIfExists('wallets');
    }
};
php
<?php

namespace Tests\Unit;

use App\Support\Consistency;
use App\Support\ConsistencyPolicy;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;

class ConsistencyPolicyTest extends TestCase
{
    public function test_money_is_linearizable_and_waits_for_the_standby(): void
    {
        $level = ConsistencyPolicy::for('wallet.balance');

        $this->assertSame(Consistency::Linearizable, $level);
        $this->assertSame('remote_apply', $level->synchronousCommit());
        $this->assertSame('linearizable', $level->mongoReadConcern());
    }

    public function test_likes_are_eventual_and_skip_the_flush(): void
    {
        $this->assertSame('off', ConsistencyPolicy::for('post.likes')->synchronousCommit());
    }

    public function test_every_item_needs_an_explicit_decision(): void
    {
        $this->expectException(InvalidArgumentException::class);

        ConsistencyPolicy::for('cart.items');
    }
}

The Laravel angle ​

Laravel featureUse for consistencyNote (Laravel 13 docs)
read / write hostsRoute reads to replicas"When multiple values exist in the host configuration array, a database host will be randomly chosen for each request"
'sticky' => trueRead-your-writes within one request"any further "read" operations will use the "write" connection" after a write in the request cycle
DB::withoutAffectingStickiness()Housekeeping writes that should not pin reads to the primaryJob progress, audit timestamps
PreventStaleDatabaseReads middlewareRead-your-writes across requests in a session"By default, requests within two seconds of a write will use the write connection"; ::for(5); after StartSession
DB::connection()->usingWritePdo(fn ...)Force primary reads for one callbackRestores the previous read preference even on exceptions
DB::transaction(fn, attempts) + DB::statement('SET LOCAL ...')Per-transaction synchronous_commitSET LOCAL lasts until COMMIT/ROLLBACK
lockForUpdate()Check-then-act on the primaryLinearizable for that row on one primary
insertOrIgnore()Idempotent AP writesUnique key does the dedup
laravel-mongodb optionsw, wTimeoutMS, journal, readConcernLevel, readPreference, maxStalenessSecondsURI options of the MongoDB PHP library
getDatabase()->selectCollection($name, [...])Per-collection writeConcern / readConcernMongoDB\Driver\WriteConcern, ReadConcern::LINEARIZABLE

Solving the classic problems ​

Overdraft during a partition ​

SolutionHowAdvantageCost / limitation
CP on the balanceMajority / sync-rep commit, row lockInvariant always holdsMinority side cannot withdraw
Bounded partition modeStand-in limit per site (ATM), log, reconcileAvailable with known worst caseNeeds compensation (fees, collections)
Escrow / split budgetPre-allocate part of the balance to each siteEach site decides locally without riskUnused budget is locked; rebalancing needed
Reservation then captureReserve on the CP side, capture laterClear user stateTwo steps, timeouts

The author does not see their own write ​

SolutionHowAdvantageCost / limitation
Request-level stickinessLaravel stickyOne lineOnly within the request
Session windowPreventStaleDatabaseReads::for(n), Facebook-style 20 sCovers redirectsExtra primary load after writes
Causal tokenMongoDB causally consistent sessions; CockroachDB causality tokenExactClient must carry the token
Visibility before ackPG remote_apply, Cassandra LOCAL_QUORUM both waysAny replica is fine afterwardsHigher write latency

Two leaders after a network blip (split brain) ​

SolutionHowAdvantageCost / limitation
Majority writesw: "majority", acks=all + min.insync.replicas=2, RaftOld leader cannot acknowledgeNeeds 3 failure domains
Fencing tokensStorage rejects lower epochsProtects external side effectsEvery resource must check the token
Leases with marginLease shorter than failure detection; clock boundsSimpleDepends on bounded clock drift
Witness / odd votersDynamoDB MRSC witness, third-zone voterBreaks tiesExtra infrastructure

QUORUM across regions is too slow ​

SolutionHowAdvantageCost / limitation
LOCAL_QUORUM both waysUsers homed per regionLocal latency, read-your-writes per regionCross-region readers may be stale
Home region per recordWrites go to the record's region (PNUTS-style)Fast for the home regionRemote writers pay RTT
Consensus group placementCockroachDB REGIONAL BY ROW, Spanner leader regionCP with local latency for mostSurvives region loss only with 3+ regions
EACH_QUORUM only where requiredFraud flags, entitlementsStrong across regions where it mattersHighest write latency

Writes hang after a standby died (PostgreSQL) ​

SolutionHowAdvantageCost / limitation
Quorum of candidatesANY 1 (a, b) or FIRST 1 (a, b)One standby may dieNeed two standbys
MonitoringAlert on pg_stat_replication.sync_stateEarly warningOperational work
Explicit degrade procedureRunbook to change synchronous_standby_names and reloadRestores availabilityWindow where commits are not replicated (choose A consciously)
Per-transaction levelssynchronous_commit local/off for non-critical writesOnly critical writes waitCode discipline

Acknowledged writes vanish after the partition heals ​

SolutionHowAdvantageCost / limitation
Avoid LWW on read-modify-write dataUse CP path or LWT for those fieldsNo silent lossLatency, availability
Mergeable typesCassandra sets/maps/counters, CRDTsBoth sides' intent survivesNot every invariant is mergeable
SiblingsRiak/Dynamo vector clocks, app mergeNothing silently droppedApp must merge
Detect and compensateLog discarded versions (the Go HealReport.Discarded)Business can repairNeeds a compensation process

Producer gets NotEnoughReplicas (Kafka) ​

SolutionHowAdvantageCost / limitation
Retry with idempotenceenable.idempotence=true, bounded delivery.timeout.msNo duplicatesProducer blocks while ISR is small
Buffer locally (outbox)Keep events in the database outbox until acceptedNo loss, service stays upDelay (Transactional Outbox)
Lower min.insync.replicas temporarilyOperator decisionAvailabilityDurability risk: choose A explicitly

Choosing ​

By data item ​

SituationRecommendationExtra techniqueReason
Ledger, balance, paymentsPC/EC: sync commit (remote_apply or on), w: "majority", Spanner/CockroachDBIdempotency keys, CHECK constraints, 503 + Retry-AfterOne wrong answer costs more than refusing
Inventory with flash salesPC/EC with a bounded AP reservation pool per regionEscrow, compensation (backorder email)Balance availability and overselling risk
Unique names, locks, leader electionPC/EC: etcd/ZooKeeper linearizable, SQL unique index, LWT SERIALFencing tokensDuplicates are unrecoverable without humans
User profile, settingsPA/EL with read-your-writesSticky, session window, LOCAL_QUORUMOnly the author notices staleness
Carts, wish listsPA/ELSets, CRDTs, idempotent addsAlways-writeable beats strict order
Counters, likes, viewsPA/ELSharded counters, ONE, synchronous_commit = offApproximate is acceptable
Feeds, search, recommendationsPA/EL with harvest < 100%Partial results, deadlinesYield matters more than completeness
Configuration and feature flagsPC/EC writes, AP cached reads with TTLWatches, versioned configWrites rare, reads everywhere
Global sessionsPA/EL (DynamoDB MREC, Cassandra LOCAL_QUORUM)TTL, idempotent updatesLosing an edit is acceptable
Cross-region strong dataPC/EC (Spanner, CockroachDB, DynamoDB MRSC)Place majority near writersPay RTT on writes, RPO 0

By product question ​

You needChooseAvoid
Strong reads on a coordination storeetcd default reads, ZooKeeper sync() + read, Consul ?consistentStale/serializable reads for lock decisions
Strong single-document reads in MongoDBw: "majority" + readConcern: "linearizable" + maxTimeMSw: 1 with secondary reads
Read-your-writes on SQL replicasLaravel sticky + PreventStaleDatabaseReads, or PG remote_applyRandom replica reads right after writes
No acknowledged-write loss in KafkaRF 3, min.insync.replicas=2, acks=all, unclean election offacks=1 for business events
Low latency multi-region CassandraLOCAL_QUORUM / LOCAL_ONEQUORUM on hot paths
Never-diverging multi-region key-valueDynamoDB MRSCMREC plus read-modify-write

In architecture: from a single process to a distributed system ​

CAP starts to matter the moment state is copied to a second place that can be unreachable. The decision moves from "which database" to "which operation, during which failure".

Monolith: one process, one database ​

One PostgreSQL primary and one application is not a CAP system: there is one copy, and if it is unreachable nothing works (C, not A). The simplest correct usage is to keep it that way until you need replicas, with a synchronous standby for durability (synchronous_standby_names = 'ANY 1 (a, b)') and asynchronous replicas only for reporting. Concrete example: a shop with 50 orders per minute on one primary; checkout is linearizable for free because every read goes to the primary.

Modular monolith: boundaries without the network ​

Modules share the process but should not share assumptions: give each module's data its consistency label now (the ConsistencyPolicy table), even though everything is still on one primary. When the catalogue module later moves its reads to replicas, only its rows change from "primary" to "replica + sticky". Example: the catalogue reads products from a replica with Laravel read hosts, while the orders module keeps primary reads and lockForUpdate.

Microservices: CAP between services ​

Every service call is a replication link that can partition. The order service cannot be linearizable with the payment service; it can be available (accept the order as "pending") or consistent (refuse until payment answers). Common shape:

text
     Checkout across services during a partition between orders and payments
1    POST /orders (Idempotency-Key k)        orders: insert order "pending" + outbox row (local transaction, CP on its own DB)
2    outbox relay -> Kafka orders.created     acks=all, min.insync.replicas=2 (refuses if ISR too small)
3    payments unreachable                      orders stays "pending"; UI shows "payment in progress"
4    payments back: consumes, charges once     inbox dedup on k; emits payment.succeeded
5    orders -> "confirmed"; if it fails        saga compensation: release stock, email the user

Each service picks CP or AP for its own data; across services you get eventual consistency by design, made safe with the outbox, idempotent consumers and sagas (Saga Pattern, Idempotent Consumers).

Distributed data: replicas, caches, regions ​

Here CAP and PACELC are literal. Read replicas are AP/EL for reads (stale by the lag); caches are AP by construction (Fox and Brewer's "expiration-based caching to get AP"); multi-region writes are either PA/EL with conflict resolution (DynamoDB MREC, Cassandra LOCAL_QUORUM) or PC/EC with consensus placement (Spanner, CockroachDB, DynamoDB MRSC). Example: a global SaaS keeps tenant data in a home region (PC/EC within the region, ANY 1 sync standby in another zone), serves dashboards from cross-region read replicas (PA/EL, labelled "updated 3 s ago"), and stores sessions in DynamoDB MREC.

Scaling path: 1x, 10x, 100x ​

ScaleShapeCAP/PACELC decision
1xOne primary, sync standby in another zoneC over A for writes if the standby is required; quorum of standbys to keep A
10xPrimary + read replicas, cache, queuePer-item reads: primary for authors and money, replicas for the rest (sticky, session window)
100xSharded or multi-region; Cassandra/DynamoDB for high-volume items, Spanner/CockroachDB or sharded SQL for moneyPer-operation levels (LOCAL_QUORUM, ConsistentRead), partition-mode runbooks, compensation jobs, chaos tests of partitions

Lab: the same register as CP and AP, partition mode, and quorum latency ​

Steps 1–2 run in one process (Go 1.24+, no network). Steps 3–6 use real clusters and are expected, not run: they need multi-node setups that this chapter does not start.

bash
# 1) Tests (run)
cd docs/snippets/system-design/cap-pacelc/go
go test ./...
# ok  academy/cap-pacelc/atm
# ok  academy/cap-pacelc/before
# ok  academy/cap-pacelc/pacelc
# ok  academy/cap-pacelc/register
go test -run TestRandomScheduleCPNeverStale -v ./register
# register_test.go: CP: refused=875 stale=0 | AP: refused=0 stale=420
bash
# 2) The simulation (run; output is deterministic)
go run ./cmd/capsim
# == CP (R=2, W=2), partition {n0,n1} | {n2}
#    write n0=left  -> ok
#    write n2=right -> write via node 2: unavailable: not enough replicas reachable (reached 1, need W=2)
#    read  n1       -> "left"
#    read  n2       -> read via node 2: unavailable: not enough replicas reachable (reached 1, need R=2)
#    replicas       [left left v1]
#    heal           hints=0 repaired=1 discarded=[] -> [left left left]
# == AP (R=1, W=1, hints), partition {n0,n1} | {n2}
#    write n0=left  -> ok
#    write n2=right -> ok
#    read  n1       -> "left"
#    read  n2       -> "right"
#    replicas       [left left right]
#    heal           hints=2 repaired=0 discarded=[left] -> [right right right]
# == ATM stand-in mode (limit 200), balance 100
#    A withdraw 150 -> ok
#    B withdraw 100 -> ok
#    A withdraw 100 -> A: stand-in limit reached; try again later (net 150 of 200)
#    recover        replayed=2 final=-175 compensations=[{overdrawn by 150 during partition; fee charged, repayment requested 25}]
# == ELC: latency per level, RF eu=3 us=3, coordinator in eu
#    LOCAL_ONE    needs 1 -> waits 1ms, survives 5 replica(s) down
#    LOCAL_QUORUM needs 2 -> waits 2ms, survives 4 replica(s) down
#    QUORUM       needs 4 -> waits 85ms, survives 2 replica(s) down
#    EACH_QUORUM  needs 4 -> waits 88ms, survives 2 replica(s) down
#    ALL          needs 6 -> waits 90ms, survives 0 replica(s) down
sql
-- 3) Cassandra, 3 nodes, RF 3 (expected, not run). Stop two nodes, then in cqlsh:
CREATE KEYSPACE lab WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3};
CREATE TABLE lab.kv (k text PRIMARY KEY, v text);
CONSISTENCY QUORUM;
INSERT INTO lab.kv (k, v) VALUES ('a', '1');
-- expected: Unavailable ... Cannot achieve consistency level QUORUM. Required 2 but only 1 alive.
CONSISTENCY ONE;
INSERT INTO lab.kv (k, v) VALUES ('a', '1');
-- expected: succeeds (AP for this request); restarted nodes receive hints
SERIAL CONSISTENCY SERIAL;
INSERT INTO lab.kv (k, v) VALUES ('user:sara', 'id-7') IF NOT EXISTS;
-- expected with 2 nodes down: unavailable (Paxos needs a majority)
bash
# 4) etcd, 3 members; block member 3 from the others (expected, not run)
etcdctl --endpoints=http://192.0.2.13:2379 put /cfg/flag on
# expected: Error: etcdserver: request timed out
etcdctl --endpoints=http://192.0.2.13:2379 get /cfg/flag --consistency=s
# expected: /cfg/flag  off    (stale but answered)
etcdctl --endpoints=http://192.0.2.11:2379 get /cfg/flag
# expected: /cfg/flag  on     (majority side)
js
// 5) MongoDB replica set rs0 (P-S-S); isolate the primary with one client (expected, not run)
db.wallets.insertOne({ _id: 7, balance: 100 }, { writeConcern: { w: "majority", wtimeout: 2000 } })
// expected on the isolated primary: write concern error, code 64 WriteConcernTimeout, after 2 s
db.wallets.find({ _id: 7 }).readConcern("linearizable").maxTimeMS(3000)
// expected: MaxTimeMSExpired (50), never a stale document
db.getMongo().setReadPref("nearest")
db.wallets.find({ _id: 7 }).readConcern("local")
// expected from a minority secondary: answers, possibly stale
bash
# 6) PostgreSQL primary with synchronous_standby_names = 'standby_a'; stop standby_a (expected, not run)
psql -h primary -c "BEGIN; UPDATE wallets SET balance = balance - 1 WHERE id = 7; COMMIT;"
# expected: hangs at COMMIT. In another session: SELECT pg_cancel_backend(<pid>);
# expected in the first session:
# WARNING:  canceling wait for synchronous replication due to user request
# DETAIL:  The transaction has already committed locally, but might not have been replicated to the standby.
psql -h primary -c "ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)'; " -c "SELECT pg_reload_conf();"
# expected: commits proceed as soon as standby_b confirms

Common misconceptions ​

BeliefReality
Pick any two of C, A and PP is not optional; the choice is C or A during a partition, per operation
A CA distributed system exists"CA" only means partitions are rare enough to ignore (Brewer 2017: Spanner "effectively CA", technically CP)
CAP consistency is ACID consistencyCAP C is linearizability of single operations; ACID C is constraint preservation
Serializable means linearizableSerializability orders transactions, not necessarily in real time; PostgreSQL SSI is not linearizable
CAP availability is uptimeIt is "every request received by a non-failing node" answered; single-leader systems fail it
Databases are CP or APMost configurations are neither; classify operations and settings (Kleppmann)
R + W > N gives linearizabilityIt gives overlap; sloppy quorums, LWW and concurrent writes still break linearizability
Eventual consistency happens because of partitionsUsually it is chosen for latency on normal days: the EL of PACELC
acks=all waits for all replicasIt waits for the current ISR, which can be the leader alone unless min.insync.replicas ≥ 2
Synchronous replication makes standbys up to date for readsOnly remote_apply waits for visibility; on waits for flush
Cancelling a hung synchronous commit rolls it backIt "has already committed locally"
w: "majority" makes every read correctReads also need majority or linearizable read concern, and the right member
ZooKeeper reads are linearizable because it is CPPlain reads come from the connected server; use sync()
Last-write-wins resolves conflictsIt discards one of them; compensation or merge is still your job
Partitions are clean, symmetric splitsThey are often partial, one-sided and short; detection is per node, by timeout

Cheat sheet ​

TopicRemember
CAPDuring a partition, an operation needing both sides is either linearizable or always answered, not both
DefinitionsC = linearizable; A = every non-failing node responds; P = arbitrary message loss
Partition"a time bound on communication"; detected by timeouts, per node
CANot a choice; a probability claim ("effectively CA")
Partition lifecycleDetect → partition mode (limit or log) → recovery (merge + compensate)
PACELCP: A or C; Else: L or C. PA/EL, PC/EC, PA/EC (MongoDB), PC/EL (PNUTS)
QuorumMajority = ⌊N/2⌋+1; R + W > N overlaps; survives N − k failures
CassandraLOCAL_QUORUM in multi-region; QUORUM crosses regions; SERIAL for CAS
Sloppy quorumStand-ins accept writes with hints; overlap not guaranteed; Riak pr/pw > 0 = strict
etcd / ZK / ConsulLinearizable default / sync() / ?consistent; fast reads: --consistency=s / plain / ?stale
MongoDBw: "majority" + wtimeout; linearizable + maxTimeMS on the primary, one document
PostgreSQLANY 1 (a, b); synchronous_commit per transaction: remote_apply > on > remote_write > local > off
KafkaRF 3, min.insync.replicas=2, acks=all, unclean election off
DynamoDBConsistentRead=true costs 2x; MREC LWW vs MRSC three Regions
Harvest/yieldPartial answers keep yield; mark them
Per itemMoney/locks/uniqueness CP; carts/likes/feeds AP; profiles AP + read-your-writes

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A three-node etcd cluster is split {1, 2} | {3}. What happens to a put and to a default get sent to member 3, and how can a client still read there? Important ​

Answer

Answer: Both need consensus: the put times out (etcdserver: request timed out) and the default linearizable get cannot be served. A serializable read (etcdctl get --consistency=s or clientv3.WithSerializable()) answers from member 3's local store, possibly stale. That is choosing A over C for that read only.

2 — Why is "CA" not a valid choice for a system running on more than one machine? Must-know ​

Answer

Answer: You cannot choose to have no partitions. When one happens, the system must either refuse (C) or answer (A). Brewer 2012: "If the choice is CA, and then there is a partition, the choice must revert to C or A." CA can only mean partitions are rare enough to ignore, as with Spanner's "effectively CA".

3 — Under the strict definitions, why is a PostgreSQL primary with asynchronous read replicas neither CP nor AP? Good to know ​

Answer

Answer: Not AP: a client partitioned from the primary cannot write, so not every non-failing node answers. Not CP: reads from asynchronous replicas can be stale, so reads are not linearizable. Kleppmann's point: such systems are "neither CAP-consistent nor CAP-available".

4 — N = 3. Compare (R, W) = (1, 2) and (2, 2) during a partition {A, B} | {C}. Important ​

Answer

Answer: (1, 2): writes succeed on the majority side; a read at C succeeds with the old value (stale, no error) because 1 + 2 = 3 is not > 3. (2, 2): writes and reads succeed on the majority side; both fail at C. The Go test TestRPlusWNotGreaterThanNIsStale shows the first case.

5 — Two datacenters with RF 3 each. How many replicas do QUORUM, LOCAL_QUORUM and EACH_QUORUM need, and which crosses the ocean on every request? Good to know ​

Answer

Answer: QUORUM needs 4 of 6, so at least one remote replica: every request pays a cross-region round trip. LOCAL_QUORUM needs 2 local replicas. EACH_QUORUM needs 2 in each datacenter (4 total) and also crosses the ocean.

6 — What does PACELC add to CAP, and how would you classify a default Cassandra deployment and Spanner? Important ​

Answer

Answer: The "else" trade-off between latency and consistency when there is no partition. Default Cassandra (Abadi) is PA/EL: available during partitions and low-latency at the cost of consistency normally. Spanner is PC/EC: it refuses on the minority side and pays quorum and commit-wait latency normally.

7 — Describe Brewer's three steps for managing a partition, using the ATM. Good to know ​

Answer

Answer: Detect: the ATM times out talking to the bank. Partition mode: stand-in mode allows net withdrawals up to a limit (say $200) and logs them; deposits always work. Recovery: replay the log (commutative), check balance ≥ 0, and compensate violations with a fee and a repayment request.

8 — A PostgreSQL commit hangs because the only synchronous standby is unreachable; an operator cancels it. Is the transaction rolled back? Important ​

Answer

Answer: No. PostgreSQL warns "canceling wait for synchronous replication due to user request" with the detail "The transaction has already committed locally, but might not have been replicated to the standby." Use ANY 1 (a, b) so one standby can be lost.

9 — A Kafka topic has RF 3, min.insync.replicas=1, producers use acks=all. Two followers fall out of the ISR. What is the durability risk, and what is the fix? Important ​

Answer

Answer: The ISR is just the leader, so acks=all is satisfied by one broker; if it dies before followers catch up, acknowledged records are lost (or the partition stays offline with unclean election disabled). Set min.insync.replicas=2 so writes are rejected with NOT_ENOUGH_REPLICAS instead.

10 — Which MongoDB settings give a linearizable balance read, and what must the client add so the read does not hang on a minority primary? Good to know ​

Answer

Answer: Writes with w: "majority", reads with readConcern: "linearizable" on the primary, by a filter that uniquely identifies one document; plus maxTimeMS, because "Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable."

11 — Give one data item you would make CP and one you would make AP in a social shopping app, with the knob. Must-know ​

Answer

Answer: CP: the wallet balance or stock count, via SET LOCAL synchronous_commit TO 'remote_apply' with a row lock (or MongoDB majority/linearizable). AP: likes, via synchronous_commit = off and replica reads (or Cassandra ONE), labelled approximate.

12 — What are harvest and yield, and how would a search page use them during a partition? Good to know ​

Answer

Answer: Yield is the probability of completing a request; harvest is the fraction of data reflected in the answer. During a partition that hides 3 of 100 shards, the page returns results from 97 shards (harvest 97%, yield kept) and marks them partial instead of failing.

Glossary ​

TermMeaning
CAP theoremDuring a partition, a replicated read/write object cannot be both linearizable and always available (Gilbert and Lynch 2002)
Consistency (CAP)Linearizability, also called atomic consistency
LinearizabilityOne total order of operations consistent with real time; each takes effect at an instant between call and return
Linearizable readA read guaranteed to see every write acknowledged before it began (etcd default, MongoDB linearizable)
Serializable read (etcd)A member-local read that may be stale; not SQL serializable isolation
Availability (CAP)Every request received by a non-failing node results in a response
Partition toleranceCorrect behaviour when arbitrarily many messages between nodes are lost
Network partitionSome nodes cannot exchange messages in time; detected by timeouts, may be partial or one-sided
CPAn operation/configuration that refuses on the side without a quorum to stay consistent
APAn operation/configuration that answers on every side and reconciles later
CA mythThe idea that a distributed system can opt out of partitions; at best "effectively CA"
Partition modeAn explicit mode entered on detecting a partition: limit risky operations, log everything
Partition recoveryMerging state after the partition and compensating for violated invariants
CompensationA business action that restores an invariant or corrects an externalised mistake
InvariantA rule the data must satisfy, such as balance ≥ 0 or unique usernames
Stand-in modeBrewer's ATM partition mode: offline withdrawals up to a limit
PACELCIf Partition: A or C; Else: Latency or Consistency (Abadi 2012)
PA/EL, PC/EC, PA/EC, PC/ELThe four PACELC classes
Latency (in PACELC)The time consistency costs on a normal day: waiting for remote replicas
Tunable consistencyChoosing consistency per request (Cassandra levels, DynamoDB ConsistentRead, Mongo concerns)
QuorumA set of replicas whose acknowledgement is required; majority quorums intersect
Majority⌊N/2⌋ + 1 replicas
R + W > NRead and write quorum sizes whose sets always overlap
N, R, WReplication factor, read quorum, write quorum (Dynamo)
ONE, TWO, THREECassandra levels needing that many replica responses
QUORUMCassandra: majority of all replicas across datacenters
LOCAL_QUORUMCassandra: majority in the coordinator's datacenter
EACH_QUORUMCassandra: majority in every datacenter
ALLCassandra: every replica
LOCAL_ONECassandra: one replica in the local datacenter
ANYCassandra write level that accepts a stored hint
SERIAL / LOCAL_SERIALCassandra serial consistency for the Paxos phase of lightweight transactions
Lightweight transaction (LWT)Cassandra conditional write (IF) using Paxos
Sloppy quorumQuorum met by the first N healthy nodes, possibly stand-ins (Dynamo, Riak)
Strict quorumOnly home replicas count (Riak pr/pw > 0)
Hinted handoffA stand-in stores a write for an unreachable replica and delivers it later
Read repairA read that sees divergent replicas writes the newest version back
Anti-entropyBackground replica comparison (Merkle trees) that guarantees convergence
Last write wins (LWW)Conflict rule keeping the version with the highest timestamp; discards the others
Vector clockPer-node counters that detect concurrent versions (Dynamo, Riak)
Write concernMongoDB acknowledgement requirement: w, j, wtimeout
w:majorityMongoDB write concern requiring a majority of voting members
wtimeoutTime limit for a write concern; the write is not undone when it expires
Read concernMongoDB read guarantee: local, available, majority, linearizable, snapshot
Read preferenceMongoDB member selection: primary, secondary, nearest, …
maxTimeMSServer-side time limit for an operation
synchronous_commitPostgreSQL per-transaction commit wait: remote_apply, on, remote_write, local, off
synchronous_standby_namesPostgreSQL list of synchronous standbys, FIRST n or ANY n
remote_applyCommit waits until the standby has applied the change (visible to queries)
acks=allKafka producer waits for all in-sync replicas
ISRKafka in-sync replicas: replicas caught up with the leader
min.insync.replicasKafka minimum ISR size for acks=all writes to succeed
Unclean leader electionKafka electing a non-ISR replica; availability over consistency
Split brainTwo nodes acting as leader at the same time
FencingRejecting operations from an outdated leader using a monotonic token
TrueTimeGoogle's clock API returning an interval with bounded uncertainty
Commit waitSpanner waiting out clock uncertainty before acknowledging
External consistencySpanner's guarantee: transactions appear in real-time commit order
Effectively CACP system whose partitions are rare enough that users assume availability
MREC / MRSCDynamoDB global tables: multi-Region eventual vs strong consistency
WitnessA voting member that stores no readable data (DynamoDB MRSC)
ConsistentReadDynamoDB parameter for strongly consistent reads
HarvestFraction of the data reflected in a response
YieldProbability of completing a request
BASEBasically Available, Soft state, Eventual consistency (Brewer 2000)
Eventual consistencyReplicas converge if updates stop; no bound on when
Read-your-writesA session sees its own writes
Sticky (Laravel)After a write in a request, reads in that request use the write connection
PreventStaleDatabaseReadsLaravel middleware routing a session's reads to the write connection for a window after a write
Delay-sensitivityKleppmann's alternative to CAP: how operation latency depends on network delay
ABD registerAttiya, Bar-Noy, Dolev quorum algorithm for a linearizable register (the Go CP config)
DynamoAmazon's 2007 key-value store paper: quorums, sloppy quorum, hinted handoff
RiakDynamo-style key-value store with n_val, r, w, pr, pw
PNUTSYahoo's store with per-record masters; Abadi's PC/EL example

References ​

Built by Morteza Negahi