Distributed systems: consensus, replication, consistency, idempotency, queues, caches, and failure handling

Exactly-once delivery does not exist; at-least-once plus idempotent consumers does. Quorums are odd, replication mode is your RPO, and unbudgeted retries turn a slowdown into an outage.

Read the briefing
About 4 min to read 8 drills

What to remember

  1. 3 or 5 nodes, never 4. Majority of 4 is 3 — same tolerance, more cost, worse partition behaviour.
  2. Replication mode is your RPO. Async failover loses the lag window. Decide per data class and monitor the lag.
  3. Write the idempotency key before the side effect. Then a retry can ask what happened instead of doing it twice.
  4. An unbounded queue converts overload into unbounded latency. Bound it, shed at admission, and drop work whose deadline has passed.
  5. Retries need jitter and a budget or they amplify. Three layers of three attempts is 27× load on the thing that is already failing.

The big picture

The distributed-systems round tests whether you can reason about failure between machines: quorums and what happens when you lose one, synchronous versus asynchronous replication and the data you lose on failover, consistency models and what clients can observe, why exactly-once delivery is a myth and idempotency is the answer, and the resilience trio of timeouts, retries with backoff, and circuit breakers that stops one slow dependency from taking down everything.

The mental model

Every remote call can be slow, lost, duplicated, or reordered, and the acknowledgement can be lost after the work succeeded. Design so each of those is survivable: quorums for agreement, replication choices for durability, idempotency for duplicates, bounded queues and timeouts for slowness, and a consistency model you can state in terms of what a client sees.

In depth

Consensus, replication, and consistency

Consensus (Raft, Paxos) commits when a majority acknowledges: 3 nodes tolerate 1 failure, 5 tolerate 2, and even sizes add cost without tolerance (4 nodes still tolerate only 1). Every write pays a round trip to a majority, so a quorum stretched across continents pays ~100 ms per write; losing quorum stops writes, which is the deliberate choice of consistency over availability. Replication outside consensus is a spectrum: synchronous (acknowledge after replicas persist: no data loss on failover, higher latency, and your availability now depends on the replica), asynchronous (fast, but replication lag is exactly the window of writes you lose when the primary dies), and semi-synchronous (wait for one of N: a common compromise). Consistency: linearizable means every read sees the latest acknowledged write; eventual means replicas converge later; read-your-writes and monotonic reads are the practical middle that keeps users from seeing their own actions disappear. CAP says a partitioned system must choose consistency or availability; PACELC adds that even without a partition you choose between latency and consistency, which is the choice you actually make every day.

Idempotency, queues, and backpressure

Exactly-once delivery across a network is impossible in general: the sender cannot distinguish a lost request from a lost acknowledgement, so it must retry, so duplicates happen. What is achievable is exactly-once effects: at-least-once delivery plus idempotent consumers, implemented with an idempotency key supplied by the client, a dedup table keyed by a stable identity, or upserts that are naturally repeatable. Payments, transfers, and on-chain submissions all live or die by this.

Queues absorb bursts, but an unbounded queue converts overload into unbounded latency and memory exhaustion, and then delivers work whose deadline has already passed. Backpressure is the discipline of bounded queues, rejecting or shedding at admission, consumer-driven flow control, and dropping stale work (deadline propagation): fail fast, stay responsive for what you can actually serve. Queue depth and age are the two metrics to alert on; a queue that never drains is a capacity problem wearing a buffer costume.

Caching and the resilience trio

Caches trade freshness for latency and load. Invalidation is hard because the cache does not observe writes; the tools are TTLs, write-through or explicit invalidation, and protection against stampedes (request coalescing/single-flight, jittered TTLs, early refresh) and hot keys. A cache the system requires to serve traffic is a database with worse durability guarantees: size and fail-over accordingly.

Timeouts, retries, circuit breakers. A timeout bounds how long you wait (and must be shorter than your caller's, with deadlines propagated). Retries recover transients only with jittered exponential backoff and a retry budget (for example, retries capped at 10% of requests): naive retries multiply load exactly when a dependency is struggling, which is how a slow dependency becomes a cascading failure through exhausted thread pools and connection pools. Circuit breakers stop calling a failing dependency, return a fallback quickly, and probe for recovery. Add bulkheads (separate pools per dependency) so one slow dependency cannot consume every thread, and load shedding at the entrance so the system sheds deliberately rather than collapsing.

Myths and facts

Myth: A 4-node cluster tolerates more failures than a 3-node one.

Fact: Both tolerate one failure (majority of 4 is 3); even sizes add cost and no tolerance.

Myth: Exactly-once delivery is achievable with the right message broker.

Fact: Delivery cannot be exactly-once across a network; brokers give exactly-once effects through deduplication and transactional writes, which is idempotency by another name.

Myth: Retries make the system more reliable.

Fact: Unbudgeted retries amplify load during failures; use jittered backoff, a budget, and circuit breakers.

Myth: Asynchronous replication is fine because failover is automatic.

Fact: Automatic failover with async replication loses every write in the replication lag window; decide whether that is acceptable and measure the lag.

Myth: Adding a queue fixes overload.

Fact: An unbounded queue converts overload into latency and memory exhaustion; bounded queues plus shedding is the fix.

How pros do it

  • Size quorums odd (3 or 5) and keep them within a region unless the write latency is acceptable.
  • State your replication mode and measure lag; know exactly what a failover loses.
  • Make every write path idempotent with a client-supplied key or a dedup table; assume duplicates.
  • Bound every queue, propagate deadlines, drop stale work, and alert on queue age.
  • Timeouts shorter than the caller's, jittered backoff with a retry budget, circuit breakers, and bulkheads per dependency.

Questions people ask

Why 3 or 5 nodes, never 4?

Majority of 4 is 3, so it tolerates one failure just like 3 nodes, while costing more and making network partitions more likely to lose quorum.

Explain CAP in practice.

Pick a concrete system and a partition: the node cut off from the majority either stops answering (consistent but unavailable) or answers with possibly stale data (available). Say what the client sees in each case, that quorum systems choose to stop the minority and that this is the split-brain protection, then add PACELC — with no partition you still trade latency for consistency, which is the choice you actually make every day.

How do I choose between sync and async replication?

Ask what a failover may lose. Zero tolerance means synchronous or semi-sync (paying latency and coupling availability to replicas); a bounded loss means async with lag monitoring and alerting.

What is a retry budget?

A cap on retries as a fraction of total requests (commonly 10%), enforced client-side, so a struggling dependency is not hit with multiplied traffic.

What does read-your-writes buy me?

Users never see their own action disappear, which is most of the perceived correctness of an eventually consistent system; implement with sticky routing or by reading from the primary for a short window after a write.

How do I prevent a cache stampede?

Single-flight/request coalescing so one miss populates for all waiters, TTL jitter so keys do not expire together, and early asynchronous refresh for hot keys.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

How many node failures can a 5-node Raft cluster tolerate while still committing writes, and what happens beyond that?

  1. Two: a majority of 3 must acknowledge. With three nodes down there is no quorum, so writes stop (reads may be served stale depending on configuration) rather than risking split brain. Majority quorum is ⌊n/2⌋+1 = 3; losing quorum halts writes by design.
  2. Three, if the remaining two are in the same zone. Quorum is by node count, not zone adjacency.
  3. Two, and beyond that the cluster elects a new leader among survivors and continues. A minority cannot elect a leader; that is exactly what prevents split brain.
  4. Four, since only one node needs to hold the data. Consensus requires a majority to agree, not one surviving copy.
In short

Two failures: three of five nodes must agree, and with only two left the cluster stops writes instead of risking split brain.

Why

Halting on quorum loss is a feature: it chooses consistency over availability during partitions. The operational consequence is that quorum placement (zones, regions) determines both write latency and what failure takes the system down.

The common mistake

Saying the survivors 'elect a new leader and carry on'. A minority cannot elect a leader; that is the whole point.

Read the docs

2 Pick the strongest answer

The interviewer says: "Explain the CAP theorem in practice, not the textbook version." Your example is a three-replica order store behind a load balancer, and a network partition has just cut one replica off from the other two. What does CAP actually force you to choose here, and what does PACELC add?

  1. CAP means a consistent system cannot be highly available, so a 99.99% target forces eventual consistency. The trade-off applies only during a partition and only to the cut-off side; a quorum system stays consistent and available on the majority side, and its nines depend on how often it loses quorum, not on CAP.
  2. With three replicas the partition cannot matter: the load balancer stops routing to the isolated replica and nothing else changes. The balancer may not see the same partition the replicas do, and the isolated replica still has to decide what to do with requests that reach it — including from clients on its side of the split.
  3. You pick two of the three properties at design time; most teams drop partition tolerance and keep consistency and availability. Partitions are not optional on a real network. The only design decision is how the system behaves when one happens.
  4. The choice is about what the cut-off replica does. It can refuse reads and writes until it rejoins (consistent: every answer it gives is current, but it is unavailable to clients on its side), or it can keep answering (available: possibly stale reads, and writes that must be reconciled later). The majority side keeps serving consistently either way, which is why quorum systems choose to stop the minority — that is the split-brain protection. PACELC adds that with no partition at all you still trade latency for consistency: a linearizable read costs a quorum round trip that a local read does not. CAP constrains one moment — a node that cannot reach a majority during a partition — and PACELC names the latency-versus-consistency choice made on every request the rest of the time.
In short

During a partition the cut-off replica must either stop answering (consistent) or answer with possibly stale data (available); with no partition you still trade latency for consistency.

Why

CAP is a statement about one moment: when a partition exists, a node that cannot reach a majority must choose between answering (available, possibly stale or conflicting) and refusing (consistent, unavailable). Quorum systems such as Raft-backed stores choose consistency: the minority side stops, the majority side carries on, and that is what prevents split brain. Eventually consistent stores choose availability and reconcile afterwards. The practical answer names the system, names which side of the partition you are on, and says what a client observes. PACELC is the everyday half: even with no partition, a linearizable read costs a quorum round trip, so you trade latency for consistency on every request — which is why the follow-up is usually "and which reads in your system actually need to be linearizable?"

The common mistake

Saying "pick two of three" and choosing to drop P. Partitions happen whether you like them or not; the only design decision is how the minority side behaves when one does.

3 Read the output

Describe the failure mode and the two changes that would have contained it.

# service A calls service B; B's p99 rose from 80ms to 3s at 14:02
14:02  B p99: 3s          A threads busy: 40/200   A rps in: 900   A errors: 0.1%
14:04  B p99: 6s          A threads busy: 170/200  A rps in: 910   A errors: 0.4%
14:06  B p99: 9s          A threads busy: 200/200  A rps in: 905   A errors: 38%
14:06  A queue depth: 4200 (unbounded)   A retries to B: 3x per request, no backoff
14:08  C (calls A) starts timing out; C retries A 3x
14:10  B rps in: 2700 (3x)  B p99: 20s
  1. C should stop calling A during incidents. Not a mechanism; C needs the same timeout/breaker discipline.
  2. A has a thread leak; restart A. Threads are blocked on a slow dependency, not leaked.
  3. A cascading failure: B slowed, A's threads all blocked on B, A's unbounded queue grew, A's un-backed-off retries tripled load on B, and C's retries tripled it again. Containment: bound A's concurrency to B (bulkhead + circuit breaker with a fast fallback) and replace blind retries with jittered backoff under a retry budget, plus a bounded queue that sheds. Every line is the textbook amplification chain; the fixes are concurrency isolation and retry discipline.
  4. B is undersized; add capacity to B. Capacity may help but the amplification (3× then 9×) is what turned a slowdown into an outage.
In short

It is a cascading failure from unbudgeted retries and an unbounded queue; fix it with a bulkhead and circuit breaker around calls to B and with jittered, budgeted retries.

Why

Cascading failure has a signature: a dependency slows, callers' concurrency saturates, queues grow unbounded, retries multiply load, and the amplification propagates upstream. The fixes are structural: bulkheads and circuit breakers to bound the damage, jittered backoff with a budget to stop amplification, bounded queues with shedding, and deadline propagation so stale work is dropped.

The common mistake

Diagnosing B as undersized or A as leaking threads. The signature is amplification: 3× retries at A and 3× at C turned 900 requests into 2,700 at B and can reach nine calls per user request.

Read the docs

4 Answer out loud

You are designing a write path that must not double-charge users and must survive a dependency being slow. Explain your consistency and durability choices, how you guarantee exactly-once effects, and how you stop a slow dependency from cascading. Five to seven sentences.

In short

A strong answer writes the idempotency key before the side effect, states the replication mode as the RPO, and bounds slow calls with deadlines, budgeted retries and a circuit breaker.

What a strong answer does
  • correctness: Client-supplied idempotency key recorded before the effect, dedup on stable identity, at-least-once plus idempotent consumer; explicit durability (sync/semi-sync) and stated RPO; deadlines, jittered backoff with budget, circuit breaker, bulkhead, shedding.
  • judgment: Chooses per data class, names the latency cost of synchronous durability, states what the client observes (read-your-writes) and what happens during a partition.
  • communication: Write path narrated step by step with the failure at each step and the mechanism that covers it.
Why

Staff answers make the idempotency identity exist before the side effect, state the RPO as a decision, and cover slowness with concurrency isolation rather than with more retries.

The common mistake

Saying 'use transactions' or 'use a broker with exactly-once delivery'. Delivery cannot be exactly-once across a network; effects can, through a client-supplied key recorded before the effect and dedup on a stable identity.

5 Pick the strongest answer

A service submits blockchain transactions on behalf of users. The RPC call times out, but the transaction may have been broadcast. What design makes this safe?

  1. Use a message broker with exactly-once delivery. No broker provides exactly-once across a network boundary to an external chain; the consumer must be idempotent.
  2. Idempotent submission: derive a deterministic identity for the intent (a client-supplied key or the signed transaction hash), record it before broadcasting, and on retry check whether that identity was already submitted or confirmed instead of building a new transaction. Duplicates are inevitable; a stable identity plus a dedup record converts at-least-once delivery into exactly-once effects.
  3. Do not retry; report failure to the user. Loses legitimately failed submissions and pushes the ambiguity onto the user.
  4. Retry with a fresh nonce so the second attempt definitely lands. That risks two transactions executing: the classic double-spend of user intent.
In short

Make submission idempotent: record a stable identity for the intent before broadcasting, and on retry check that identity instead of building a new transaction.

Why

Any workflow with external side effects needs a stable identity established before the effect, and a check on that identity when retrying. The signed transaction's hash is a natural key: rebroadcasting the same signed transaction is idempotent, while rebuilding it with a new nonce is not.

Read the docs

6 Find what's broken

A team hands you this client config for review before a launch. Which settings will turn a slow dependency into an outage, and how do you fix each one?

client:
  connect_timeout: 30s
  request_timeout: 60s          # caller's own deadline is 5s
  retries:
    attempts: 5
    backoff: fixed 100ms
    budget: unlimited
  circuit_breaker: disabled
queue:
  type: in_memory
  max_size: unbounded
  drop_stale_after: never
cache:
  ttl: 300s                     # every key written at deploy time
  on_miss: fetch_from_origin
  single_flight: false
In short

Five settings are dangerous: unbudgeted fixed retries, an unbounded queue, no circuit breaker, a timeout longer than the caller's deadline, and a cache with no single-flight and a uniform TTL.

What's broken
  • Line 6: Five retries with fixed 100 ms backoff and no budget: a struggling dependency receives 5× traffic almost instantly, with all retries synchronized.
  • Line 11: An unbounded in-memory queue turns overload into unbounded latency and eventual OOM, and never drops work whose deadline has passed.
  • Line 16: No single-flight with a uniform TTL means every key expires together and every miss hits the origin: a synchronized stampede every 300 s after deploy.
  • Line 3: A 60 s request timeout is longer than the caller's own 5 s deadline, so work continues on requests nobody is waiting for.
  • Line 8: The circuit breaker is disabled, so once the dependency is failing every request still waits out the full timeout and retry sequence: nothing fails fast, nothing probes for recovery, and the thread pool drains into a dependency that cannot answer.
Why

The connect timeout is generous but harmless, the cache TTL value itself is reasonable, and fetching from origin on a miss is normal. The dangerous five: retries that multiply load exactly when the dependency is failing; an unbounded queue that converts overload into latency and memory exhaustion; no circuit breaker, so the client keeps pouring requests into a dependency that is already failing instead of failing fast with a fallback; a request timeout longer than the caller's own deadline, so threads work on requests nobody is waiting for; and a cache whose keys all expire together with no request coalescing. Retries, the queue and the missing breaker are the amplification chain of a cascading failure; the timeout and the cache make it worse and slower to recover.

Read the docs

7 Scenario: what do you do next?

Your primary Postgres failed over automatically at 03:00. The service is up, but support reports that a handful of customers' recent actions "did not happen", and one customer sees an order that no longer exists. Replication was asynchronous with a typical lag of 2–4 seconds.

Step 1. First action?

  1. Disable failover so it cannot happen again. Removes recovery capability rather than addressing the durability choice.
  2. Tell customers it was a glitch and ask them to retry. Before knowing what was lost, and it risks duplicates for actions that did succeed.
  3. Fail back to the old primary immediately. Split brain risk: writes have gone to the new primary since promotion.
  4. Establish the data loss window: compare the promoted replica's last applied LSN against the old primary's last written position (if reachable), and identify writes acknowledged after that point; freeze anything that would compound the divergence, such as automatic re-syncs that discard evidence. Async failover loses the lag window by design; the size and content of that window is the first fact.

Step 2. About 6 seconds of writes were lost (the lag spiked during the failure): 40 orders and some profile edits. What now?

  1. Switch all writes to synchronous replication immediately during the incident. A durability change under pressure, with a latency and availability impact nobody has evaluated.
  2. Restore from last night's backup to get the orders back. That would lose everything since the backup; the lost window is 6 seconds, not a night.
  3. Ask customers to re-place their orders without saying what happened. Dishonest and produces duplicates.
  4. Recover what you can from upstream sources of truth (application logs, the payment provider, event stream) and reconcile idempotently; notify affected customers with specifics; then decide whether the durability model should change. Reconstruct from other records where possible, communicate honestly, then revisit the design decision the loss exposed.

Step 3. Design decision afterwards?

  1. Make everything synchronous across three zones. Pays write latency and couples availability to replicas for data that does not need it; decide by class.
  2. Choose deliberately per data class: semi-synchronous (wait for one replica) for orders and payments so failover loses nothing, async acceptable for low-value data; alert on replication lag with a threshold tied to the tolerable loss; make writes idempotent so replays are safe; and document the RPO. Turns an implicit RPO into an explicit one per data class, with monitoring and a replay-safe design.
  3. Keep async and accept the loss silently. The loss was invisible to the business until customers found it; at minimum it must be explicit and monitored.
In short

Measure the lost write window first, then rebuild lost data from other sources and tell customers, then choose sync or async replication per data class.

Why

This is the interview's favourite way to test whether you understand that replication mode is your RPO. The strong answer establishes the window, reconstructs from other sources, communicates honestly, and then sets durability per data class with lag alerting.

Read the docs

8 Quick recall

Since exactly-once delivery is impossible, what property must consumers have so at-least-once delivery is safe?

In short

Consumers must be idempotent.

Accepted

idempotency · idempotent · idempotence

Why

At-least-once delivery plus idempotent consumers (idempotency keys, dedup tables, upserts) yields exactly-once effects.

That's the last lesson in mission 05 Pick your next mission
Drill · Distributed systems
0:00

Loading…