Skip to content
Tech Interview Prep
Technical interview guide

CAP Theorem & Consistency Models

Why a distributed system can't have perfect consistency, availability, and partition tolerance all at once, and what real systems trade off.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Vendor-neutral distributed-systems principles; current AWS architecture guidance.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-14

Explain why a distributed system cannot distinguish a slow node from a failed one.

Answer

The 90-second answer

A node that has failed and a node that is merely slow produce the same thing at the observer: no reply. The observer has no channel to the node other than messages, so "no message arrived by time t" is one observation with at least five causes: crashed, alive but stalled, request lost, reply lost, or processed-and-ack-lost. Nothing in the observation separates them.

No amount of waiting fixes this, because in an asynchronous network there is no bound on message delay you can rely on. If you knew every message arrived within 500 ms, a 1 s silence would mean failure. You don't know that, and a node in a 3 s GC pause is indistinguishable from a node that is gone. This is the FLP result: in a fully asynchronous system with one crash-faulty process, no deterministic protocol solves consensus. Dwork, Lynch and Novák showed the escape hatch, assume bounds exist but are unknown (partial synchrony), which is why every real system has a timeout somewhere.

The same observation, different worlds

What the client seesWorld AWorld B
no reply within 1 snode crashed before applyingnode applied, then paused 3 s
no reply within 1 srequest dropped in flightreply dropped in flight
no reply within 1 snode partitioned from clientnode alive, partitioned from client only

Every row is the same bytes on the wire.

Worked trace: a write that may or may not have happened

Counter service, client C, nodes N and M. C sends INCR counter by 1 with a 1 s deadline.

  • t=10 ms: N receives, applies, counter 41 → 42.
  • t=15 ms: N enters a 3 s stop-the-world GC pause before writing the reply.
  • t=1000 ms: C's deadline fires. C has no reply. C declares N failed.
  • t=1000 ms: C retries to M. M applies, counter 42 → 43.
  • t=3010 ms: N wakes and sends its reply. C has already given up and discards it.

Final counter 43. One increment was intended. The client cannot tell this from the case where N crashed at t=5 ms and only M's increment landed (counter 42): both look like "no reply in 1 s, then a retry succeeded."

That is the whole problem in one trace: the timeout is a decision, and the decision is sometimes wrong in both directions.

What the numbers look like

  • TCP connect: net.ipv4.tcp_syn_retries defaults to 6, roughly 127 s before connect gives up. That is the kernel's guess, not a fact about the peer.
  • etcd/Raft: --heartbeat-interval=100 ms, --election-timeout=1000 ms. A leader that misses heartbeats for 1 s is replaced; a leader in a 1.2 s pause is replaced too, and may come back still believing it leads.
  • Kubernetes: --node-monitor-period=5s, --node-monitor-grace-period=40s. A node is marked NotReady after 40 s of missed heartbeats; pods get the node.kubernetes.io/unreachable taint with tolerationSeconds: 300 before eviction. Those are chosen thresholds, not measurements.
  • Cassandra's phi accrual detector (phi_convict_threshold, default 8) makes the same trade with a continuous score instead of a fixed timer.

What you do about it

Since you cannot detect failure, you contain being wrong about it:

  • Fencing tokens: every write carries a monotonically increasing token; storage rejects any token lower than the highest seen, so a resurrected node's stale writes are refused.
  • Idempotency keys: the retry in the trace above carries the same key, so M's apply is a no-op if N already applied it.
  • Quorums: a node that cannot reach a majority stops serving, so a partitioned minority cannot act alone.

The design goal is not a better failure detector. It is making a wrong failure decision survivable.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain the CAP theorem and why 'pick two' is misleading.

Answer

The 90-second answer. CAP says a distributed store cannot simultaneously guarantee linearizable consistency (every read sees the most recent acknowledged write), availability (every request to a non-failing node returns a non-error response), and partition tolerance (the system keeps serving while messages between nodes are dropped). Gilbert and Lynch proved it in 2002 under an asynchronous network model.

"Pick two" is misleading because P is not a checkbox. Any system on more than one machine over a real network will see partitions: a misconfigured switch, a cut fibre, an AZ losing its uplinks. A system that "chooses CA" does not dodge partitions; it stops serving when one arrives. That is a failure mode, not a design. So the only real choice is C versus A during a partition, and it is usually made per request, not per system.

Where the choice actually lives. Abadi's PACELC (2012) adds the else branch: if Partition, choose A or C; Else, choose Latency or Consistency. The else branch is where nearly all traffic runs.

System and settingDuring a partitionNormal operation
etcd, 3 nodes (Raft)CP: writes need 2/3; linearizable reads need quorum, serializable reads can be served locally and go staleEC: leader round trip, single-digit ms in-region
Cassandra RF=3, CL=QUORUMAP: write succeeds on 2/3EL: tunable R/W
Cassandra RF=3, CL=ALLCP: any replica down blocks the writeEL
DynamoDB default readsAPEL; strongly consistent reads cost 2x RCU
SpannerCP: Paxos majorityEC: commit-wait burns the TrueTime uncertainty, ~7 ms in the 2012 paper
Kafka acks=all, min.insync.replicas=2CP for producers: fails below 2 in-sync replicasEL
PostgreSQL synchronous_commit=on + synchronous_standby_namesCP: commit blocks if the standby is unreachableEC: commit latency includes the standby's WAL flush RTT

Worked trace: Cassandra, RF=3, CL=QUORUM. Replicas A, B, C hold key k. A partition isolates C. A client writes k=v at CL=QUORUM: the coordinator sends to all three, C times out, A and B ack. QUORUM for RF=3 is floor(3/2)+1 = 2, so the write returns success. C still holds the old value. A read at CL=QUORUM goes to two replicas. If it picks A and C, the digests differ, the coordinator fetches the full row from the replica holding the newer timestamp, returns v, and read-repairs C. If it picks A and B, it returns v directly. Either way the read cannot miss the write, because R + W = 2 + 2 = 4 > 3 = N, so the read set and the write set must intersect. Set CL=ALL and the same write fails while C is unreachable: you bought consistency with availability, per request. Note the ceiling: Cassandra resolves conflicts last-write-wins on client timestamps, so this is not linearizability; two concurrent writers to k can lose one.

CAP's C is not ACID's C. CAP consistency is replica agreement, close to linearizability. ACID consistency is a transaction preserving declared invariants. Shared letter, nothing else.

Failure modes to name. A CP store's minority side rejects writes: watch etcd leader elections and etcdctl endpoint status, Kafka's UnderReplicatedPartitions, Postgres commits stalling on a dead standby. An AP store's risk is silent staleness and lost updates: watch Cassandra dropped mutations and read-repair latency. The question to ask of any system: what does it do during a partition, and was that chosen or inherited from a default?

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain the consistency spectrum from strong to eventual.

Answer

The 90-second answer. Consistency is a spectrum of what a read is allowed to return, and the price of moving up the spectrum is coordination. Linearizability needs a round of agreement per operation; causal consistency needs only dependency metadata; eventual consistency needs nothing on the write path. Most products need the session guarantees in between, read-your-writes and monotonic reads, which cost one routing decision. So: find the weakest model that satisfies the requirement, and be explicit about which operations genuinely need more.

Where the models sit, and what they cost.

ModelGuaranteeMechanismCost
Linearizableread returns the latest committed write, in real-time orderPaxos/Raft quorum per op; Spanner TrueTime + commit-waitSpanner waits out 2ε before commit, ε typically 1–7 ms; cross-region quorum RTT 60–150 ms
Sequentialone total order, not tied to real timesingle leader / logone leader RTT, no clock wait
Causalcausally related ops seen in the same orderdependency tracking (COPS-style, vector clocks)metadata per write, no coordination on the read path
Session (RYW, monotonic reads/writes)per-client orderingsticky routing to one replicaone routing decision
Eventualreplicas converge once writes stopanti-entropy, read repair, hinted handoffno write-path coordination; unbounded staleness window

Worked trace: why R+W>N is not linearizability. Cassandra, RF=3, nodes A, B, C. Write x=1 at CL=ONE lands on A. A read at CL=ONE hits B, which hasn't seen it, and returns the old value. Now set W=2, R=2: the write goes to {A,B}, the read to {B,C}. The sets intersect at B, so the read sees x=1: that is the arithmetic, 2+2>3. But it only holds if the write actually reached both replicas. With hinted handoff and sloppy quorums, a "successful" W=2 write can land on non-replica nodes, and the intersection argument breaks. That gap is the difference between quorum and linearizable. Cassandra's driver default is CL=ONE for both reads and writes; Dynamo's paper uses (N,R,W)=(3,2,2) as its example.

Failure modes, detection, cost.

  • Stale read of a balance. A user sees $100 after depositing $50. Detect by comparing a version or writetime column client-side; Cassandra exposes ReadRepairAttempted and ReadRepairRepairedBlocking metrics, and nodetool tpstats shows repair backlog.
  • Lost update. Two clients read x=5 and both write 6. Detect with a monotonic version check. Fix with Cassandra LWT (UPDATE ... IF x = 5), which is Paxos: roughly four round trips, commonly measured at ~4× the latency of a normal write. Keep it off hot paths.
  • Counter anomaly. A counter goes backwards because a replica applied an older increment. Detect by comparing against a monotonic source; fix with CRDT counters or a single writer per shard.
  • Causal violation. A reply is visible before its parent message. Detect with a client-side "parent not found" check; fix with causal dependency metadata or by pinning a user's session to one replica.

Choosing. Read-modify-write on money or inventory: pay for linearizable, either Spanner or consensus on that key alone. Feeds and profiles: causal plus read-your-writes via sticky sessions. Counters you can recompute and caches: eventual is fine.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

What does it mean for an operation to be linearizable, and when do you need it?

Answer

The 90-second version

Linearizability is a consistency guarantee for a single object: every operation appears to take effect atomically at one instant between its invocation and its response, and the resulting order of all operations is consistent with real time. If client A's write is acknowledged before client B's read starts, B cannot see the old value. Once a write returns, every read that starts afterwards (any client, any replica) sees that write or a later one.

That real-time clause is the whole difference from sequential consistency, which only requires some total order. Under sequential consistency you may order B's read before A's write and be legal; under linearizability you may not, because the write already returned.

Trace: sequentially consistent but not linearizable

Register x, initially 0. Two clients.

real timeclient Aclient B
t1write(x,1) → ack
t2read(x) → 0

A's write completed at t1; B's read started at t2 > t1. The history is sequentially consistent (order it as B's read, then A's write) but not linearizable, because no legal linearization can place B's read after A's write and still return 0. This is exactly the bug you get from reading a follower replica that has not caught up.

modelorder it respectswhat it forbids
linearizableone total order consistent with real timestale read after an acknowledged write
sequentialone total order, real time ignoreddivergent per-client orders
causalonly causally related operations ordereda reply appearing before its cause
eventualnonenothing; only promises convergence

Where you need it: uniqueness constraints (two claims on the same username), locks and leases (two holders means no lock), leader election (split brain), and any read that feeds an irreversible decision: balance before a withdrawal, seat count before a booking.

Where you do not: feeds, analytics, recommendations, search indexes, caches, and counters people already treat as approximate: likes, views, followers.

What it costs

Coordination on the operation. In a Raft cluster a linearizable write needs a majority to durably acknowledge: 3 nodes tolerate 1 failure, 5 tolerate 2, and the write pays one round trip to that quorum plus an fsync on each node. Intra-AZ that is roughly 1–3 ms of added latency; put the quorum across regions (us-east-1 ↔ eu-west-1, on the order of 75–90 ms RTT) and every linearizable write pays that. During a partition the minority side must refuse the operation: that is the availability you trade away.

Named specifics worth knowing:

  • ZooKeeper: writes are linearizable because they go through the leader, but reads served by a follower are not. They can be stale. Calling sync() before a read forces that follower to catch up.
  • etcd: etcdctl defaults to --consistency=linearizable, which routes the read through Raft; --consistency=serializable reads local state and can be stale.
  • Spanner: TrueTime commit-wait, with the OSDI 2012 paper reporting ε typically under 7 ms. You pay that wait on commit to get external consistency.

The framing that matters: linearizability is a property of individual operations, not of a system. Use it for the handful that need it and weaker guarantees elsewhere. And prefer a system that already provides it (a relational database's unique constraint, or etcd/ZooKeeper) over hand-rolling it; the bugs only surface under partition, which is precisely when they matter.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

What is the technical difference between linearizability and sequential consistency in distributed systems?

Answer

The 60-second answer. Both models require every process to agree on one total order of operations, and that order must respect each process's program order. Linearizability (Herlihy & Wing, 1990) adds one more constraint: the total order must also respect real time. If operation A completes before operation B begins, A must come before B. Sequential consistency (Lamport, 1979) drops that constraint: it only requires that some total order exists which respects program order and which every process observes identically.

So linearizability = sequential consistency + real-time recency. Linearizability implies sequential consistency; the converse is false.

The test that separates them. Register x, initially 0:

P1:  W(x,1) ──┐
P2:           └── R(x) -> 0

W(x,1) completes before R(x) starts, and R returns 0.

  • Not linearizable: R began after W completed, so it must return 1 or a later write.
  • Sequentially consistent: yes. Order the operations R(x)->0, W(x,1). Each process has one operation, so program order is trivially satisfied, and every process sees the same order.

Sequential consistency is not a free-for-all. P1: W(x,1); R(x) -> 0 violates it, because P1's own program order puts the write before the read.

Where they differ in practice.

LinearizabilitySequential consistency
OrderingTotal order + real timeTotal order + program order
ComposabilityYes: per-object linearizability composes into a linearizable systemNo: two SC objects can combine into a non-SC system
StalenessA read sees the last write that completed before it started, or laterUnbounded: any value consistent with some total order
Read costQuorum round trip (Raft ReadIndex) or a leader leaseLocal replica read, no coordination

The composability row is the one people get wrong. Two registers x and y, both initially 0:

P1: W(x,1); R(y) -> 0
P2: W(y,1); R(x) -> 0

Each register alone is sequentially consistent: order the read before the write. Together they are not: P1's read forces W(x,1) before W(y,1), P2's read forces W(y,1) before W(x,1). No total order satisfies both. Linearizability has no such gap, which is why it is the right target for a single object.

Systems. etcd serves linearizable reads by default: the leader confirms it still holds quorum via ReadIndex (a heartbeat round trip, no log write) before answering. etcdctl get --consistency=s opts into serializable reads, which a follower answers from local state and which may be stale. ZooKeeper is the sequential-consistency case: reads are served from whichever replica the client is connected to, so they can be arbitrarily stale; the documented guarantee is sequential consistency, and sync() before a read is what forces the client up to the leader's committed state. Spanner targets strict serializability, linearizability plus transaction atomicity, using TrueTime, paying a commit-wait bounded by the uncertainty ε, which the 2012 OSDI paper reports as typically under 7 ms.

Failure modes. A linearizable read on a partitioned leader must fail closed: the leader cannot confirm quorum, so it returns an error or blocks rather than serving a value that might be stale. If it serves anyway you have a split brain: detect it by comparing lease duration against measured clock skew, since a lease longer than the real skew bound lets two leaders answer reads. Sequential consistency fails differently and more quietly: after a partition heals, a client can read a value older than one it already saw, so the symptom is a read-your-writes or monotonic-read violation, not an error. That is the trade: SC buys local reads at the cost of a staleness bound you cannot state.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Explain quorums and how they let you tune consistency.

Answer

What a strong candidate says first. With N replicas per key, a write is acknowledged once W replicas have applied it, and a read waits for R replicas and returns the newest version among the responses. If R + W > N, every read set and every acknowledged write set must intersect, so the read sees at least one copy of the latest acknowledged write. That inequality is the whole tuning knob.

The knob, with N = 3

WRR+W>Nwrite survivesread survives
11no2 of 3 down2 of 3 down
22yes1 of 3 down1 of 3 down
31yes0 down2 of 3 down
13yes2 of 3 down0 down

Dynamo's production default was (N, R, W) = (3, 2, 2): one node down on either side, still consistent. Cassandra exposes the same knob per statement: on RF=3, QUORUM means 2, ALL means 3, LOCAL_QUORUM means 2 within the local datacenter. You set it per query, new SimpleStatement(...).setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM), so a balance check and a dashboard read on the same table can pay different prices.

Worked trace, RF = 3, replicas A, B, C, W = R = 2

  1. Write k=v1. The coordinator sends to A, B, C. A and B ack; C is slow. The write returns success. C still holds v0.
  2. Read k. The coordinator sends to A, B, C and waits for 2. B and C answer first: B has v1, C has v0. Newest wins, so v1 is returned. Read repair pushes v1 to C.
  3. The same read now hitting C and A returns v1 from either.

Now set W = R = 1. Write k=v2 lands only on A. A read that hits C returns v0, and the client has no signal that it is stale. That is the trade, made visible.

Where it breaks

  • Sloppy quorums. Dynamo and Cassandra accept a write on a non-owner when the owner is down, storing a hint. R + W > N can then hold without intersecting the real replica set. nodetool tpstats shows hint delivery; nodetool statushandoff reports whether handoff is enabled. Hints drain when the node returns.
  • Partial writes. A write that never reached W is not rolled back. Some readers see it, some don't, and the inequality says nothing about it.
  • Per key only. Quorum overlap gives you no cross-key invariant. Cassandra's lightweight transactions use Paxos at SERIAL consistency and cost roughly four round trips: that is the price of a compare-and-set.
  • Multi-DC. A global QUORUM spans regions and pays the cross-region RTT. LOCAL_QUORUM with RF=3 per DC keeps it to 2-of-3 locally.

Cost. A quorum write waits for the second-fastest of three replicas, not the slowest. Illustrative, not measured: if a single replica write is 1 ms at p50 and 15 ms at p99, an ALL write's p99 tracks that 15 ms while a QUORUM write's p99 tracks the median of three draws. Lower, and the gap widens as replica latency variance grows. That is the number to put in front of a product owner asking why the write path got slower.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain read repair and anti-entropy in eventually consistent systems.

Answer

Assumptions: RF = 3, CL = QUORUM, Cassandra-style Dynamo lineage. Read repair runs on the read path, anti-entropy runs off it, and hinted handoff is a third mechanism that prevents divergence instead of repairing it.

Read repair. The coordinator sends the read to every replica in the key's replica set, not just the CL-many it needs. Each returns a digest of its value. If the digests disagree, the coordinator fetches full data from the replicas reporting the newest timestamp, merges, writes the winner to the stale replicas, and only then answers the client. Because the repair happens before the response, it is blocking: a divergent read costs an extra round trip.

Trace: key user:42:profile, RF = 3, CL = QUORUM:

stepABCclient
statev2 @ ts 1000v2 @ ts 1000v1 @ ts 900—
1. digest request to all threedigest(v2)digest(v2)digest(v1)waiting
2. digests disagree → full read from newestv2v2—waiting
3. write v2 to the stale replica——v2 @ ts 1000waiting
4. respondv2

C is converged. A read that happens to hit only A and B never triggers any of this.

The gap is structural: a key nobody reads is never repaired. Cold data stays divergent until someone reads it. Usually during an incident, which is the worst moment to discover it.

Anti-entropy. Background comparison, independent of traffic. A naive comparison is O(n) per range; Merkle trees make it O(log n) hashes when the divergence is small. Each replica hashes the rows of a token range into a tree; two replicas exchange root hashes and descend only into subtrees whose hashes differ.

Arithmetic: 1,000,000 rows per range, fanout 128 → depth ⌈log₁₂₈ 1,000,000⌉ = 3, since 128³ = 2,097,152. Isolating one differing row costs at most 3 levels × 128 child hashes = 384 hash comparisons, against 1,000,000 for a row-by-row scan. That ratio is why anti-entropy is affordable at all.

In Cassandra this is nodetool repair, run per node: usually with -pr so each node repairs only its primary ranges and the ring is covered once, and scheduled, weekly being common. It has to finish inside gc_grace_seconds, default 864000 (10 days), or a tombstone can be garbage-collected on one replica while the deleted row still exists on another, and the delete is undone. Cassandra 3.0+ incremental repair (-inc) splits SSTables into repaired and unrepaired sets so later runs compare only unrepaired data.

Hinted handoff. When a replica is down for a write, another node stores a hint in system.hints and replays it when the replica returns. Cassandra caps this at max_hint_window_in_ms, default 10800000 (3 hours); past that, hints stop being written and only anti-entropy can close the gap.

mechanismtriggercostcovers
blocking read repairread finds divergent digests+1 round trip on that readhot keys
probabilistic read repairread_repair_chance (default 0.1 in 2.x/3.x; deprecated in 3.0, removed in 4.0)background writehot keys, older versions
hinted handoffwrite to a down replicahint storage and replayoutages under 3 h
anti-entropyscheduled nodetool repairMerkle build plus SSTable streamingeverything, eventually

Failure modes. Repair that does not finish inside gc_grace_seconds resurrects deleted rows. Anti-entropy run too rarely leaves divergence that only surfaces on read; run too often it saturates disk and network streaming SSTables. Hints expiring past the 3-hour window is silent unless you watch system.hints size. On DynamoDB you have no repair knob at all: the service runs anti-entropy internally, and the closest signal is the ReplicationLatency CloudWatch metric on global tables.

When not to use this. If you need a linearizable read, no amount of repair helps. Use R + W > N with quorum reads, or a consensus system. Read repair and anti-entropy buy convergence, not consistency.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What causes disappearing updates across replica reads, and what architectural mechanisms guarantee read-your-writes and monotonic reads?

Answer

A disappearing update occurs when an application serves writes and reads across asynchronous replicas without pinning session state. In an asynchronous primary-replica topology, writes commit to the primary and stream to replicas via WAL or binlog shipping. If a user writes an update to the primary and their subsequent read request hits a replica lagging by even 50 ms, the user observes stale data. If a third read hits an up-to-date replica or the primary, the update reappears; if the fourth read hits a lagging replica again, it disappears once more. This violates two specific session guarantees:

  1. Read-Your-Writes Consistency: A process that writes a value always observes that value on subsequent reads.
  2. Monotonic Read Consistency: If a process reads value $V_1$ at logical time $T_1$, it never subsequently observes an older value $V_0$ at $T_2 > T_1$.

Trace of a Disappearing Update

Client               Primary               Replica A (lag: 0ms)   Replica B (lag: 200ms)
  |                     |                           |                      |
  |-- 1. POST /status ->|                           |                      |
  |      (writes v2)    |-- WAL repl (v2) --------->|                      |
  |<- 2. 200 OK --------|                           |                      |
  |-- 3. GET /status ------------------------------>|                      | (observes v2)
  |<- 4. Returns v2 ----|                           |                      |
  |-- 5. GET /status ----------------------------------------------------->| (observes v1!)
  |<- 6. Returns v1 ----|                           |                      | Update "disappeared"

Architectural Mechanisms to Prevent It

MechanismImplementation DetailTrade-off / Cost
Pinned Session / User-Primary RoutingRoute user's reads to the primary for $N$ seconds after a write (e.g., set a cookie/header last_write_at). All other reads hit replicas.Concentrates read traffic onto the primary briefly after write bursts; simple to implement in API gateways or load balancers.
Replica Log Sequence Number (LSN) GatingOn write response, primary returns the committed LSN/timestamp. The client presents this token on subsequent reads (after_lsn). The replica holds or rejects the read until pg_last_wal_replay_lsn() $\ge$ after_lsn.Zero primary read load for stale reads, but replica read tail latency spikes during heavy replication lag.
Strong Read Pinning on Own ResourcesEnforce strongly consistent reads only when a user accesses their own mutable records (e.g., DynamoDB ConsistentRead=true or MongoDB readConcern: "linearizable"); use eventual reads for shared public feeds.Doubles read request cost in DynamoDB (1 RCU per 4 KB instead of 0.5 RCU) and increases read latency by forcing read quorum or primary validation.
Session Affinity (Sticky Routing)Direct all traffic for a specific user_id to a designated replica pool or persistent connection.Provides monotonic reads, but does not guarantee read-your-writes if that replica lags behind the primary. Imbalances worker loads during hot-key traffic.

Failure Modes & Edge Cases

  • Client Retries & Connection Pools: If an application pools database connections across replicas dynamically without transaction affinity, consecutive statements within the same web request can hit different replicas, reading stale snapshots between steps.
  • Primary Failover / Unreplicated Transactions: If asynchronous replication is used and the primary dies before WAL reaches replicas, a committed write can be dropped permanently on failover. Read-your-writes is broken globally because the write never existed on the promoted standby.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

What is read-your-writes consistency, and how can it be implemented in an eventually consistent distributed store?

Answer

Read-your-writes (RYW) consistency guarantees that once a client successfully updates a record, any subsequent read by that same client will observe that update or a later one. It does not promise that other clients immediately see the change; it bounds staleness strictly for the author to prevent confusing feedback loops like a user submitting a comment, refreshing, and seeing it vanish.

In an eventually consistent store, there are four primary ways to implement it:

1. Primary pinning / Write-time windowing

Route any read for an entity that the client modified within the replication lag window directly to the primary node (or use a strongly consistent read API, such as DynamoDB's ConsistentRead=true).

Client ---- Write (t=0) ----> Primary (Postgres / RDS)
  |                             |
  | (Set cookie: last_write=t0) | Async replication
  v                             v
Client ---- Read (t=2s) ----> Router
                                |--> if (now - last_write < max_lag) -> Primary
                                `--> else                            -> Read Replica

Trade-off: If a user writes frequently, they bypass the replica pool entirely, concentrating load on the primary.

2. Version tokens / Monotonic LSN tracking

When a write commits, the store or application returns a monotonically increasing token (e.g., PostgreSQL Log Sequence Number pg_current_wal_lsn(), MongoDB cluster time, or a custom version integer). The client includes this token in the header of subsequent reads.

  • The read replica checks its local replay position (pg_last_wal_replay_lsn()).
  • If replica_lsn >= token_lsn, it serves the read immediately.
  • If replica_lsn < token_lsn, the replica either waits up to a bounded timeout (e.g., 50 ms) for the catchup, or the routing layer transparently falls back to the primary.
MechanismClient OverheadRead Load on PrimaryFailure Mode
Time-based routingLow (cookie timestamp)High during burstsClock drift serves stale data
LSN / Version tokenMedium (state passing)Minimal (only on fallback)Blocked read if replica lags
Quorum overlap ($R + W > N$)NoneDistributed across nodesRead latency tracks slowest quorum node
Optimistic local cacheMedium (UI state management)NoneInconsistent across multiple tabs/devices

3. Configurable Quorums ($R + W > N$)

In leaderless distributed stores (e.g., Dynamo-style systems), assign replica count $N$ such that read quorum size $R$ and write quorum size $W$ satisfy $R + W > N$. If $N=3$, choosing $W=2$ and $R=2$ guarantees that at least one node in the read quorum witnessed the successful write. Using version numbers or vector clocks, the client picks the latest version among the read responses.

4. Client-side state overlay

The client applies optimistic local caching: the browser or mobile client updates its internal UI store (e.g., Redux, local SQLite) immediately upon a 200 OK from the write endpoint. Reads check local overlay state before querying background stores. This is effective for single-device sessions but breaks if the user switches from mobile to desktop immediately after writing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How does the PACELC theorem expand on CAP, and what trade-offs does it govern when the network is healthy?

Answer

The 60-second answer. CAP describes one branch of a system's life: what happens during a partition. Partitions are rare, a well-run multi-AZ deployment can go months without one, so CAP says nothing about the behaviour you actually operate. PACELC (Abadi, 2012) adds the other branch: if there is a Partition, trade Availability against Consistency; Else, trade Latency against Consistency. The load-bearing claim is that the L/C choice is exercised on every request, not only during failures, and that it is what sets your p99 write latency floor.

The four quadrants

QuadrantPartition behaviourNormal behaviourSystems Abadi classifies here
PC/ECReject writes, stay consistentCoordinate on every writeBigTable/HBase, VoltDB, PostgreSQL with synchronous replication
PA/ELAccept writes on both sidesAnswer locally, converge laterDynamo, Cassandra, Riak, DynamoDB default reads
PC/ELStay consistentAnswer locallyPNUTS
PA/ECAccept writesCoordinate on every writeMongoDB (as classified in the 2012 paper)

The label is a property of an operation, not of a product. DynamoDB is PA/EL for a default GetItem and PC/EC for a strongly consistent read, which costs 2× the read capacity units and is served by the partition leader. PostgreSQL is EC only when synchronous_standby_names is non-empty; with the default empty value, synchronous_commit = on still commits locally and replicates asynchronously.

Worked trace: what the Else clause costs

Two data centres, 35 ms inter-DC RTT, primary in DC1, standby in DC2, client in DC1.

EL path. Primary appends the commit record to WAL, fsyncs locally (~1 ms), returns success. Client sees ~1–2 ms. The WAL sender streams the record asynchronously; the standby applies it roughly 35 ms plus apply time later. A read issued in DC2 ten milliseconds after the write returns commits only up to the standby's applied LSN: the write is not there.

EC path. The commit waits for the local flush and the standby's flush acknowledgement. These overlap: the WAL sender ships the record while the local fsync is in flight, so the floor is roughly

max(local fsync, RTT + remote fsync) ≈ max(1 ms, 35 + 1 ms) ≈ 36 ms

If the primary's local flush were slower than the round trip, it would dominate instead. Either way, choosing consistency in normal mode pins your p99 write latency to a network round trip.

Quorum variant. With R + W > N, latency is the slowest replica in the quorum, so tails amplify. Three replicas each exceeding 5 ms with probability 1% give P(at least one slow) = 1 − 0.99³ ≈ 3%: the quorum's p99 sits above the per-replica p99.

Failure modes and how you detect them

  • Unbounded replica lag (EL). If the write rate exceeds what the replica's apply threads can replay, lag grows without bound rather than settling. Symptom: read-your-writes violations when a user is routed to a different replica after a redirect. Detect with Seconds_Behind_Source (formerly Seconds_Behind_Master) in MySQL, pg_last_wal_replay_lsn() against pg_current_wal_lsn() in PostgreSQL, or the CloudWatch ReplicaLag metric on RDS.
  • Commit stalls from one slow standby (EC). A standby that is alive but slow (a saturated disk, a cross-region link under load) blocks every commit until it catches up. Detect via commit-latency histograms, not averages. Mitigate with the quorum form ANY 1 (s1, s2) in synchronous_standby_names so a single lagging standby cannot stall the primary.
  • Jitter bleeding into p999 (EC). A retransmission on the synchronous link adds directly to application latency even though no partition occurred. This is the case PACELC exists to name.

PACELC is a classification, not a law: it says nothing about durability, and both L and C are spectra rather than switches. Its value is forcing the question "what does consistency cost me on a healthy Tuesday?" instead of "what happens when the network breaks?"

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How does the PACELC theorem extend the CAP theorem, and what trade-offs does it capture during normal operations?

Answer

The 90-second version. CAP describes exactly one situation: an active partition. It says nothing about the rest of the time, when the network is healthy, and that is where most design decisions actually get made. PACELC (Abadi, 2012) adds the missing branch: if Partition, trade Availability against Consistency; Else, trade Latency against Consistency. Every system gets two labels, not one. DynamoDB is PA/EL by default; Spanner is PC/EC.

The Else branch exists because consistency costs coordination even with no failures. To return the latest committed value you must talk to a quorum, or wait for a replica to acknowledge, and that costs at least one network round trip to the slowest quorum member, plus a durable write. Skip it and you answer from a local replica immediately, but reads can be stale by however long replication takes.

Why the trade-off is physical. A linearizable write must be durable on a quorum before it is acknowledged, so its latency floor is RTT-to-quorum plus fsync. Inside one region spread over three AZs that is roughly a millisecond. A cross-region quorum (us-east-1 ↔ eu-west-1, roughly 75 ms RTT) pays that on every write. That is why Spanner keeps quorums inside a region and uses TrueTime commit-wait (2ε, with ε typically under 7 ms in Google's deployment (OSDI '12)) instead of coordinating across continents.

Classification, and the config that decides it.

LabelExampleElse branchIf branch
PC/ECSpanner; PostgreSQL synchronous_commit = on with a sync standby; DynamoDB ConsistentRead: trueCommit or read waits on a quorum round tripBlocks until the quorum is reachable
PA/ELDynamoDB default reads; Cassandra ONE; MongoDB w:1 + readConcern:"local"Local ack, single-digit-ms reads, stale reads possibleServes from the reachable side, divergence possible
PA/ECMongoDB w:1 with reads pinned to the primaryReads hit the single primary, so they are currentPrimary keeps serving; a minority primary steps down after the 10 s election timeout

The label is per-operation, not per-database. Cassandra is PA/EL at ONE and PC/EC at QUORUM. Cosmos DB exposes five levels (strong, bounded staleness, session, consistent prefix, eventual) on one account.

Worked example: DynamoDB's two read paths. Each partition is replicated three ways across AZs, and a write is acknowledged once two of the three replicas have persisted it. An eventually consistent read can be served by any replica and costs 0.5 RCU per 4 KB; ConsistentRead: true is served by the leader and costs 1 RCU per 4 KB. A workload doing 100 reads/s of 4 KB items therefore costs 50 RCU/s on the eventual path and 100 RCU/s on the strong path: the Else branch is paid in latency and in capacity. A read issued right after a successful PutItem can still return the previous value on the eventual path.

Failure modes worth naming.

  • Postgres with a single sync standby: if that standby dies, commits block rather than fail. Detect with pg_stat_replication (no sync state) and sessions waiting on SyncRep. Fix with synchronous_standby_names = 'ANY 1 (a, b)'. With no sync standby configured, synchronous_commit = on degrades to a local flush.
  • MongoDB w:1 with the default j:false: the primary acknowledges from memory and journals every 100 ms, so a crash inside that window loses acknowledged writes, and a stepdown can roll them back into a rollback file under dbPath.
  • DynamoDB global tables: cross-region replication is last-writer-wins, so concurrent writes to the same key in two regions silently drop one.

What PACELC still misses. It treats consistency as one knob, but CAP's C means linearizability while most systems offer weaker, more useful models: read-your-writes, monotonic reads, causal. It ignores durability-versus-latency (fsync batching). And latency is a distribution: a system can behave PC/EC at p50 and PA/EL at p99 if it times out and degrades.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Explain the trade-off between synchronous and asynchronous replication.

Answer

Core answer (first 60–120 seconds). The trade-off is what a commit waits for before returning to the client. Asynchronous: the primary flushes its own WAL and returns; standbys catch up in the background. Synchronous: the commit waits for at least one standby to acknowledge. That buys a bounded data-loss window, zero for acknowledged writes, at the cost of added write latency and a new availability dependency: if the standby is unreachable, writes can block. The decision is not binary. PostgreSQL exposes five synchronous_commit levels, and you can set them per transaction.

Mechanism. In PostgreSQL, an empty synchronous_standby_names means async regardless of synchronous_commit. When set, synchronous_commit controls how far the standby must get:

synchronous_commitCommit waits forData loss on primary crashAdded latency
offlocal WAL write, no flushup to ~3× wal_writer_delay (default 200 ms)~0
locallocal flushnone on primary crash, but standby may laglocal fsync (~1 ms)
remote_writestandby OS writestandby crash loses recent writes+1 RTT
on (default)standby flush to disknone for acknowledged writes+1 RTT + standby fsync
remote_applystandby applies (visible to queries)none, and reads see it+1 RTT + apply time

remote_apply is what you want if a read replica must serve read-your-writes.

Arithmetic. Same-AZ RTT 0.5 ms, cross-region US-East to US-West RTT 70 ms, local fsync 1 ms. Async p99 write latency: ~2 ms. Sync on same-AZ: 2 + 0.5 + 1 ≈ 3.5 ms. Sync on cross-region: 2 + 70 + 1 ≈ 73 ms. A 36× increase. That is the number to put in front of a product owner.

Availability. Naive sync with one standby makes the system depend on two nodes. If the standby is down, writes block. PostgreSQL 10+ quorum commit fixes this: synchronous_standby_names = 'ANY 1 (s1, s2, s3)' requires one ack from any of three, tolerating two down. FIRST 2 (s1, s2, s3) requires two, in priority order. MySQL's semi-sync has a different escape hatch: rpl_semi_sync_source_timeout (ms, default 10000; MySQL 8.0.26+ names it source; earlier versions use master) falls back to async if no ack arrives, which silently drops the durability guarantee, so alert on it.

Code. Per-transaction override:

SQL
-- PostgreSQL 10+
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby1, standby2, standby3)';
-- default for the cluster is synchronous_commit = on
-- payments ledger: strongest guarantee
BEGIN;
SET LOCAL synchronous_commit = 'remote_apply';
UPDATE accounts SET balance = balance - 100 WHERE id = 42;
COMMIT;
-- analytics event: async is fine
BEGIN;
SET LOCAL synchronous_commit = 'off';
INSERT INTO events (payload) VALUES ('...');
COMMIT;

Failure modes. Split brain when the old primary is still accepting writes; a promoted replica missing the last few async writes; clients caching the old primary's address. Detect with pg_stat_replication lag (write_lag, flush_lag, replay_lag) and alert on pg_last_wal_replay_lsn() falling behind. Test failover: an untested failover is not a recovery plan.

Decision. Payments ledger: sync remote_apply to a same-region standby, async to a cross-region one. Analytics events: async. Most systems are mixed; per-table or per-transaction synchronous_commit is legitimate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

What is split brain and how do you prevent it?

Answer

In the first 90 seconds. Split brain is two nodes in one cluster both acting as primary and both accepting writes. When the partition heals you have two divergent histories and no automatic way to choose between them: duplicate records, a double-spent balance, a lost write, usually found days later.

It happens because a node cannot distinguish "the other side is down" from "I am cut off". Both look like silence. So any rule shaped like "if I can't see the primary, promote myself" produces split brain under partition. Prevention is two independent mechanisms, and you want both:

  • Quorum. Only a side holding a majority of voting members may accept writes. Two sides of a partition cannot both hold a majority, so at most one keeps serving; the minority stops. That is the availability you pay deliberately.
  • Fencing. When a new primary is promoted, the old one must be unable to write: even if it is alive, healthy, and does not know it was replaced. Quorum alone does not cover this, because the old primary may be reachable from clients while sitting outside the cluster's view.
MechanismConcrete formCost
Majority quorumRaft/etcd: 3 nodes tolerate 1 failure, 5 tolerate 2; etcd defaults --heartbeat-interval 100 ms, --election-timeout 1000 msMinority side unavailable for the duration
Self-demotionMongoDB primary steps down after settings.electionTimeoutMillis (default 10000 ms) without a majorityUp to 10 s of write unavailability
Replica gateRedis Cluster min-replicas-to-write (default 0) with min-replicas-max-lag (default 10 s)Master refuses writes while isolated
Fencing tokenMonotonic token from the lock service; storage rejects any write carrying a token below the highest it has seenStorage must check the token
Power fencingSTONITH in Pacemaker/Corosync (stonith-enabled)Needs out-of-band control: PDU or BMC
WitnessSQL Server AG file-share witness; corosync two_node: 1Extra component, tie-break only

Trace: 5-node Raft cluster {A,B,C,D,E}, leader A at term 7. Network splits {A,B} | {C,D,E}.

  1. C, D, E hold 3 of 5: a majority. After the election timeout (etcd default 1000 ms) C stands, wins votes from D and E, and becomes leader at term 8. Writes commit on 3 replicas.
  2. A and B hold 2 of 5: no majority. A cannot commit anything and steps down once it stops hearing from a majority; B stays a follower. Client writes to A hang or error.
  3. Heal: A and B see term 8 > 7, discard their uncommitted term-7 entries, and follow C. Everything C committed in term 8 is the truth.

A never accepted a committed write during the partition, because commit needs a majority. That is exactly what quorum buys.

Fencing, same shape. Client 1 takes the lock and gets token 33, then pauses 12 s in a GC. The lease expires, client 2 takes the lock with token 34 and writes. Client 1 wakes and writes with token 33; storage has already seen 34 and rejects it. Without the token check, client 1's write lands and corrupts the record: the lease alone did not stop it.

Failure modes worth naming. An even cluster size is a trap: 4 nodes split 2-2 leaves nobody with a majority and the whole cluster stops accepting writes. Use an odd size or a witness. Cassandra-style AP systems have no quorum at all and resolve conflicts by last-write-wins on the cell timestamp, silently dropping the losing write; fine for metrics, wrong for a ledger. Elasticsearch 7.0 deprecated the hand-set discovery.zen.minimum_master_nodes in favour of an automatically maintained voting configuration, and forgetting that setting was a classic split brain. And test it: partition a test cluster with iptables and confirm the minority side stops accepting writes, because failover code is written once and rarely exercised.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

What should happen during a network partition, and how do you decide?

Answer

The 90-second answer. A partition splits the cluster into sides that cannot talk. Only one side can hold a majority, so the real decision is: does the minority side refuse writes, or accept them and create data that has to be merged later? I default to refusing writes on the minority side, because merge logic is a design you have to build and test, and most teams have not. I deviate only for operations where a stale read is provably harmless and the write is commutative or last-writer-wins.

Assumptions I would state out loud: this is a network partition, not a node crash; nodes on both sides are alive; clients can reach both sides.

The mechanism. Quorum arithmetic decides who can write. With N replicas, a write needs W acks and a read needs R, and R + W > N guarantees the read set overlaps the write set. N=3, W=QUORUM=2, R=QUORUM=2 gives 4 > 3. A 2–1 split leaves the majority side able to reach 2 replicas and the minority side able to reach 1, so the minority's writes fail with a timeout rather than silently succeeding. The minority is not "choosing" consistency; it is arithmetically unable to reach quorum.

Concrete knobs:

systemsettingdefaultpartition behaviour
Cassandraconsistency levelLOCAL_ONE (Java driver 4.x)minority side times out; write_request_timeout_in_ms defaults to 2000 ms
etcdquorum(n/2)+13 nodes tolerate 1 loss, 5 tolerate 2; --election-timeout 1000 ms, --heartbeat-interval 100 ms
PostgreSQLsynchronous_standby_namesunsetwith ANY 1 (s1,s2) the primary keeps writing when one standby is cut off; with a single named standby it blocks
Consulconsistency modedefault (leader lease)consistent forces a linearizable read through the leader; stale reads any server

Per operation, not per system. A retail site keeps browsing available, that is most of its traffic, and refuses to confirm the last unit of stock. Same cluster, two answers.

How I decide. Ask the business a concrete either/or: "for the next ten minutes we either stop taking orders, or we take orders we may not be able to fulfil." That is answerable. "Do you want consistency or availability?" is not.

Recovery is part of the answer. If both sides accepted writes, you need merge rules: last-writer-wins on a timestamp (what DynamoDB global tables do), a CRDT, or application-level reconciliation. Hinted handoff covers short partitions, Cassandra's max_hint_window_in_ms defaults to 3 hours, and past that the divergence is permanent until repaired. If writes were refused, the returning side replays a backlog; cap client retries with a budget (Google SRE suggests 10% of requests) and jittered backoff, or the heal becomes a second outage.

Worked trace. Five-node etcd, nodes A–E, quorum 3. A partition isolates D and E. A, B and C keep a leader and serve writes. D and E hold an election, fail to reach 3 votes, and stay candidates; a client write to D or E returns etcdserver: request timed out after the client timeout (etcdctl defaults to 5 s). On heal, D and E rejoin, take the log from the leader, and roll back any uncommitted entries. No merge is needed, because the minority never committed. Now the same split with Cassandra at CL=ONE: both sides accept writes, and on heal the conflicting rows resolve by cell timestamp. The later write wins and the earlier one is silently gone. That is the cost of the availability choice, and it is why I want the choice made per operation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

What are recovery point and recovery time objectives, and how do they relate to consistency?

Answer

RPO is the maximum age of data you can lose, expressed as time: an RPO of five minutes means losing the last five minutes of writes is acceptable. RTO is the maximum time the service can be unavailable. They are the operational form of the consistency/availability trade: RPO is a durability claim about committed writes, RTO is the availability side of the same CAP choice. RPO 0 for a single write means that write survives a node failure; it says nothing about serializability across keys.

What sets each, by failure mode:

FailureRPO set byRTO set by
Single node crashsynchronous_commit=on → 0automatic failover, typically 60–120 s on RDS Multi-AZ
AZ losssync standby in a second AZ → 0failover plus client reconnection
Region lossasync cross-region lag, seconds to minutespromotion, minutes to hours
Accidental DELETElast backup or PITR windowrestore time, scales with data size
Bad migrationimmutable backuprestore plus replay

The mechanism: async replication makes RPO equal to the replication lag at the instant of failure, and that lag is a number you can read. On PostgreSQL:

SQL
-- on the primary
SELECT application_name, sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes
FROM pg_stat_replication;

replay_lag_bytes is bytes, not time: divide by your write rate to get the RPO you are actually running. pg_last_xact_replay_timestamp() on the standby gives time directly, but it is stale on an idle primary: it reports the last replayed transaction, not the current gap.

Sync replication moves RPO to 0 for the failures it covers. PostgreSQL's synchronous_commit has five levels: off, local, remote_write, on (the default), remote_apply. on waits for the standby to flush WAL to disk but not to apply it, so failing over to that standby can still lose the tail; remote_apply waits for apply, which is what you need if you want read-your-writes on the standby. synchronous_standby_names = 'ANY 1 (s1, s2)' and 'FIRST 1 (s1, s2)' both keep writes flowing when one of two standbys is down: the difference is which one is chosen: FIRST takes the highest-priority connected standby, ANY takes whichever acks first. Writes block when fewer than num_sync listed standbys are connected, so FIRST 1 (s1) with a single standby means RPO 0 but RTO = ∞ if s1 is down. That is the trade in one line.

MySQL's semi-synchronous replication has the same shape with a silent failure: rpl_semi_sync_source_timeout defaults to 10000 ms, and after ten seconds without an ack the source falls back to async. RPO quietly becomes non-zero. Monitor Rpl_semi_sync_source_status.

Managed equivalents worth naming: DynamoDB point-in-time recovery restores to any second in a 35-day window; S3 Replication Time Control commits to replicating 99.99% of objects within 15 minutes.

Arithmetic to do before agreeing to a number: 2 TB restored over a 1 Gbps link is 2×10¹² bytes × 8 ÷ 10⁹ bps ≈ 16,000 s ≈ 4.4 hours of transfer alone, before restore processing. If the business says RTO one hour, that backup path cannot meet it and the answer is a warm standby, not a faster restore.

Two cautions. An untested RTO is an aspiration; the first real failover is slower than the diagram. And the numbers should differ per data type: losing 30 s of analytics events is fine, losing 30 s of payments is not, so one system-wide number over-engineers some paths and under-protects others.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How does consistency interact with multi-region deployment?

Answer

Core answer (first 90 seconds)

Multi-region doesn't change the consistency menu, it changes the price. Coordination that costs about a millisecond inside a region costs 70–200 ms across regions, because that is the fiber round trip and no amount of software beats it. So the real question is which operations can afford a cross-region round trip.

Sanity check on the floor: Ashburn–Dublin is ~5,500 km great-circle, fiber runs ~1.3× that (~7,100 km), and light in fiber moves at ~200,000 km/s. That is ~36 ms one way, ~71 ms round trip. Measured RTT is ~75 ms. The floor is physics, not the stack.

linkRTT
same AZ~0.5 ms
us-east-1 ↔ us-west-2~65 ms
us-east-1 ↔ eu-west-1~75 ms
eu-west-1 ↔ ap-southeast-1~160 ms
us-east-1 ↔ ap-southeast-1~200 ms

A quorum write over three regions, coordinated locally, needs one remote ack: ~75 ms. A write needing a quorum in every region waits for the slowest: ~200 ms. The same write inside one region is ~1 ms. That is a 75–200× penalty paid on every write, not only during failures. This is PACELC: under a partition you trade availability against consistency; the rest of the time you trade latency against consistency, and multi-region makes the second trade permanent.

The options

designwrite latencyread consistencyconflict handling
single-region primary, remote read replicascross-region RTT (~75–200 ms)local reads stale by replication lagnone needed
active-active, last-writer-winslocal (~1 ms)eventually consistent, ~1 s lagtimestamps; silent data loss
active-active, CRDT / mergelocaleventually consistent, convergesdata model must be commutative
regional partitioninglocalstrong within regionnone; breaks when users move
split by operationlocal for most, cross-region for the fewmixedonly the coordinated writes

Worked example: Cassandra, RF=3 per DC

Python
from cassandra import ConsistencyLevel
from cassandra.query import SimpleStatement

# replication = {'class':'NetworkTopologyStrategy',
#                'us-east':3, 'eu-west':3, 'ap-southeast':3}

# 2 of 3 replicas in the local DC. No cross-region wait. ~1 ms.
session.execute(SimpleStatement(q, consistency_level=ConsistencyLevel.LOCAL_QUORUM))

# A quorum in every DC. Latency = slowest region RTT. ~200 ms from us-east.
session.execute(SimpleStatement(q, consistency_level=ConsistencyLevel.EACH_QUORUM))

The rule that makes this checkable: strong consistency needs read CL + write CL > replication factor. LOCAL_QUORUM + LOCAL_QUORUM = 2 + 2 = 4 > 3, so reads and writes are strongly consistent within a DC, and the cross-DC path is still asynchronous, so a client in eu-west reading LOCAL_QUORUM can miss a write committed in us-east. EACH_QUORUM buys cross-region strong consistency (R+W > RF in every DC) and pays the ~200 ms.

Failure modes

  • Last-writer-wins active-active (DynamoDB global tables, replication lag typically under 1 s) silently drops one of two concurrent writes. Detect it by logging resolved conflicts, not by hoping.
  • Read-your-writes breaks across regions: a user writes in eu-west, the next request routes to us-east, and they see the old value for up to the replication lag. Under 1 s for DynamoDB global tables and Aurora Global Database.
  • Regional partitioning fails the moment a user moves: their data is in the wrong region and the request either crosses regions or 404s.
  • Clock-based conflict resolution depends on clock skew. TrueTime-style bounded uncertainty is what makes Spanner's external consistency work; the Spanner paper reports commit-wait averaging ~7 ms.

What I'd establish first

Data residency (it may decide the design for you), where users are and whether they move, and the write latency budget. Then ask whether multi-region is needed at all: a single region with multi-AZ redundancy already gives high availability, and multi-region multiplies complexity in every dimension. It is justified by global latency or a regulatory requirement, not by a vague wish for resilience.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do caches interact with consistency guarantees?

Answer

A cache is a replica you didn't call a replica. It holds a copy of data whose source can change, so it has a staleness window, and every guarantee you'd reason about for a read replica (read-your-writes, monotonic reads, bounded staleness) applies to it. The difference is scale: async replication lags by tens to low hundreds of milliseconds, a cache lags by its TTL, which is usually 60–300 seconds. So the answer is that a cache buys read latency and origin load with an explicit, bounded staleness window, and the engineering is choosing that window per item and making invalidation reliable enough that the TTL is a backstop rather than the mechanism.

The race that survives a correct invalidation. Cache-aside, Redis, TTL 300s. Times illustrative.

t (ms)readerwritercacheDB
0GET → missempty100
1SELECT → 100empty100
2UPDATE → 50, commitempty50
3DEL keyempty50
4SET key=100 EX 30010050

At t=3 the DEL was correct and executed: it was a no-op because the key was absent. The reader's fill at t=4 landed after it and resurrected the old value for 300s. "We invalidate on write" is not sufficient on its own.

Closing the window with a lease. The lease lives under the same key as the value, so the writer's single DEL invalidates both. Redis 6.x, redis-py:

Python
FILL = """
if redis.call('GET', KEYS[1]) == ARGV[1] then
  redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])
  return 1
end
return 0
"""

def get_balance(user_id):
    key = f"user:{user_id}:balance"
    v = r.get(key)
    if v is not None and not v.startswith(b"lease:"):
        return int(v)
    token = b"lease:" + uuid4().hex.encode()
    if not r.set(key, token, nx=True, ex=10):
        return read_primary(user_id)          # another reader holds the lease
    value = read_primary(user_id)
    r.eval(FILL, 1, key, token, value, 300)   # fills only if the lease survived
    return value

A writer does r.delete(key). If it lands between the reader's SELECT and FILL, the compare-and-set fails and the stale value is never written. The cheap approximation is a delayed double delete, DEL at write time and again ~500 ms later, which narrows the window to the delay without closing it.

Invalidation strategies.

strategystaleness boundhow it failswrite-path cost
TTL onlythe TTL (e.g. 300s)none: self-healszero
delete-on-writepropagation (~1 ms same-DC) + race windowone missed DEL → full TTL of stalenessone DEL per write
write-through0 on successcache down → writes fail or bypass itone SET per write; write path coupled to cache
write-behindunboundedqueue or cache loss → data lossasync, lowest write latency

I'd run delete-on-write with a TTL backstop, and accept that the TTL is what bounds a forgotten write path: a script, a new service, an admin action. One will forget.

Failure modes worth naming. A key missing the tenant or user serves one customer's data to another; detect it with a wrapper that asserts the key prefix, or a test that reads as tenant B after tenant A writes. A thundering herd on expiry sends 10k concurrent misses at one key to the origin; detect it as a DB QPS spike correlated with TTL expiry, and fix it with the lease above or HTTP stale-while-revalidate. A hot key at 100k QPS exceeds a single Redis node (ballpark 100k simple GETs/s, single-threaded); detect it as pinned node CPU with p99 spikes, and fix it with a short-TTL in-process cache or key sharding.

At the HTTP layer the same reasoning shows up as Cache-Control: max-age=60, s-maxage=300, stale-while-revalidate=30, ETag with If-None-Match returning 304 to revalidate without resending the body, and Vary: a missing Vary on a personalised response is the CDN version of the missing-tenant key.

Finally, set the window per item, not globally: a permission check wants 5–30s because that is your revocation latency, a product catalogue tolerates 300s, an FX rate wants 60s. One global default means at least one of them is wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

How does eventual consistency affect application design in practice?

Answer

Eventual consistency means replicas converge once writes stop; the window is unbounded, not "a few milliseconds". The design consequence is one classification: every read is either display-only or decision-informing, and consistency gets bought per operation rather than per database.

What breaks, concretely

  • Read-your-writes. A user saves a profile, the next read lands on a lagging replica, they see the old value, and save again. It presents as a UI bug, so it gets misdiagnosed.
  • Monotonic reads. Two consecutive reads hit replicas at different positions and the value goes present → absent → present.
  • Write conflicts. Concurrent writes need a resolver. Cassandra resolves per cell by last-write-wins on the client-supplied timestamp, so a node whose clock runs fast wins every conflict and the other write disappears with no error.

The knobs that fix them

StoreSettingWhat it buys
DynamoDBConsistentRead: true on GetItem/Query/Scan1 RCU per 4 KB instead of 0.5. Not available on GSIs: they are eventually consistent only
CassandraCL=QUORUM on both read and write, RF=3R+W = 4 > N = 3, so a read sees the last acknowledged write
MongoDBreadConcern: "majority" + writeConcern: {w: "majority"}, causal-consistency sessionRead-your-writes and monotonic reads inside the session
PostgreSQLSET LOCAL synchronous_commit = remote_applyCommit returns only after the standby has applied the WAL, so a standby read sees it
RedisWAIT numreplicas timeoutBlocks until N replicas acknowledge

The arithmetic that decides how much to buy

DynamoDB, 4 KB items, 5,000 reads/s:

  • Eventually consistent: 0.5 RCU per item → 2,500 RCU/s.
  • Strongly consistent: 1 RCU per item → 5,000 RCU/s.

Making every read strongly consistent doubles read capacity. If 3% of reads are decision-informing (150/s), routing only those through ConsistentRead: true costs 2,500 + 150 = 2,650 RCU/s: 6% over the eventual-only baseline. That gap is why the classification is worth an afternoon.

A trace of the read-your-writes fix

  1. Client PUT /profile → primary writes, returns the new document in the response body.
  2. Client renders from the response instead of issuing GET /profile.
  3. No replica read happens, so no staleness window exists for this user.

Re-fetching after a write feels more correct and is the single most common cause of this bug. Where the write response can't carry the value, pin the session to one replica for the duration of the session.

Failure modes worth naming

  • Uniqueness checks on a replica. Two concurrent inserts both read "no such email", both write, and you have duplicates. The fix is a conditional write on the primary (attribute_not_exists(email) in DynamoDB, IF NOT EXISTS in Cassandra) and Cassandra's lightweight transactions run Paxos in roughly four round trips, so they cost far more than a normal write. Budget for that.
  • Quorum latency tracks the tail. A quorum write waits for the second-fastest of three replicas, so one slow replica raises write p99 even though it isn't needed for the ack. Watch per-replica latency histograms, not the cluster average.
  • LWW clock skew. Detect it by comparing writetime() across replicas for the same key, or avoid it by writing with server-side now().

The distinction to hold onto: a stale read that displays something is cosmetic; a stale read that informs a write decision is a correctness bug. Follower counts can lag. Balance checks, uniqueness checks and inventory checks cannot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How would you decide which operations need strong consistency?

Answer

The test. For each operation, ask what a stale read causes: an action that cannot be undone, or a display that corrects itself. Only the first needs a strong read. Applied operation by operation, the list is short, typically a handful out of dozens, and everything else stays on replicas.

OperationStale read causesWhat it actually needs
WithdrawalOverdraftStrong read, or a conditional write
Checkout decrementOversellConditional write on the primary
Signup uniquenessDuplicate accountUnique index: no read at all
Permission checkUnauthorised actionPrimary read, or cache with explicit revocation
Follower count, feed, dashboardNothingReplica read

Most "strong reads" are really strong writes. Inventory is the standard example. The version that needs a strong read is read-then-write:

SQL
SELECT qty FROM inventory WHERE sku = 'SKU-1';   -- both sessions read 1
UPDATE inventory SET qty = qty - 1 WHERE sku = 'SKU-1';

Two concurrent checkouts both read qty = 1, both decrement, and the row ends at -1. The read was consistent; the pair was not.

Move the guard into the write and the read disappears:

SQL
-- Postgres 16, READ COMMITTED (the default)
UPDATE inventory SET qty = qty - 1
 WHERE sku = 'SKU-1' AND qty >= 1
RETURNING qty;

Trace it with qty = 1 and two sessions. T1 takes the row lock, sets qty = 0, returns one row. T2 blocks on the lock; when T1 commits, T2 re-evaluates qty >= 1 against the newly committed row, under READ COMMITTED Postgres re-checks the predicate on the updated version, the predicate fails, T2 updates zero rows and returns an empty result. The app maps "zero rows" to 409 out of stock. No oversell, no strong read at add-to-cart, and the authoritative check happens exactly once, at the point that matters.

Uniqueness works the same way: INSERT INTO users (email) VALUES ($1) ON CONFLICT (email) DO NOTHING RETURNING id returns zero rows when the email already exists. The unique index enforces it at write time, so the pre-check read was never doing the work.

The middle case is read-your-writes, and it is a session guarantee. A user reading their own profile after an edit is technically a display, but a stale one reads as a broken system. Don't promote the whole read path to the primary for this. Capture the write's position and wait for the replica to reach it: on Postgres, take pg_current_wal_lsn() on the primary, hand it to the session, and on the replica wait until pg_last_wal_replay_lsn() is at or past it, falling back to the primary on timeout. MySQL has the same shape in WAIT_FOR_EXECUTED_GTID_SET(gtid, timeout). Only the writing user's own reads pay the cost.

Failure modes. Strong everywhere makes the primary the read bottleneck: say a primary absorbing 5k writes/s has little headroom for the 20k reads/s three replicas were serving, and cross-region reads pay the round trip. Eventual everywhere produces the oversell and the duplicate account above. The detectable symptom of the first is replica CPU near idle while primary CPU pins; of the second, negative counters and unique-constraint violations in the logs.

Where it's a business call. Overselling by a small amount is sometimes cheaper than the latency of a strong check, but that is a decision for the business, with a defined compensation process, not something to settle silently in the data layer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you handle conflicting concurrent writes?

Answer

What I'd say first

Ask what the data is before picking a policy. Three questions settle it: can the two writes be combined without a human deciding, does losing one cost anything, and can the client retry? Then choose per field, not per system: a user's document body and a last_seen timestamp in the same row want different answers.

The default for user-authored data is optimistic concurrency: a version column or an ETag, reject the stale write, let the client re-read. The default for counters and sets is to make the operation commutative so there is no conflict to resolve. Last-write-wins is reserved for data where loss is harmless, and that judgement gets written down.

Optimistic concurrency, traced

SQL
CREATE TABLE doc (id int PRIMARY KEY, body text NOT NULL, version int NOT NULL DEFAULT 0);
INSERT INTO doc VALUES (1, 'v0', 0);

-- client A                            -- client B, concurrently
UPDATE doc SET body='A', version=version+1
 WHERE id=1 AND version=0;             UPDATE doc SET body='B', version=version+1
-- UPDATE 1                             WHERE id=1 AND version=0;
                                        -- blocks on A's row lock
                                        -- UPDATE 0   (after A commits)

Under READ COMMITTED, B blocks on the row lock, and when A commits Postgres re-evaluates B's WHERE against the new row version: version is now 1, so the predicate fails and B updates zero rows. No error is raised. If you don't check the affected-row count, you have quietly implemented last-write-wins. Under REPEATABLE READ the same race raises ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) and the client must retry the whole transaction.

The HTTP equivalent is If-Match: "<etag>"; a stale tag gets 412 Precondition Failed (RFC 9110). DynamoDB does it with ConditionExpression="version = :v", returning ConditionalCheckFailedException.

Last-write-wins and clocks

Cassandra resolves conflicts per cell by a microsecond timestamp, and the client can set it with USING TIMESTAMP. Two coordinators whose clocks differ by 50 ms can order two writes backwards, and the loser is discarded with no error and no trace. Equal timestamps are broken by comparing the cell values byte-wise, largest wins: deterministic, but arbitrary. Client timestamps older than gc_grace_seconds (default 864000 s, ten days) can resurrect deleted data. CockroachDB sidesteps this with hybrid logical clocks and a --max-offset default of 500 ms: a node whose clock drifts further self-terminates rather than serve a bad order. Spanner's TrueTime uncertainty is typically less than 7 ms, and it commit-waits that interval.

Merging and CRDTs

A G-Counter merges by taking the per-replica maximum; state is one integer per replica, so it grows with replica count, not with write volume. OR-Sets and sequence CRDTs (Yjs, Automerge) cover lists and text. They converge regardless of delivery order, and they constrain what you can express: you cannot ask a CRDT for "the value as of 14:00" without extra machinery.

The highest-leverage move

Model the change as a delta or an append-only event instead of an absolute assignment. add 5 merges with add 3; set to 12 does not. Kafka's single-writer-per-partition log is the same idea taken to its limit: ordering is decided by the log, so there is nothing to resolve.

strategymechanismcostloses datafits
LWWhighest timestamp winsnoneyes, silentlypresence, cache
version checkreject stale writeone round tripnouser-authored rows
CRDT / mergecombinestate ∝ replicasnocounters, sets, lists
surfacehuman picksUI + latencynodocuments

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you design a system that must never oversell inventory?

Answer

I would first check whether 'never' is the actual requirement, because it is expensive and often stronger than the business needs. Many retailers accept rare oversells and handle them with an apology and a refund, because the cost of that is lower than the cost of the latency and complexity of guaranteeing it. That is a business decision and worth asking rather than assuming.

If it genuinely must never oversell, the constraint is that the decrement must be atomic and conditional: reduce the count only if it is sufficient, in a single operation that cannot interleave. UPDATE inventory SET available = available - 1 WHERE sku = ? AND available >= 1, checking that exactly one row was affected. There is no read-then-write window, so concurrent requests cannot both succeed on the last item.

The critical point is that the read does not need to be strongly consistent: only the write does. Displaying stock levels can be eventually consistent and slightly stale; showing 'in stock' when the last item just went is a minor and recoverable disappointment. The authoritative check happens at the decrement, which is where the consequence is. That converts an apparently system-wide strong-consistency requirement into one atomic operation, which is dramatically cheaper.

The distributed complication is that if inventory is partitioned or replicated across regions, an atomic decrement requires coordination, which reintroduces latency and partition sensitivity. Options: keep inventory authoritative in one place and accept the latency for that operation only; or partition inventory by location so each region owns its own stock and decrements locally, which is often how physical retail actually works and removes the coordination entirely.

Reservations are the pattern I would use for a checkout flow: decrement on adding to cart with a timeout, releasing if checkout is not completed. That prevents the race between two shoppers holding the same last item, at the cost of temporarily unavailable stock and an expiry process to get it back.

And the failure paths matter: what happens if payment fails after the decrement, or the process dies between reserving and confirming. Each needs a compensating action, and the expiry sweeper is what makes reservations safe against crashes rather than a source of permanently stuck stock.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you handle a feature that needs stronger consistency than the current architecture provides?

Answer

What I'd say in the first 90 seconds

Ask what guarantee the feature actually needs, then buy it for the narrowest scope that satisfies it. Three questions settle it: which anomaly is unacceptable (lost update, stale read after your own write, or a torn read across two keys); which operations need it (one write path, or every read of the entity); and what breaks if I only fix that path.

Most "we need strong consistency" requests turn out to be read-your-writes on one entity. That is a routing change, not an architecture change.

The ladder, cheapest first

1. Per-operation guarantee. Consistency is chosen per request, not per cluster. DynamoDB: ConsistentRead: true on GetItem/Query. Strongly consistent, not available on GSIs, and it bills 1 RCU per 4 KB instead of 0.5. MongoDB: readConcern: "majority" for a read that reflects majority-committed writes, or "linearizable" for a single-document read on the primary with a unique-index filter. Postgres: send the read to the primary.

2. Restructure the operation. Convert a strong read into a conditional write. In Postgres under READ COMMITTED (the default), UPDATE stock SET n = n - 1 WHERE sku = $1 AND n >= 1 takes a row lock and re-evaluates the predicate against the updated row, so concurrent decrements serialise with no application-level lock. In DynamoDB, ConditionExpression: "stock >= :one" is evaluated on the leader node, so replica staleness never enters the picture.

3. Isolate the data. If the entity genuinely needs constraints and multi-key transactions, put it in Postgres and leave the feed in the eventually consistent store. One writer per entity, the other side derived through an outbox or CDC: never dual writes.

4. Change the architecture. Only when several features hit the same wall. One feature is not evidence. If the requirement is genuinely cross-region linearizability, that is Spanner/CockroachDB territory and a different conversation.

NeedMechanismCost
Read-your-writesRoute the session's reads to the primary, or wait for replica replayPrimary read load; a few ms of wait
No lost update on one itemConditional write (ConditionExpression, UPDATE ... WHERE)1 extra WCU per rejected attempt, plus retries
Linearizable single-key readDynamoDB ConsistentRead: true; Mongo readConcern: "linearizable"2x read cost; primary-only
Multi-key atomicTransactWriteItems (≤100 items, ≤4 MB); Postgres transaction2x WCU; lock contention

Worked trace: 500-unit flash sale

Item {pk: "SKU#A1", stock: 500}, under 1 KB, on-demand table. Write path:

Python
# boto3, DynamoDB
table.update_item(
    Key={"pk": "SKU#A1"},
    UpdateExpression="SET stock = stock - :one",
    ConditionExpression="stock >= :one",
    ExpressionAttributeValues={":one": 1},
    ReturnValuesOnConditionCheckFailure="ALL_OLD",
)

At 12,000 attempts in one second: 500 succeed (stock 500 → 0), 11,500 raise ConditionalCheckFailedException. Failed conditional writes are still billed, so that second costs 12,000 WCU = 0.012 M × $1.25/M ≈ $0.015.

The read-then-write version: read stock, compare in the app, write. At 12,000 rps with a 20 ms gap between read and write, 12,000 × 0.02 = 240 requests are in flight inside that window, so up to 240 buyers can each see the last unit. Oversell is bounded by concurrency, not by stock.

Making the read strongly consistent instead: at 50,000 product-page reads/sec of 4 KB, eventual reads cost 25,000 RCU/s and strong reads 50,000 RCU/s. At $0.25 per million RCU that is $540/day versus $1,080/day: $540/day to fix the wrong end of the problem.

Failure modes and how I'd detect them

  • Retrying conditional writes without jitter concentrates load on one hot key. Detect: ConditionalCheckFailedException rate and retry amplification per key.
  • Dual writes to two stores diverge on partial failure. Detect: a reconciliation job counting mismatches per hour; alert on any non-zero.
  • Postgres SERIALIZABLE aborts with SQLSTATE 40001 under contention and must be retried. Detect: pg_stat_database.xact_rollback.
  • Quorum reads with R + W ≤ N are not linearizable even though they look like it. Detect: read-repair and digest-mismatch counters.
  • Weakening the requirement to fit the architecture without recording it. That is a defect deferred, not a decision.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Explain why 'the database handles consistency' is an incomplete answer.

Answer

Core answer (first 90 seconds)

Saying 'the database handles consistency' is only true of the transaction the database itself executes, at the isolation level you chose, over the objects it owns. It says nothing about caches, replicas, other services, brokers, or the application code reading and writing through it. Assume a common stack: Postgres 16 primary, one asynchronous streaming replica serving reads, Redis cache-aside in front, two services with separate databases, events published to Kafka, and the default isolation level of READ COMMITTED. Every inconsistency I would expect in that stack lives outside the primary's transaction engine.

Where the boundary actually sits

HopWhat the database guaranteesFailure that still happensNamed control
Read from async replicaCommit is durable and ordered on the primary; apply on the replica is not synchronousRead-your-writes violated while WAL apply lagsPostgres hot standby; pg_stat_replication replay_lag; synchronous_standby_names
Cache-aside read (Redis)Nothing, the cache sits outside the DBStale value until TTL expiry or explicit deleteSET key val EX 60, DEL on write, versioned keys
Second service's own databaseNothing across processesTwo updates with no shared atomic boundaryTransactional outbox plus a polling relay
Kafka produce after commitNothing spanning commit and publishEvent lost or duplicated (dual-write)Outbox row inserted in the same transaction
Application read-then-writeOnly the per-statement snapshot of READ COMMITTEDLost updateSELECT ... FOR UPDATE, or UPDATE ... WHERE balance = expected
Isolation level in useOnly the anomalies that level forbidsNon-repeatable reads, phantomsSET TRANSACTION ISOLATION LEVEL REPEATABLE READ or SERIALIZABLE

Worked trace: replica lag (figures hypothetical, scenario is the standard one)

t = 0 ms: app commits UPDATE accounts SET balance = 100 WHERE id = 7 on the primary; commit returns at t = 1.2 ms. t = 1 ms: pg_stat_replication on the primary reports replay_lag = 18 ms for the replica. t = 2 ms: the same app reads that row from the replica and gets balance = 80, the pre-update value. The read fell inside the replica's 18 ms apply-lag window. t = 20 ms: the replica has replayed the WAL and now returns 100.

The database kept its promise: the commit was durable and ordered on the primary. The application broke read-your-writes by routing its own read to a replica.

Worked trace: lost update under READ COMMITTED (Postgres 16, psycopg 3.2, Python 3.12)

# accounts(id, balance); row id = 7 starts at 100.
# S1 and S2 each want to add 10.
# S1: BEGIN; SELECT balance FROM accounts WHERE id = 7;  -- 100
# S2: BEGIN; SELECT balance FROM accounts WHERE id = 7;  -- 100
# S1: UPDATE accounts SET balance = 110 WHERE id = 7; COMMIT;  -- ok
# S2: UPDATE accounts SET balance = 110 WHERE id = 7; COMMIT;  -- ok
# Final balance = 110, not 120. One increment vanished.

Two safe fixes, both application-side:

  1. Pessimistic: SELECT balance FROM accounts WHERE id = 7 FOR UPDATE before computing.
  2. Atomic: UPDATE accounts SET balance = balance + 10 WHERE id = 7.

Set the transaction to REPEATABLE READ in Postgres and S2's UPDATE no longer silently wins: it raises SQLSTATE 40001, 'could not serialize access due to concurrent update', and your code must catch it and retry. The database did exactly what the chosen level promises; the retry logic is yours.

What that means for the answer

So the precise statement is: a database provides specific guarantees, at a chosen level, within its boundary. The useful follow-up is to name the boundaries: which reads go to a replica or a cache, where data crosses a service or a broker, and where code reads a value and then writes based on it. Those are where consistency bugs actually appear, and every one of them is outside what the database can promise.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you test a system's consistency behaviour?

Answer

To test consistency, you must create the conditions that break it: concurrency, replication lag, partitions, failover. Start with a realistic topology: at least 3 nodes across 2 AZs, one primary, two replicas. A single-node test cannot exhibit any of these.

Read-your-writes with induced lag. Use PostgreSQL 15 primary + streaming replica. Default synchronous_commit = on only flushes local WAL; the replica can lag. Write to primary, read from replica immediately:

Python
import psycopg2
primary = psycopg2.connect("host=primary dbname=test")
replica = psycopg2.connect("host=replica dbname=test")
cur = primary.cursor()
cur.execute("INSERT INTO kv (k, v) VALUES ('x', '1')")
primary.commit()
cur2 = replica.cursor()
cur2.execute("SELECT v FROM kv WHERE k = 'x'")
row = cur2.fetchone()
assert row is not None and row[0] == '1', "read-your-writes violated"

Induce 500 ms lag on the replica: tc qdisc add dev eth0 root netem delay 500ms. The test fails with row is None. Fix: set synchronous_commit = remote_apply and synchronous_standby_names = 'replica1' on primary; the write now waits for replica apply, and the test passes.

Concurrent writes with a linearizability checker. Use Porcupine (Go) to check a register history. A non-linearizable history:

Go
history := []porcupine.Operation{
  {ClientId: 0, Input: 1, Call: 0, Output: 0, Return: 10},
  {ClientId: 1, Input: 2, Call: 5, Output: 0, Return: 15},
  {ClientId: 2, Input: porcupine.Read, Call: 20, Output: 1, Return: 25},
}
ok := porcupine.CheckOperations(porcupine.RegisterModel, history)
// ok == false

The read at 20 must see the latest write (2, completed at 15), but it returns 1. Porcupine catches it. Run this against your system by recording real client operations with timestamps.

Partition test. Block traffic between primary and replica: iptables -A INPUT -s <replica_ip> -j DROP on primary, and vice versa. Then run writes and reads. For etcd 3.5 with --consistency=linearizable, writes fail once quorum is lost (3-node cluster, 1 node isolated: quorum lost). For Cassandra 4.0 with CONSISTENCY ONE, writes succeed but reads may return stale data. Observe which errors surface and what the client sees.

Failover test. Promote replica: pg_ctl promote. Measure time to promotion (e.g., 2-10 seconds). Check for lost writes: compare pg_last_wal_replay_lsn() on replica before promotion with pg_current_wal_lsn() on primary. If they differ, acknowledged writes were lost. Set synchronous_commit = remote_apply to avoid.

Cold and unavailable cache. Flush Redis: redis-cli FLUSHALL. Run read-your-writes test. Then stop Redis: redis-cli SHUTDOWN. Observe if reads fall back to database or fail. Both change the consistency picture.

Linearizability checker for critical components. Use Jepsen with elle for transactional isolation or knossos for single-object linearizability. Run against a 5-node etcd cluster with --consistency=linearizable. Jepsen records a concurrent history and checks it.

TestTool/SettingPassFail
Read-your-writestc netem delay 500msWrite visible immediatelySELECT returns None
LinearizabilityPorcupine CheckOperationstruefalse for concurrent writes
Partitioniptables -A INPUT -s ... -j DROPQuorum writes failWrites succeed but reads stale
Failoverpg_ctl promoteNo data lossAcknowledged writes lost

All tests must run against a realistic topology. A single-node environment cannot exhibit replication lag, partitions, or failover. That gap is usually discovered during the first real partition.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Explain what you would monitor to detect consistency problems.

Answer

A stale read returns a plausible value with no error, so error rates and latency percentiles tell you nothing about consistency. You have to monitor the mechanisms that produce convergence, and you have to measure staleness directly with a synthetic probe, because every indirect signal can lie.

SignalSourceWhat it catchesExample alert
Replication lagMySQL SHOW REPLICA STATUS → Seconds_Behind_Source; Percona pt-heartbeatReplica stalenessp99 > 1 s for 5 min
WAL replay lagPostgres pg_stat_replication: replay_lag minus write_lagApply backlog, isolated from network delayreplay_lag > 2 s
Replica offset gapRedis INFO replication: master_repl_offset − slave_repl_offsetBacklog in bytes> 1 MB
Read repairCassandra JMX type=ReadRepair: ReadRepairAttempted, ReadRepairRepairedBackgroundDivergence being repaired on the read pathrepaired/attempted ratio rising
Anti-entropyCassandra system.repair_history, nodetool statushandoffConvergence machinery silently failingno successful repair in > gc_grace_seconds
Cross-region replicationDynamoDB global tables: ReplicationLatency, PendingReplicationCountGlobal-table stalenessReplicationLatency > 1 s
Derived-store driftElasticsearch _count vs source SELECT count(*)Index/DB divergence> 0.1% mismatch
Consumer lagKafka records-lag-max JMX, kafka-consumer-groups --describe LAGCDC and rollup pipelines> 10k records
Split brainpg_is_in_recovery() on both nodes; MySQL gtid_executed on bothTwo writers accepting writesany occurrence

The probe. Indirect signals can all be green while reads are stale, so write a token to the primary and read it back from every replica, recording how long each took to serve it:

Python
import time, redis  # redis-py 5.x

primary = redis.Redis(host="primary", port=6379, decode_responses=True)
replicas = [redis.Redis(host=h, port=6379, decode_responses=True)
            for h in ("replica-a", "replica-b", "replica-c")]

def probe(i, budget=5.0):
    key, token = f"probe:{i}", str(time.time_ns())
    primary.set(key, token)
    t0, seen = time.monotonic(), {}
    while len(seen) < len(replicas) and time.monotonic() - t0 < budget:
        for idx, rep in enumerate(replicas):
            if idx not in seen and rep.get(key) == token:
                seen[idx] = time.monotonic() - t0
        time.sleep(0.005)
    return seen   # {replica index: seconds until it served the write}

A replica missing from the returned dict never served the write inside the budget: that is the divergence signal. Report p99 per replica; alert when a replica is absent from more than 0.1% of probes. Distinguish "replica unreachable" from "replica stale", or a network partition looks like a consistency failure and a failed probe looks like success.

Deriving the threshold. Don't pick 10 s because it's round. Take the read-your-writes requirement: a user writes, then their next request may land on a replica. Say access logs show the median write-to-next-read gap is 1.2 s and p99 is 4 s. Promising read-your-writes to 99% of users means replica lag p99 must stay under 1.2 s, so alert at 1 s. Promising it to 99.9% gives a 4 s budget and a 3 s alert. The number comes from traffic, not taste.

Traps that make these signals lie. Seconds_Behind_Source (MySQL 8.0.22+; Seconds_Behind_Master before) is derived from the timestamp of the last event the SQL thread applied, if the primary is idle it reads 0 while the replica is arbitrarily far behind. Postgres pg_last_xact_replay_timestamp() returns NULL on an idle primary for the same reason. A heartbeat fixes both: pt-heartbeat writes a row carrying the primary's timestamp every second, so the replica always has something to be behind on. In pg_stat_replication (PG 10+), write_lag is time to reach the standby's WAL receiver and replay_lag is time to become visible to queries; the difference is apply backlog, and a network-only alert misses it. Elasticsearch refreshes every 1 s by default (index.refresh_interval), so a search index is up to 1 s behind by design: alert on drift persisting past the refresh interval, not on the interval itself. In Cassandra, if nodetool repair hasn't completed within gc_grace_seconds (default 864000 s, 10 days), a replica that never saw a tombstone can resurrect deleted data; alert on repair age, not just repair failure.

Write-side guard. Redis min-replicas-to-write 1 with min-replicas-max-lag 10 refuses writes when no replica has acknowledged within 10 s, which converts silent staleness into a visible error. Use it where losing read-your-writes is worse than failing the write.

User reports. Tag "my change disappeared" tickets as a category and correlate them with lag spikes; they are often the earliest evidence of a defect the technical signals haven't crossed a threshold on yet.

Monitor the mechanisms, not the outcomes. By the time a wrong value is served, the divergence has been present for a while and something downstream has already consumed it.

Curated: · Written: · Reviewed:

Difficulty: Hard