In leaderless replication, popularized by Amazon's Dynamo paper and used by Cassandra, Riak and ScyllaDB, any replica can accept reads and writes. Each key is stored on N replicas; a write succeeds after W acknowledgments and a read after R replies. When R + W > N, every read set overlaps every write set, so reads normally see the latest acknowledged write. Turning these three knobs lets you trade consistency, latency and availability per query, and the repair mechanisms (read repair, hinted handoff, Merkle-tree anti-entropy) keep replicas converging.
Think of it like
Witnesses and a notebook
A club records every decision in N members' notebooks, but only waits until W of them have written it down. Later, to recall a decision, you ask R members and trust the most recent entry among their answers. If R + W > N, at least one person you ask must have been there when it was written down, no matter which members you pick.
N, R and W
- N (replication factor)
- How many replicas store each key, typically 3. The replicas are the first N nodes clockwise on the hash ring: the key's preference list (see Consistent Hashing).
- W (write quorum)
- How many replicas must acknowledge a write before the client is told it succeeded. The write is still sent to all N.
- R (read quorum)
- How many replicas must respond before a read returns. The coordinator returns the newest version among the replies.
- Coordinator
- The node that receives the client request and fans it out. In Dynamo-style systems any node can coordinate any key.
With N = 3, W = 2, R = 2: a write lands on at least two of three replicas, a read asks at least two, and any two-element subsets of a three-element set share at least one element. Separately, W > N/2 ensures any two writes overlap, so conflicting concurrent writes are at least noticed by one replica. Use the simulation above to change N, R and W and watch when reads start returning stale values.
Quorum reads and writes in action
Tuning N, R and W
| Configuration | Reads | Writes | Overlap? | Tolerates | Good for |
|---|---|---|---|---|---|
| N=3, R=2, W=2 | Moderate | Moderate | Yes | 1 replica down for both | The common balanced default |
| N=3, R=1, W=3 | Fastest (one replica) | Slow, fails if any replica is down | Yes | Reads: 2 down. Writes: 0 down | Read-heavy, rarely written data |
| N=3, R=3, W=1 | Slow, fails if any replica is down | Fastest | Yes | Writes: 2 down. Reads: 0 down | Write-heavy data that is rarely read |
| N=3, R=1, W=1 | Fastest | Fastest | No (2 ≤ 3) | 2 down for both | Metrics, caches, anything that tolerates stale reads |
| N=5, R=3, W=3 | Moderate | Moderate | Yes | 2 replicas down for both | Higher durability and availability |
Why R + W > N is not linearizability
Quorum overlap is a strong hint of freshness, not a proof of linearizability (see Consistency Models). Several edge cases let stale or inconsistent reads slip through:
- Sloppy quorums can satisfy W with nodes outside the preference list, breaking the overlap.
- Concurrent writes to the same key must be resolved. With last-writer-wins by timestamp, one write is silently discarded, and clock skew can make the "older" write win. See Time, Clocks & Ordering.
- A read concurrent with a write may see the new value at one replica and the old at another; two readers can disagree about which is current.
- A failed write is not rolled back. If a write reached only one replica (W not met, client told it failed), later reads may or may not return it.
- Losing a replica that held the new value, and restoring it from a stale replica, can drop the number of up-to-date copies below W.
Keeping replicas in sync
Read repair
When a read sees replicas disagree, the coordinator pushes the newest version to the stale ones. It is cheap and targeted, but it only fixes keys that are actually read; cold data can stay inconsistent indefinitely.
Hinted handoff
When a replica is down, another node stores the write plus a hint and replays it when the replica returns. It speeds recovery from short outages, but hints are bounded: Cassandra stops collecting them after max_hint_window (3 hours by default), after which a full repair is needed.
Anti-entropy with Merkle trees
A background process compares replicas and fixes every difference, including cold keys. Comparing every key would mean shipping the whole dataset, so replicas exchange Merkle trees: each leaf is a hash of the keys in one token range, and each parent is the hash of its children. Equal roots mean the ranges are identical; otherwise descend only into children whose hashes differ.
- 1
Build
Each replica hashes its data per key range into leaves, then hashes pairs of nodes upward to a single root.
- 2
Compare roots
If the roots match, the replicas are in sync: one hash compared instead of gigabytes.
- 3
Descend
Where hashes differ, compare the two children. Matching subtrees are skipped entirely.
- 4
Stream
Only the leaf ranges that differ are exchanged and reconciled. Cost is roughly proportional to the number of differences times the tree height.
Cassandra runs this via nodetool repair; Riak calls it active anti-entropy. Teams schedule repairs regularly (within gc_grace_seconds in Cassandra) so deleted data's tombstones reach every replica before they are purged.
Conflicting versions
Last-writer-wins (LWW)
- Each value carries a timestamp; the highest wins
- Simple, and replicas always converge
- Concurrent writes are silently lost
- Clock skew can make an older write win
- Cassandra's default (per cell)
Version vectors + siblings
- Each value carries a version vector
- Concurrent versions are detected and both kept as siblings
- The application merges them (for example, union two carts)
- No silent data loss, more complexity
- Original Dynamo, Riak
CRDTs
- Data types whose merge is automatic and deterministic
- Counters, sets, maps, registers
- No conflicts to resolve by hand
- Limited to operations that fit a CRDT
- Riak data types, Redis Enterprise Active-Active
Consistency levels in Cassandra and DynamoDB
| Cassandra level | Replicas that must respond | Notes |
|---|---|---|
ANY (writes only) | 1 node, and a stored hint counts | Highest availability, weakest durability |
ONE / TWO / THREE | 1 / 2 / 3 replicas | ONE is the cqlsh default; recent drivers default to LOCAL_ONE |
LOCAL_ONE | 1 replica in the local data center | Avoids cross-DC hops |
QUORUM | ⌊(sum of RFs across DCs) / 2⌋ + 1 | Two DCs with RF 3 each: 4 of 6, so it crosses DCs |
LOCAL_QUORUM | Majority of replicas in the local DC | The usual choice for multi-DC: strong locally, no cross-DC latency |
EACH_QUORUM (writes) | A majority in every DC | Strong across DCs, slow |
ALL | Every replica | Any single replica down means failure |
SERIAL / LOCAL_SERIAL | Paxos among replicas | Linearizable compare-and-set (lightweight transactions) |
CONSISTENCY LOCAL_QUORUM;
INSERT INTO carts (user_id, items) VALUES (42, ['book', 'pen']);
SELECT items FROM carts WHERE user_id = 42; -- overlaps the write within this DC
-- Linearizable compare-and-set: Paxos under the hood
INSERT INTO usernames (name, user_id) VALUES ('ada', 42) IF NOT EXISTS;DynamoDB is not leaderless internally: each partition is replicated across three Availability Zones with a Multi-Paxos leader, and writes are acknowledged once a quorum persists them. Its knob is on reads: the default eventually consistent read can be served by any replica (half the read-capacity cost), while ConsistentRead: true goes to the leader and reflects all acknowledged writes.
Implementation
Fan out to all N replicas, return after the first W (or R) successes, and repair stale replicas on reads. Real systems use timestamps or vector clocks instead of a plain integer version.
import asyncio
from dataclasses import dataclass
@dataclass
class Versioned:
value: str
version: int
async def gather_quorum(coros, need: int, timeout: float = 0.5) -> list:
"""Return the first `need` successful results; fail fast if a quorum becomes impossible."""
tasks = [asyncio.ensure_future(c) for c in coros]
results, failures = [], 0
try:
for next_done in asyncio.as_completed(tasks, timeout=timeout):
try:
results.append(await next_done)
except Exception:
failures += 1
if len(tasks) - failures < need:
break
continue
if len(results) == need:
return results # stragglers keep running in the background
except asyncio.TimeoutError:
pass
raise RuntimeError(f"quorum not reached: {len(results)}/{need}")
async def quorum_write(replicas, key: str, v: Versioned, w: int) -> None:
await gather_quorum([rep.write(key, v) for rep in replicas], need=w)
async def quorum_read(replicas, key: str, r: int) -> Versioned | None:
async def ask(rep):
return rep, await rep.read(key)
replies = await gather_quorum([ask(rep) for rep in replicas], need=r)
newest = max((v for _, v in replies if v is not None), key=lambda v: v.version, default=None)
if newest is not None:
for rep, v in replies: # read repair
if v is None or v.version < newest.version:
asyncio.ensure_future(rep.write(key, newest))
return newestKey takeaways
- Leaderless stores write to N replicas, wait for W acks, and read from R replicas, returning the newest version.
- R + W > N guarantees read and write sets overlap; N=3, R=2, W=2 is the common balanced choice.
- Quorum overlap is not linearizability: sloppy quorums, concurrent writes and partial failures still produce anomalies.
- Read repair, hinted handoff and Merkle-tree anti-entropy keep replicas converging, each covering different gaps.
- Concurrent writes need a resolution policy: LWW (lossy), version vectors with siblings, or CRDTs.
- Cassandra's LOCAL_QUORUM gives strong reads within a data center without cross-DC latency.
Common pitfalls
- Assuming R + W > N means linearizable reads and building locks or unique constraints on it.
- Relying on last-writer-wins with unsynchronized clocks and losing writes silently.
- Never running anti-entropy repair, so cold data diverges and deleted data resurrects.
- Using QUORUM instead of LOCAL_QUORUM in multi-DC clusters and paying cross-region latency on every request.
- Forgetting that sloppy quorums can acknowledge writes that a later strict quorum read won't see.
Interview tips
- Explain the overlap with the pigeonhole argument and a concrete N=3 example.
- Offer different R and W choices for read-heavy and write-heavy paths in the same design.
- Mention all three repair mechanisms and when each one applies.
Real-world applications
- Cassandra and ScyllaDB clusters serving user data with per-query consistency levels.
- Riak and Dynamo-style shopping carts that merge concurrent versions.
- Distributed key-value stores; see Design a Distributed Key-Value Store.
- Object storage metadata and time-series stores that favor write availability.
Test yourself
With N = 3, which configuration guarantees that reads overlap the latest successful write?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.