← tonia.ai

Distributed systems · consistency and replication

Copies that agree

Keeping several copies of data is the standard way to survive failures and serve users quickly. The hard part is what happens between copies. A consistency model is a contract stating which values a read may return while updates are still propagating. This page covers how replicas are organized, the main consistency models, quorums, and how systems repair divergence and resolve conflicts.

Why replicate

  • Availability: if one copy is unreachable, another can answer.
  • Latency: a copy near the user avoids a cross-continent round trip.
  • Read throughput: many copies can serve reads in parallel.

The cost falls on writes. Every update must reach every copy, and until it does, copies disagree. Replication improves reads and resilience, but it raises write latency and coordination work, and the cost grows with the number of replicas and the strength of the consistency promised. More replicas do not make everything faster.

Who accepts writes

Single-leaderMulti-leaderLeaderless writes L L1 L2 client one write path, simple orderingleader is a bottleneck writes in every regionconcurrent writes conflict no failover neededquorums and repair required
ArchitectureHow writes flowGood forExamples
Single-leader (primary–replica)All writes go to one node, which streams a log of changes to followersRead-heavy workloads; simple consistencyPostgreSQL, MySQL, Redis
Multi-leaderSeveral nodes accept writes and exchange them asynchronouslyMulti-region writes, offline clientsCouchDB, collaborative editors
LeaderlessClients (or a coordinator) write to several replicas directlyHigh write availabilityCassandra, Dynamo, Riak
Consensus-basedA leader replicates a log; entries commit once a majority store themStrong consistency with automatic failoveretcd, CockroachDB, Spanner

Sync, async, and lag

With synchronous replication, the leader waits for followers to confirm before acknowledging a write. No acknowledged write is lost if the leader dies, but one slow follower stalls every write. With asynchronous replication, the leader acknowledges immediately and ships changes in the background. Writes are fast, but followers lag behind and a leader crash can lose recent writes. Many systems compromise: one synchronous follower, the rest asynchronous.

clientleaderfollower write name="Ana" ok change still in transit read name "old name" replication lag
The user saved a change and immediately saw the old value. The write isn't lost; it hasn't arrived yet. Lag is usually milliseconds but can grow to minutes under load or after a failure.

Consistency models

Data-centric consistency models describe what every client can observe, ordered from strongest to weakest.

Linearizability
The system behaves like a single copy. Each operation appears to take effect at one instant between its call and its return, so real-time order is respected.
Sequential consistency
All clients see operations in one total order that respects each client's own program order, but not necessarily real time.
Causal consistency
Operations related by happened-before are seen in that order everywhere; concurrent operations may appear in different orders on different replicas.
Eventual consistency
If updates stop, replicas eventually converge. Nothing is promised about reads in the meantime.

"Strong consistency" is an informal phrase; linearizability is the precise term. The difference between linearizable and sequential is real time, as this history shows:

client Aclient B write(x = 1) read(x) → 0 write finished here Sequential: OK (order "B reads, then A writes" is a legal total order) Linearizable: violation (the read began after the write completed) linearizable sequential causal FIFO (PRAM) eventual ← stronger guarantees, simpler to program higher availability, lower latency →

Linearizability is what makes locks, leader election, and unique constraints safe, and it costs coordination on every operation. Causal consistency is about as strong as a model can be while every replica stays available during a network partition, which makes it a popular target for geo-replicated systems.

PapersHerlihy & Wing, "Linearizability: A Correctness Condition for Concurrent Objects," ACM TOPLAS 12(3), 1990 · Lamport, "How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs," IEEE Trans. Computers, 1979 · Ahamad et al., "Causal Memory," Distributed Computing 9(1), 1995 · Viotti & Vukolić, "Consistency in Non-Transactional Distributed Storage Systems," ACM Computing Surveys 49(1), 2016
ExploreJepsen consistency models map

Client-centric guarantees

Many applications don't need global agreement. They need each user's own view to make sense. Session guarantees, introduced with the Bayou system, give exactly that on top of eventually consistent replicas:

GuaranteePromise to one clientPrevents
Read your writesA read reflects all of the client's earlier writesSaving a profile and seeing the old one
Monotonic readsLater reads never see older data than earlier readsA comment appearing, then vanishing on refresh
Monotonic writesThe client's writes are applied in the order issuedAn edit overwritten by the client's own earlier edit
Writes follow readsA write is ordered after the writes the client read before itA reply visible before the post it answers

Typical implementations route a user's reads to the replica that took their writes, or attach a version token to each session and only read from replicas that have caught up to it.

PapersTerry et al., "Session Guarantees for Weakly Consistent Replicated Data," PDIS 1994 · Vogels, "Eventually Consistent," CACM 52(1), 2009

Quorums

In a leaderless system with N replicas, a write succeeds once W replicas confirm it, and a read queries R replicas and keeps the newest version it sees. If R + W > N, every read set overlaps every write set, so a read always reaches at least one replica holding the latest acknowledged write.

write v2 acknowledged by W = 3 v2v2v2v1v1 read queries R = 3 → newest is v2 R + W = 6 > N = 5, so the sets always share at least one replica
Setting (N = 3)Effect
W = 2, R = 2Overlapping quorums; tolerates one slow or failed replica for both reads and writes
W = 3, R = 1Fast reads; any replica failure blocks writes
W = 1, R = 3Fast writes; any replica failure blocks reads
W = 1, R = 1Fastest and most available; reads may be stale

Overlap alone does not make a system linearizable. Concurrent writes, failed writes that partially succeeded, and sloppy quorums (accepting writes on stand-in nodes during failures, then handing them back later) can all expose stale or out-of-order values. In practice, measurements show that even non-overlapping settings are usually fresh within milliseconds, which is why many deployments accept the risk.

PapersGifford, "Weighted Voting for Replicated Data," SOSP 1979 · DeCandia et al., "Dynamo," SOSP 2007 · Bailis et al., "Probabilistically Bounded Staleness for Practical Partial Quorums," PVLDB 5(8), 2012

Repairing divergence

Replicas drift apart whenever a write misses some of them. Three mechanisms bring them back together:

  • Read repair: when a read sees replicas with different versions, it writes the newest version back to the stale ones.
  • Hinted handoff: a node that accepted a write for an unreachable replica keeps a "hint" and delivers it when that replica returns.
  • Anti-entropy: replicas periodically compare their contents in the background. Comparing Merkle trees (hash trees over key ranges) lets two replicas find differences by exchanging a few hashes instead of all their data.

PapersDemers et al., "Epidemic Algorithms for Replicated Database Maintenance," PODC 1987 · Merkle, "A Digital Signature Based on a Conventional Encryption Function," CRYPTO 1987

Resolving conflicts

When two replicas accept different writes to the same item concurrently, the system must pick a result. The options range from simple and lossy to precise and more complex.

StrategyHowTrade-off
Last writer winsKeep the write with the highest timestampSimple; silently discards concurrent writes and depends on clocks
Version vectors with siblingsDetect concurrency and keep every concurrent version for the application to mergeNothing lost; application must write merge logic
Operational transformationRewrite concurrent edits so they apply cleanly in any orderWorks well for text; usually needs a central server
CRDTsData types whose merge is mathematically guaranteed to convergeAutomatic convergence; limited to suitable types and has metadata overhead

A conflict-free replicated data type (CRDT) defines a merge that is commutative, associative, and idempotent. Replicas can then exchange state in any order, any number of times, and still converge. A grow-only counter is the simplest example:

replica 1 · total 4 A:3 B:0 C:1 replica 2 · total 7 A:2 B:4 C:1 merge A:3 B:4 C:1 element-wise max · total 8 same result in any order, any number of times
Each replica only increments its own entry, so taking the maximum never loses an increment. Sets, registers, maps, and text sequences have CRDT versions too.

PapersTerry et al., "Managing Update Conflicts in Bayou," SOSP 1995 · Shapiro et al., "Conflict-Free Replicated Data Types," SSS 2011 · Kleppmann et al., "Local-First Software," Onward! 2019

Choosing a point

CAP says that during a network partition a replicated system must choose between answering every request (availability) and never returning stale data (linearizability). PACELC adds the everyday case: even with no partition, stronger consistency costs latency, because replicas must coordinate before answering.

The choice can be made per operation. A shop can read its catalog from any replica while checking out against a linearizable inventory count. Systems like Cassandra, DynamoDB, and MongoDB expose this as a per-request setting.

-- Cassandra: choose consistency per statement (N = 3)
CONSISTENCY ONE;     -- fastest; may read stale data
CONSISTENCY QUORUM;  -- 2 of 3; R + W > N when both use QUORUM
CONSISTENCY ALL;     -- every replica; any failure blocks

Eventual consistency guarantees convergence only once updates stop. Under a steady stream of writes, replicas can stay out of sync indefinitely. If the application must be correct during that window, it needs a stronger model or a CRDT.

PapersBrewer, "CAP Twelve Years Later," IEEE Computer 45(2), 2012 · Abadi, "Consistency Tradeoffs in Modern Distributed Database System Design," IEEE Computer 45(2), 2012
DocsDynamoDB read consistency · MongoDB read concern

In practice

Cassandra and DynamoDB

leaderlesstunable quorums

Cassandra adopted Dynamo's design: consistent hashing, configurable N, R, and W, hinted handoff, read repair, and Merkle-tree anti-entropy. The managed DynamoDB service later moved to leader-based replication within each partition, using Multi-Paxos. That offers both eventually consistent and strongly consistent reads with predictable latency.

Lakshman & Malik, "Cassandra: A Decentralized Structured Storage System," SIGOPS OSR 44(2), 2010 · Elhemali et al., "Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service," USENIX ATC 2022

Causal consistency at scale

geo-replication

COPS showed that a geo-replicated key-value store can provide causal consistency, plus convergence, while staying available and fast in every datacenter. Each write tracks the writes it depends on, and remote replicas delay applying it until those dependencies arrive.

Lloyd et al., "Don't Settle for Eventual," SOSP 2011

Spanner

consensus replicationexternal consistency

Each shard is replicated with Paxos across datacenters, and TrueTime timestamps order transactions globally. The result is linearizable reads and writes worldwide, at the cost of cross-region latency on writes.

Corbett et al., "Spanner," OSDI 2012

Tools and reading

Try it

  • PostgreSQL streaming replicationSet up a primary and replica, then measure lag under a write-heavy load.
  • CassandraRun three nodes, stop one, and compare reads at ONE and QUORUM.
  • Automerge and YjsCRDT libraries; edit the same document offline in two tabs and merge.
  • MaelstromWrite a replicated key-value store and test it against consistency checkers.
  • Jepsen consistency mapSee how the models relate and which survive partitions.

Read it