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 for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a partition forces a choice at all | Why it exists |
| Fox and Brewer 1999, Brewer 2000, Gilbert and Lynch 2002, Abadi 2012, Kleppmann 2015 | Where it comes from |
| The exact statement and its three definitions | CAP, Linearizability, Availability, Partition |
| "CA systems" and "pick two" | What CAP does not say |
| What to do while partitioned and after | Partition mode, Compensation |
| Which products refuse and which diverge | CP in products, AP in products, Split brain and fencing |
| The latency half of the trade-off | PACELC |
| R + W > N, Cassandra levels, sloppy quorums | Quorums, Cassandra levels, Sloppy quorums |
| Product knobs one by one | etcd/ZooKeeper/Consul, MongoDB, PostgreSQL, Kafka, Spanner/CockroachDB, DynamoDB |
| Partial answers instead of errors | Harvest and yield |
| Money vs likes | Deciding per data item, Eventual-consistency UX |
| Formulas, knobs, error messages | Mechanics |
| Code | Go, Laravel |
| Classic incidents and fixes | Solving the classic problems |
| Which setting when | Choosing |
| From one process to many regions | In architecture |
| Run it yourself | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The theorem, with its real definitions (Gilbert and Lynch 2002).
| Letter | Means in the proof | Does 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 one | The 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 result | During 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).
| Product | During a partition, by default | Knob |
|---|---|---|
| etcd | Majority side serves; minority returns etcdserver: request timed out / no leader (CP) | --consistency=s (serializable) reads answer on the minority, possibly stale |
| ZooKeeper | Writes need a majority (CP); reads are served by the connected server, not linearizable | sync() before a read; read-only mode lets the minority serve reads |
| Consul | HTTP API default mode needs the leader; DNS uses stale mode | ?consistent (extra quorum round trip) or ?stale |
| Cassandra | Depends on the consistency level per request: ONE answers (AP), QUORUM may fail with UnavailableException (CP-like) | ONE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL, SERIAL |
| DynamoDB | Eventually consistent reads (default); global tables MREC replicate asynchronously, last writer wins | ConsistentRead=true; MRSC global tables (three Regions) |
| MongoDB | Primary on the majority side; { w: "majority" } is the usual default; minority has no primary | write concern w, wtimeout; read concern local/majority/linearizable; read preference |
| PostgreSQL | Asynchronous streaming replication by default: primary keeps committing, standbys lag | synchronous_standby_names + synchronous_commit (remote_apply, on, remote_write, local, off) |
| Kafka | acks=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, CockroachDB | Paxos/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).
| Class | During a partition | Else (normal operation) | Examples from the paper and docs |
|---|---|---|---|
| PA/EL | Stay available | Low latency over consistency | Dynamo, Cassandra and Riak defaults; DynamoDB eventually consistent reads |
| PC/EC | Stay consistent | Consistency over latency | VoltDB/H-Store, Megastore, BigTable, HBase; Spanner, CockroachDB, etcd (by their docs) |
| PA/EC | Stay available (old primary's writes roll back later) | Consistent reads and writes | MongoDB, as classified by Abadi in 2012 |
| PC/EL | No extra loss of consistency, availability drops | Latency over consistency | Yahoo PNUTS |
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 out | Every live replica answers |
| Every answer is linearizable | Answers may be stale; concurrent writes conflict |
| Invariants (balance ≥ 0, unique username) hold automatically | Invariants must be restored after the partition (compensation) |
| Needs a majority, a leader or a lease | Needs 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 names | Good 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
- "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."
- "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.
- "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
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.
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.
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 okReal 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.
| Product | Linearizable path | Not linearizable by default |
|---|---|---|
| etcd | Every operation except watch ("etcd ensures linearizability for all other operations by default") | --consistency=s reads; watches |
| ZooKeeper | Writes; reads preceded by sync() | Plain reads (served by the connected server) |
| MongoDB | readConcern: "linearizable" on the primary, single document, plus w: "majority" writes | local, majority (majority-committed but may be behind) |
| Cassandra | Lightweight transactions (IF conditions) with SERIAL / LOCAL_SERIAL | Quorum reads and writes (Kleppmann: sloppy quorums and read repair edge cases) |
| Spanner | Every read-write transaction and strong read (external consistency) | Stale reads with a timestamp bound |
| PostgreSQL | Reads on the primary | Reads 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.
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 riskReal 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.
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 viewReal 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).
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.
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 requestReal 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 / pattern | Partition mode feature |
|---|---|
| Riak, Cassandra | Accept writes on both sides; record versions (vector clocks in Riak, timestamps in Cassandra) |
| DynamoDB global tables MREC | Each Region keeps accepting writes; "last writer wins" on reconciliation |
| CouchDB-style sync, offline apps | Local writes with revision history; conflicts exposed after sync |
| Payment terminals, ATMs | Floor limit / stand-in limit, local log, batch upload |
| Sagas | Compensating 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.
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.
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 staleReal 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.
| Product | Quorum rule | Minority-side behaviour | Error you see |
|---|---|---|---|
| etcd | Raft majority | Writes and linearizable reads fail | etcdserver: request timed out, etcdserver: no leader |
| ZooKeeper | Majority (ZAB) for writes | Writes fail; reads still served from the local server | connection loss / session expiry in client |
| Consul | Raft majority | default and consistent reads fail; stale works | HTTP 500 "No cluster leader" (typical) |
| MongoDB | Majority elects a primary | No primary; writes fail; primaryPreferred/secondary reads work | NotWritablePrimary (10107), PrimarySteppedDown (189) |
| Kafka | ISR, min.insync.replicas | Writes with acks=all rejected when ISR too small | NOT_ENOUGH_REPLICAS (19) |
| CockroachDB | Raft majority per range | Ranges without majority unavailable | statement hangs, then retry/timeout errors |
| Spanner | Paxos majority per split | Splits without majority unavailable | UNAVAILABLE / deadline exceeded (typical gRPC) |
| PostgreSQL sync rep | Named synchronous standbys | Commits wait for the standby, possibly forever | canceling 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).
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 goneReal 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").
| Product | AP setting | Convergence mechanism | Conflict rule |
|---|---|---|---|
| Dynamo (paper) | Sloppy quorum, (3,2,2) common, W=1 for highest availability | Hinted handoff, Merkle-tree anti-entropy | Vector clocks; client merges siblings |
| Cassandra | ONE, LOCAL_ONE, ANY | Hints, read repair, nodetool repair (Merkle trees) | Last write wins per column by timestamp |
| Riak KV | r, w below quorum; sloppy quorum by default (PR = PW = 0) | Hinted handoff, read repair, active anti-entropy | Vector clocks / siblings or LWW |
| DynamoDB | Eventually consistent reads; MREC global tables | Internal replication "typically within a second or less" | "last writer wins" across Regions |
| Consul | ?stale reads and DNS | Raft log catch-up | n/a (reads only) |
| ZooKeeper | Read-only mode (since 3.4.0) on the minority | Rejoin the quorum | n/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.
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 6Real 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".
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 downReal 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).
| Class | Abadi'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, HBase | Pay 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).
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 minorityReal 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:
| Level | Responses required | Typical use |
|---|---|---|
ONE | "Only a single replica must respond." | Fast reads/writes of mergeable data |
TWO, THREE | Two / three replicas | Rare; extra durability without majority |
QUORUM | "A majority (n/2 + 1) of the replicas must respond" across all datacenters | Single-region strong-ish reads and writes |
LOCAL_QUORUM | Majority of the replicas in the coordinator's datacenter | Multi-region services: "reads are guaranteed to see the latest write from within the same datacenter" |
EACH_QUORUM | Majority in each datacenter | Writes that must be in every region before acknowledging |
ALL | Every replica | Almost never; one replica down fails the request |
LOCAL_ONE | One replica, never in a remote datacenter | Lowest latency local reads |
ANY | One replica "or the coordinator may store a hint"; writes only | Maximum write availability, weakest durability |
SERIAL / LOCAL_SERIAL | Paxos phase of lightweight transactions (IF conditions) | Compare-and-set, uniqueness |
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 downReal 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.
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 repairReal 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").
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| Service | Linearizable read | Fast / available read | Staleness bound |
|---|---|---|---|
| etcd | default (--consistency=l) | --consistency=s, clientv3.WithSerializable() | none stated |
| ZooKeeper | sync() then read | plain 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."
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| Setting | Promise | Partition behaviour |
|---|---|---|
w: 1 | Primary has it | Acknowledged 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 has | Can read data that later rolls back |
readConcern: "majority" | Majority-committed data at the member's majority-commit point | Never rolled back; may be stale |
readConcern: "linearizable" | Reflects all majority writes acknowledged before the read began | Fails (with maxTimeMS) instead of answering stale |
read preference nearest / secondary | Any member | Answers 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.
-- 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; 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 abortReal 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".
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."
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 consistencyReal 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.
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 -> retryReal 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.
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 fineReal 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.
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 item | Partition choice | Else choice | Knob examples | Why |
|---|---|---|---|---|
| Wallet balance, ledger | PC | EC | PG remote_apply, Mongo w: "majority" + linearizable, Spanner | Wrong answer = lost money |
| Stock, seats, tickets | PC (or bounded AP with a reservation limit) | EC | Cassandra LWT SERIAL, SQL FOR UPDATE | Overselling is visible and expensive |
| Username / email uniqueness | PC | EC | Unique index on the primary, etcd txn | Duplicates need human compensation |
| Locks, leader, config | PC | EC | etcd linearizable, ZooKeeper sync() | Two leaders corrupt everything |
| Profile, settings | PA with read-your-writes | EL | Laravel sticky, PreventStaleDatabaseReads, LOCAL_QUORUM | Author must see their own edit |
| Shopping cart | PA | EL | Dynamo/Cassandra sets, CRDT | Losing an add-to-cart loses revenue |
| Likes, views, counters | PA | EL | ONE, PG synchronous_commit = off, sharded counters | Approximate is fine |
| Feeds, recommendations | PA (harvest < 100%) | EL | Replica reads, cache | Freshness 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.
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
| Quantity | Formula | N=3 | N=5 |
|---|---|---|---|
| Majority | ⌊N/2⌋ + 1 | 2 | 3 |
| Overlap condition | R + W > N | 2 + 2 | 3 + 3 |
| Failures a majority operation survives | N − majority = ⌊(N−1)/2⌋ | 1 | 2 |
| Write-write overlap (no two conflicting writes both succeed) | W > N/2 | W ≥ 2 | W ≥ 3 |
| Latency of an operation needing k acks | k-th fastest replica RTT | 2nd fastest | 3rd fastest |
| CockroachDB failures tolerated | (RF − 1)/2 | 1 | 2 |
| Riak defaults | n_val 3, PR = PW = 0 (sloppy) |
The knobs, product by product
| Product | Knob | Values (default first or marked) | Effect on CAP/PACELC |
|---|---|---|---|
| Cassandra | consistency level per statement | ONE, TWO, THREE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL, LOCAL_ONE, ANY | Moves each request between PA/EL and PC/EC |
| Cassandra | serial consistency | SERIAL, LOCAL_SERIAL | Paxos phase of LWT (linearizable CAS) |
| DynamoDB | ConsistentRead | false (default), true | Strong reads cost double, tables and LSIs only |
| DynamoDB global tables | consistency mode | MREC (default), MRSC | MRSC: three Regions, RPO 0, higher latency |
| MongoDB | write concern | w: "majority" (implicit default in most deployments), w: 1, w: n, j, wtimeout | Majority = no rollback of acknowledged writes |
| MongoDB | read concern | local (default), available, majority, linearizable, snapshot | linearizable refuses rather than goes stale |
| MongoDB | read preference | primary (default), primaryPreferred, secondary, secondaryPreferred, nearest, maxStalenessSeconds (≥ 90) | Secondary reads answer during partitions, stale |
| PostgreSQL | synchronous_commit | on (default), remote_apply, remote_write, local, off | Per transaction; needs synchronous_standby_names for remote levels |
| PostgreSQL | synchronous_standby_names | empty (async, default), FIRST n (...), ANY n (...) | Commits wait for standbys: CP for writes |
| Kafka | producer acks | all (default), 1, 0 | Durability of the acknowledgement |
| Kafka | min.insync.replicas | 1 (default) | ≥ 2 makes acks=all refuse when the ISR is too small |
| Kafka | unclean.leader.election.enable | false (default) | true = availability over consistency |
| etcd | read consistency | linearizable (default), serializable (--consistency=s, WithSerializable()) | Serializable answers on the minority |
| ZooKeeper | sync(), read-only mode | off by default | sync() = linearizable read; read-only = AP reads |
| Consul | read mode | default (HTTP), stale (DNS default), consistent | stale works without a leader |
| Riak KV | n_val, r, w, pr, pw, dw | n_val 3, pr/pw 0 | pr/pw > 0 = strict quorum |
| CockroachDB | replication factor, cockroach start --max-offset | RF 3; --max-offset "Default: 500ms" | Failures tolerated = (RF − 1)/2; "If observed clock offsets exceed this limit, servers will crash" |
| Laravel | sticky, PreventStaleDatabaseReads, usingWritePdo | off unless configured | Read-your-writes on replicated MySQL/PostgreSQL |
Error messages you will actually see
| Product | Message or code (verbatim) | Meaning |
|---|---|---|
| Cassandra | Cannot achieve consistency level QUORUM. Required 2 but only 1 alive. (UnavailableException) | Coordinator knows too few replicas are up: refused before trying |
| Cassandra | Operation timed out - received only 1 responses. (read/write timeout) | Replicas were thought alive but did not answer in time; write may have partially applied |
| Kafka | NOT_ENOUGH_REPLICAS (19): "Messages are rejected since there are fewer in-sync replicas than required." | ISR below min.insync.replicas |
| Kafka | NOT_ENOUGH_REPLICAS_AFTER_APPEND (20): "Messages are written to the log, but to fewer in-sync replicas than required." | Outcome uncertain; retry with idempotence |
| Kafka | NOT_LEADER_OR_FOLLOWER (6) | Leadership moved; client refreshes metadata |
| etcd | etcdserver: no leader, etcdserver: request timed out (gRPC Unavailable) | Member lost the quorum or the leader |
| MongoDB | WriteConcernTimeout (64, write concern error) | Majority not reached within wtimeout; write NOT undone on the primary |
| MongoDB | MaxTimeMSExpired (50) | Linearizable read could not confirm a majority in time |
| MongoDB | NotWritablePrimary (10107), PrimarySteppedDown (189) | Write sent to a member that is not (or no longer) primary |
| PostgreSQL | 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. | Sync rep wait cancelled; the commit stands |
| DynamoDB | ReplicatedWriteConflictException | MRSC: 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.
// 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
}
}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.
// 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:
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.
// 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
}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):
// 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
}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:
// 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 client | Knob | Note |
|---|---|---|
go.etcd.io/etcd/client/v3 | clientv3.WithSerializable() on Get | Default is linearizable; serializable is member-local |
go.mongodb.org/mongo-driver/v2 | writeconcern.Majority(), readconcern.Majority(), readconcern.Linearizable() | Set on client, database or collection options |
github.com/gocql/gocql | gocql.One, gocql.Quorum, gocql.LocalQuorum, gocql.EachQuorum; Query.SerialConsistency | Per query or per session |
github.com/aws/aws-sdk-go-v2/service/dynamodb | GetItemInput.ConsistentRead *bool | aws.Bool(true) for strong reads |
github.com/jackc/pgx/v5 | SET LOCAL synchronous_commit TO ... inside tx | Per transaction choice of durability and visibility |
github.com/twmb/franz-go/pkg/kgo | kgo.RequiredAcks(kgo.AllISRAcks()) | Topic still needs min.insync.replicas=2 |
context.WithTimeout | Every quorum call | The timeout is your partition detector; pick it per operation |
errors.Is(err, register.ErrUnavailable) | Map to HTTP 503 + Retry-After | Refusing 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
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
// 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
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
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
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
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
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
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
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
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
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 feature | Use for consistency | Note (Laravel 13 docs) |
|---|---|---|
read / write hosts | Route reads to replicas | "When multiple values exist in the host configuration array, a database host will be randomly chosen for each request" |
'sticky' => true | Read-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 primary | Job progress, audit timestamps |
PreventStaleDatabaseReads middleware | Read-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 callback | Restores the previous read preference even on exceptions |
DB::transaction(fn, attempts) + DB::statement('SET LOCAL ...') | Per-transaction synchronous_commit | SET LOCAL lasts until COMMIT/ROLLBACK |
lockForUpdate() | Check-then-act on the primary | Linearizable for that row on one primary |
insertOrIgnore() | Idempotent AP writes | Unique key does the dedup |
laravel-mongodb options | w, wTimeoutMS, journal, readConcernLevel, readPreference, maxStalenessSeconds | URI options of the MongoDB PHP library |
getDatabase()->selectCollection($name, [...]) | Per-collection writeConcern / readConcern | MongoDB\Driver\WriteConcern, ReadConcern::LINEARIZABLE |
Solving the classic problems
Overdraft during a partition
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| CP on the balance | Majority / sync-rep commit, row lock | Invariant always holds | Minority side cannot withdraw |
| Bounded partition mode | Stand-in limit per site (ATM), log, reconcile | Available with known worst case | Needs compensation (fees, collections) |
| Escrow / split budget | Pre-allocate part of the balance to each site | Each site decides locally without risk | Unused budget is locked; rebalancing needed |
| Reservation then capture | Reserve on the CP side, capture later | Clear user state | Two steps, timeouts |
The author does not see their own write
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Request-level stickiness | Laravel sticky | One line | Only within the request |
| Session window | PreventStaleDatabaseReads::for(n), Facebook-style 20 s | Covers redirects | Extra primary load after writes |
| Causal token | MongoDB causally consistent sessions; CockroachDB causality token | Exact | Client must carry the token |
| Visibility before ack | PG remote_apply, Cassandra LOCAL_QUORUM both ways | Any replica is fine afterwards | Higher write latency |
Two leaders after a network blip (split brain)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Majority writes | w: "majority", acks=all + min.insync.replicas=2, Raft | Old leader cannot acknowledge | Needs 3 failure domains |
| Fencing tokens | Storage rejects lower epochs | Protects external side effects | Every resource must check the token |
| Leases with margin | Lease shorter than failure detection; clock bounds | Simple | Depends on bounded clock drift |
| Witness / odd voters | DynamoDB MRSC witness, third-zone voter | Breaks ties | Extra infrastructure |
QUORUM across regions is too slow
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
LOCAL_QUORUM both ways | Users homed per region | Local latency, read-your-writes per region | Cross-region readers may be stale |
| Home region per record | Writes go to the record's region (PNUTS-style) | Fast for the home region | Remote writers pay RTT |
| Consensus group placement | CockroachDB REGIONAL BY ROW, Spanner leader region | CP with local latency for most | Survives region loss only with 3+ regions |
EACH_QUORUM only where required | Fraud flags, entitlements | Strong across regions where it matters | Highest write latency |
Writes hang after a standby died (PostgreSQL)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Quorum of candidates | ANY 1 (a, b) or FIRST 1 (a, b) | One standby may die | Need two standbys |
| Monitoring | Alert on pg_stat_replication.sync_state | Early warning | Operational work |
| Explicit degrade procedure | Runbook to change synchronous_standby_names and reload | Restores availability | Window where commits are not replicated (choose A consciously) |
| Per-transaction levels | synchronous_commit local/off for non-critical writes | Only critical writes wait | Code discipline |
Acknowledged writes vanish after the partition heals
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Avoid LWW on read-modify-write data | Use CP path or LWT for those fields | No silent loss | Latency, availability |
| Mergeable types | Cassandra sets/maps/counters, CRDTs | Both sides' intent survives | Not every invariant is mergeable |
| Siblings | Riak/Dynamo vector clocks, app merge | Nothing silently dropped | App must merge |
| Detect and compensate | Log discarded versions (the Go HealReport.Discarded) | Business can repair | Needs a compensation process |
Producer gets NotEnoughReplicas (Kafka)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Retry with idempotence | enable.idempotence=true, bounded delivery.timeout.ms | No duplicates | Producer blocks while ISR is small |
| Buffer locally (outbox) | Keep events in the database outbox until accepted | No loss, service stays up | Delay (Transactional Outbox) |
Lower min.insync.replicas temporarily | Operator decision | Availability | Durability risk: choose A explicitly |
Choosing
By data item
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Ledger, balance, payments | PC/EC: sync commit (remote_apply or on), w: "majority", Spanner/CockroachDB | Idempotency keys, CHECK constraints, 503 + Retry-After | One wrong answer costs more than refusing |
| Inventory with flash sales | PC/EC with a bounded AP reservation pool per region | Escrow, compensation (backorder email) | Balance availability and overselling risk |
| Unique names, locks, leader election | PC/EC: etcd/ZooKeeper linearizable, SQL unique index, LWT SERIAL | Fencing tokens | Duplicates are unrecoverable without humans |
| User profile, settings | PA/EL with read-your-writes | Sticky, session window, LOCAL_QUORUM | Only the author notices staleness |
| Carts, wish lists | PA/EL | Sets, CRDTs, idempotent adds | Always-writeable beats strict order |
| Counters, likes, views | PA/EL | Sharded counters, ONE, synchronous_commit = off | Approximate is acceptable |
| Feeds, search, recommendations | PA/EL with harvest < 100% | Partial results, deadlines | Yield matters more than completeness |
| Configuration and feature flags | PC/EC writes, AP cached reads with TTL | Watches, versioned config | Writes rare, reads everywhere |
| Global sessions | PA/EL (DynamoDB MREC, Cassandra LOCAL_QUORUM) | TTL, idempotent updates | Losing an edit is acceptable |
| Cross-region strong data | PC/EC (Spanner, CockroachDB, DynamoDB MRSC) | Place majority near writers | Pay RTT on writes, RPO 0 |
By product question
| You need | Choose | Avoid |
|---|---|---|
| Strong reads on a coordination store | etcd default reads, ZooKeeper sync() + read, Consul ?consistent | Stale/serializable reads for lock decisions |
| Strong single-document reads in MongoDB | w: "majority" + readConcern: "linearizable" + maxTimeMS | w: 1 with secondary reads |
| Read-your-writes on SQL replicas | Laravel sticky + PreventStaleDatabaseReads, or PG remote_apply | Random replica reads right after writes |
| No acknowledged-write loss in Kafka | RF 3, min.insync.replicas=2, acks=all, unclean election off | acks=1 for business events |
| Low latency multi-region Cassandra | LOCAL_QUORUM / LOCAL_ONE | QUORUM on hot paths |
| Never-diverging multi-region key-value | DynamoDB MRSC | MREC 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:
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 userEach 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
| Scale | Shape | CAP/PACELC decision |
|---|---|---|
| 1x | One primary, sync standby in another zone | C over A for writes if the standby is required; quorum of standbys to keep A |
| 10x | Primary + read replicas, cache, queue | Per-item reads: primary for authors and money, replicas for the rest (sticky, session window) |
| 100x | Sharded or multi-region; Cassandra/DynamoDB for high-volume items, Spanner/CockroachDB or sharded SQL for money | Per-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.
# 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# 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-- 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)# 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)// 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# 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 confirmsCommon misconceptions
| Belief | Reality |
|---|---|
| Pick any two of C, A and P | P 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 consistency | CAP C is linearizability of single operations; ACID C is constraint preservation |
| Serializable means linearizable | Serializability orders transactions, not necessarily in real time; PostgreSQL SSI is not linearizable |
| CAP availability is uptime | It is "every request received by a non-failing node" answered; single-leader systems fail it |
| Databases are CP or AP | Most configurations are neither; classify operations and settings (Kleppmann) |
| R + W > N gives linearizability | It gives overlap; sloppy quorums, LWW and concurrent writes still break linearizability |
| Eventual consistency happens because of partitions | Usually it is chosen for latency on normal days: the EL of PACELC |
acks=all waits for all replicas | It waits for the current ISR, which can be the leader alone unless min.insync.replicas ≥ 2 |
| Synchronous replication makes standbys up to date for reads | Only remote_apply waits for visibility; on waits for flush |
| Cancelling a hung synchronous commit rolls it back | It "has already committed locally" |
w: "majority" makes every read correct | Reads also need majority or linearizable read concern, and the right member |
| ZooKeeper reads are linearizable because it is CP | Plain reads come from the connected server; use sync() |
| Last-write-wins resolves conflicts | It discards one of them; compensation or merge is still your job |
| Partitions are clean, symmetric splits | They are often partial, one-sided and short; detection is per node, by timeout |
Cheat sheet
| Topic | Remember |
|---|---|
| CAP | During a partition, an operation needing both sides is either linearizable or always answered, not both |
| Definitions | C = linearizable; A = every non-failing node responds; P = arbitrary message loss |
| Partition | "a time bound on communication"; detected by timeouts, per node |
| CA | Not a choice; a probability claim ("effectively CA") |
| Partition lifecycle | Detect → partition mode (limit or log) → recovery (merge + compensate) |
| PACELC | P: A or C; Else: L or C. PA/EL, PC/EC, PA/EC (MongoDB), PC/EL (PNUTS) |
| Quorum | Majority = ⌊N/2⌋+1; R + W > N overlaps; survives N − k failures |
| Cassandra | LOCAL_QUORUM in multi-region; QUORUM crosses regions; SERIAL for CAS |
| Sloppy quorum | Stand-ins accept writes with hints; overlap not guaranteed; Riak pr/pw > 0 = strict |
| etcd / ZK / Consul | Linearizable default / sync() / ?consistent; fast reads: --consistency=s / plain / ?stale |
| MongoDB | w: "majority" + wtimeout; linearizable + maxTimeMS on the primary, one document |
| PostgreSQL | ANY 1 (a, b); synchronous_commit per transaction: remote_apply > on > remote_write > local > off |
| Kafka | RF 3, min.insync.replicas=2, acks=all, unclean election off |
| DynamoDB | ConsistentRead=true costs 2x; MREC LWW vs MRSC three Regions |
| Harvest/yield | Partial answers keep yield; mark them |
| Per item | Money/locks/uniqueness CP; carts/likes/feeds AP; profiles AP + read-your-writes |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| CAP theorem | During 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 |
| Linearizability | One total order of operations consistent with real time; each takes effect at an instant between call and return |
| Linearizable read | A 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 tolerance | Correct behaviour when arbitrarily many messages between nodes are lost |
| Network partition | Some nodes cannot exchange messages in time; detected by timeouts, may be partial or one-sided |
| CP | An operation/configuration that refuses on the side without a quorum to stay consistent |
| AP | An operation/configuration that answers on every side and reconciles later |
| CA myth | The idea that a distributed system can opt out of partitions; at best "effectively CA" |
| Partition mode | An explicit mode entered on detecting a partition: limit risky operations, log everything |
| Partition recovery | Merging state after the partition and compensating for violated invariants |
| Compensation | A business action that restores an invariant or corrects an externalised mistake |
| Invariant | A rule the data must satisfy, such as balance ≥ 0 or unique usernames |
| Stand-in mode | Brewer's ATM partition mode: offline withdrawals up to a limit |
| PACELC | If Partition: A or C; Else: Latency or Consistency (Abadi 2012) |
| PA/EL, PC/EC, PA/EC, PC/EL | The four PACELC classes |
| Latency (in PACELC) | The time consistency costs on a normal day: waiting for remote replicas |
| Tunable consistency | Choosing consistency per request (Cassandra levels, DynamoDB ConsistentRead, Mongo concerns) |
| Quorum | A set of replicas whose acknowledgement is required; majority quorums intersect |
| Majority | ⌊N/2⌋ + 1 replicas |
| R + W > N | Read and write quorum sizes whose sets always overlap |
| N, R, W | Replication factor, read quorum, write quorum (Dynamo) |
| ONE, TWO, THREE | Cassandra levels needing that many replica responses |
| QUORUM | Cassandra: majority of all replicas across datacenters |
| LOCAL_QUORUM | Cassandra: majority in the coordinator's datacenter |
| EACH_QUORUM | Cassandra: majority in every datacenter |
| ALL | Cassandra: every replica |
| LOCAL_ONE | Cassandra: one replica in the local datacenter |
| ANY | Cassandra write level that accepts a stored hint |
| SERIAL / LOCAL_SERIAL | Cassandra serial consistency for the Paxos phase of lightweight transactions |
| Lightweight transaction (LWT) | Cassandra conditional write (IF) using Paxos |
| Sloppy quorum | Quorum met by the first N healthy nodes, possibly stand-ins (Dynamo, Riak) |
| Strict quorum | Only home replicas count (Riak pr/pw > 0) |
| Hinted handoff | A stand-in stores a write for an unreachable replica and delivers it later |
| Read repair | A read that sees divergent replicas writes the newest version back |
| Anti-entropy | Background replica comparison (Merkle trees) that guarantees convergence |
| Last write wins (LWW) | Conflict rule keeping the version with the highest timestamp; discards the others |
| Vector clock | Per-node counters that detect concurrent versions (Dynamo, Riak) |
| Write concern | MongoDB acknowledgement requirement: w, j, wtimeout |
| w:majority | MongoDB write concern requiring a majority of voting members |
| wtimeout | Time limit for a write concern; the write is not undone when it expires |
| Read concern | MongoDB read guarantee: local, available, majority, linearizable, snapshot |
| Read preference | MongoDB member selection: primary, secondary, nearest, … |
| maxTimeMS | Server-side time limit for an operation |
| synchronous_commit | PostgreSQL per-transaction commit wait: remote_apply, on, remote_write, local, off |
| synchronous_standby_names | PostgreSQL list of synchronous standbys, FIRST n or ANY n |
| remote_apply | Commit waits until the standby has applied the change (visible to queries) |
| acks=all | Kafka producer waits for all in-sync replicas |
| ISR | Kafka in-sync replicas: replicas caught up with the leader |
| min.insync.replicas | Kafka minimum ISR size for acks=all writes to succeed |
| Unclean leader election | Kafka electing a non-ISR replica; availability over consistency |
| Split brain | Two nodes acting as leader at the same time |
| Fencing | Rejecting operations from an outdated leader using a monotonic token |
| TrueTime | Google's clock API returning an interval with bounded uncertainty |
| Commit wait | Spanner waiting out clock uncertainty before acknowledging |
| External consistency | Spanner's guarantee: transactions appear in real-time commit order |
| Effectively CA | CP system whose partitions are rare enough that users assume availability |
| MREC / MRSC | DynamoDB global tables: multi-Region eventual vs strong consistency |
| Witness | A voting member that stores no readable data (DynamoDB MRSC) |
| ConsistentRead | DynamoDB parameter for strongly consistent reads |
| Harvest | Fraction of the data reflected in a response |
| Yield | Probability of completing a request |
| BASE | Basically Available, Soft state, Eventual consistency (Brewer 2000) |
| Eventual consistency | Replicas converge if updates stop; no bound on when |
| Read-your-writes | A session sees its own writes |
| Sticky (Laravel) | After a write in a request, reads in that request use the write connection |
| PreventStaleDatabaseReads | Laravel middleware routing a session's reads to the write connection for a window after a write |
| Delay-sensitivity | Kleppmann's alternative to CAP: how operation latency depends on network delay |
| ABD register | Attiya, Bar-Noy, Dolev quorum algorithm for a linearizable register (the Go CP config) |
| Dynamo | Amazon's 2007 key-value store paper: quorums, sloppy quorum, hinted handoff |
| Riak | Dynamo-style key-value store with n_val, r, w, pr, pw |
| PNUTS | Yahoo's store with per-record masters; Abadi's PC/EL example |
References
- Seth Gilbert, Nancy Lynch — Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services, SIGACT News 2002 (author copy): https://www.comp.nus.edu.sg/~gilbert/pubs/BrewersConjecture-SigAct.pdf (MIT copy: https://groups.csail.mit.edu/tds/papers/Gilbert/Brewer6.pdf)
- Seth Gilbert, Nancy Lynch — Perspectives on the CAP Theorem, IEEE Computer 2012: https://groups.csail.mit.edu/tds/papers/Gilbert/Brewer2.pdf
- Eric Brewer — Towards Robust Distributed Systems, PODC 2000 keynote slides: https://people.eecs.berkeley.edu/~brewer/cs262b-2004/PODC-keynote.pdf
- Eric Brewer — CAP Twelve Years Later: How the "Rules" Have Changed, IEEE Computer 2012 (InfoQ): https://www.infoq.com/articles/cap-twelve-years-later-how-the-rules-have-changed/
- Eric Brewer — Spanner, TrueTime and the CAP Theorem, 2017: https://research.google/pubs/spanner-truetime-and-the-cap-theorem/ (PDF: https://research.google.com/pubs/archive/45855.pdf)
- Armando Fox, Eric Brewer — Harvest, Yield, and Scalable Tolerant Systems, HotOS 1999: https://s3.amazonaws.com/systemsandpapers/papers/FOX_Brewer_99-Harvest_Yield_and_Scalable_Tolerant_Systems.pdf
- Daniel Abadi — Consistency Tradeoffs in Modern Distributed Database System Design, IEEE Computer 2012: https://www.cs.umd.edu/~abadi/papers/abadi-pacelc.pdf
- Daniel Abadi — Problems with CAP, and Yahoo's little known NoSQL system (2010): https://dbmsmusings.blogspot.com/2010/04/problems-with-cap-and-yahoos-little.html
- Martin Kleppmann — Please stop calling databases CP or AP (2015): https://martin.kleppmann.com/2015/05/11/please-stop-calling-databases-cp-or-ap.html
- Martin Kleppmann — A Critique of the CAP Theorem, arXiv:1509.05393: https://arxiv.org/abs/1509.05393
- DeCandia et al. — Dynamo: Amazon's Highly Available Key-value Store, SOSP 2007: https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf
- Apache Cassandra — Dynamo architecture (tunable consistency, hints, read repair): https://cassandra.apache.org/doc/latest/cassandra/architecture/dynamo.html
- Apache Cassandra — cqlsh (
CONSISTENCY,SERIAL CONSISTENCY): https://cassandra.apache.org/doc/latest/cassandra/managing/tools/cqlsh.html - Apache Cassandra source —
UnavailableException: https://raw.githubusercontent.com/apache/cassandra/trunk/src/java/org/apache/cassandra/exceptions/UnavailableException.java - Apache Cassandra source —
RequestTimeoutException: https://raw.githubusercontent.com/apache/cassandra/trunk/src/java/org/apache/cassandra/exceptions/RequestTimeoutException.java - Amazon DynamoDB — Read consistency: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
- Amazon DynamoDB — Global tables, how it works (MREC, MRSC): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/V2globaltables_HowItWorks.html
- MongoDB — Write concern: https://www.mongodb.com/docs/manual/reference/write-concern/
- MongoDB — Read concern: https://www.mongodb.com/docs/manual/reference/read-concern/
- MongoDB — Read concern "linearizable": https://www.mongodb.com/docs/manual/reference/read-concern-linearizable/
- MongoDB — Error codes (
error_codes.yml): https://raw.githubusercontent.com/mongodb/mongo/master/src/mongo/base/error_codes.yml - etcd — API guarantees: https://etcd.io/docs/v3.5/learning/api_guarantees/
- etcd — API reference (Range serializable): https://etcd.io/docs/v3.5/learning/api/
- etcd — etcdctl README (
--consistency): https://raw.githubusercontent.com/etcd-io/etcd/main/etcdctl/README.md - etcd — gRPC error strings (
rpctypes/error.go): https://raw.githubusercontent.com/etcd-io/etcd/main/api/v3rpc/rpctypes/error.go - ZooKeeper — Programmer's Guide (consistency guarantees,
sync()): https://zookeeper.apache.org/doc/r3.9.4/zookeeperProgrammers.html - HashiCorp Consul — Consistency modes: https://developer.hashicorp.com/consul/api-docs/features/consistency
- PostgreSQL — Write Ahead Log settings (
synchronous_commit): https://www.postgresql.org/docs/current/runtime-config-wal.html - PostgreSQL — Replication settings (
synchronous_standby_names): https://www.postgresql.org/docs/current/runtime-config-replication.html - PostgreSQL — Log-shipping standby servers (synchronous replication): https://www.postgresql.org/docs/current/warm-standby.html
- PostgreSQL source —
syncrep.c(cancel warnings): https://raw.githubusercontent.com/postgres/postgres/master/src/backend/replication/syncrep.c - Apache Kafka — Producer configs (
acks): https://kafka.apache.org/44/configuration/producer-configs/ - Apache Kafka — Topic configs (
min.insync.replicas,unclean.leader.election.enable): https://kafka.apache.org/44/configuration/topic-configs/ - Apache Kafka — Design (replication, ISR, unclean leader election): https://kafka.apache.org/44/design/design/
- Apache Kafka source —
Errors.java: https://raw.githubusercontent.com/apache/kafka/trunk/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java - Google Cloud Spanner — TrueTime and external consistency: https://cloud.google.com/spanner/docs/true-time-external-consistency
- CockroachDB — Replication layer: https://www.cockroachlabs.com/docs/stable/architecture/replication-layer
- Cockroach Labs blog — Living Without Atomic Clocks: https://www.cockroachlabs.com/blog/living-without-atomic-clocks/
- CockroachDB —
cockroach start(--max-offset): https://www.cockroachlabs.com/docs/stable/cockroach-start - CockroachDB — Multi-region overview (
REGIONAL BY ROW): https://www.cockroachlabs.com/docs/stable/multiregion-overview - Apache Cassandra — Hints (
max_hint_window): https://cassandra.apache.org/doc/latest/cassandra/managing/operating/hints.html - Riak KV — Replication properties (
n_val,r,w,pr,pw, sloppy quorum): https://docs.riak.com/riak/kv/latest/developing/app-guide/replication-properties/index.html - Riak KV — Eventual consistency: https://docs.riak.com/riak/kv/latest/learn/concepts/eventual-consistency/index.html
- Laravel 13 — Database (read/write connections, sticky,
PreventStaleDatabaseReads,usingWritePdo): https://laravel.com/docs/13.x/database - Laravel framework source —
PreventStaleDatabaseReads: https://raw.githubusercontent.com/laravel/framework/13.x/src/Illuminate/Foundation/Http/Middleware/PreventStaleDatabaseReads.php - MongoDB Laravel integration — Connection options: https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/fundamentals/connection/connection-options/
- MongoDB Laravel integration source —
Connection.php(getDatabase): https://raw.githubusercontent.com/mongodb/laravel-mongodb/5.x/src/Connection.php - MongoDB PHP library —
MongoDB\Database::selectCollection(): https://www.mongodb.com/docs/php-library/current/reference/method/MongoDBDatabase-selectCollection/ - PHP manual —
MongoDB\Driver\ReadConcern: https://www.php.net/manual/en/class.mongodb-driver-readconcern.php - PHP manual —
MongoDB\Driver\WriteConcern::__construct: https://www.php.net/manual/en/mongodb-driver-writeconcern.construct.php - Go — etcd
clientv3: https://pkg.go.dev/go.etcd.io/etcd/client/v3 - Go — MongoDB driver v2
readconcern: https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo/readconcern - Go — MongoDB driver v2
writeconcern: https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo/writeconcern - Go — gocql: https://pkg.go.dev/github.com/gocql/gocql
- Go — franz-go
kgo: https://pkg.go.dev/github.com/twmb/franz-go/pkg/kgo - Go — AWS SDK for Go v2 DynamoDB: https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb