Designing Data-Intensive ApplicationsParts I-III (complete book) · condensed, chapter by chapter
Chapter 5

Replication

Keeping a copy of the same data on several networked machines. Copying static data is easy; all the difficulty is in replicating changes. The chapter covers the three algorithms almost every distributed database uses: single-leader, multi-leader and leaderless.

Key takeaways

  • Replication buys high availability, disconnected operation, lower latency (data near users) and read scalability.
  • Single-leader: all writes go to one leader that streams changes to followers. Easy to reason about, no conflict resolution.
  • Synchronous vs asynchronous replication decides what happens on faults: promoting an async follower after leader failure can lose recently committed writes.
  • Failover is fraught: lost writes, split brain, and choosing the right timeout. Some teams prefer manual failover.
  • Replication lag breaks user expectations; the guarantees that fix it are read-after-write, monotonic reads and consistent prefix reads.
  • Multi-leader and leaderless tolerate faulty nodes, network problems and latency spikes better, but allow concurrent writes, so conflicts must be resolved and consistency is weak.
  • Quorums (w + r > n) make stale reads less likely, not impossible. Sloppy quorums are not quorums in the traditional sense.
  • Last write wins converges by silently dropping writes. Version vectors tell overwrites from concurrent writes so no data is lost.

Why replicate

  • Keep data geographically close to users (lower latency).
  • Keep working when some parts fail (higher availability).
  • Scale out the machines serving reads (higher read throughput).

Assumption for this chapter: the whole dataset fits on every machine. Partitioning comes in Chapter 6.

Key choices are often database config options: synchronous vs asynchronous, and how to handle failed replicas. The principles date from the 1970s because network constraints have not changed.

Leaders and Followers

Each node holding a copy is a replica. Every write must reach every replica. The most common solution is leader-based replication (also called active/passive or master–slave):

  1. One replica is the leader (primary). Clients send all writes to it; it writes to local storage first.
  2. The others are followers (read replicas, secondaries, hot standbys). The leader sends each change to them as a replication log or change stream; each follower applies writes in the leader's order.
  3. Reads can go to the leader or any follower; followers are read-only to clients.

Built into PostgreSQL (since 9.0), MySQL, Oracle Data Guard, SQL Server AlwaysOn Availability Groups; also MongoDB, RethinkDB, Espresso; and message brokers Kafka and RabbitMQ highly available queues. DRBD and some network filesystems are similar.

Writer client Reader client Leader Follower 1 Follower 2 Follower 3 write repl. log read (any replica)
Figure 5-1 (simplified): writes go only to the leader; followers apply its log in order; reads may go anywhere.

Synchronous Versus Asynchronous Replication

Example: a user updates a profile image. Client sends to leader; leader forwards to followers; leader eventually reports success.

  • Synchronous follower: leader waits for its confirmation before reporting success to the user and making the write visible.
  • Asynchronous follower: leader sends the change and does not wait.
  • Replication is usually under a second, but there is no bound: followers can fall minutes behind during recovery, near-capacity load, or network problems.
Client Leader Follower 1 Follower 2 update sync ack ok to user async, delayed time →
Figure 5-2 (simplified): the leader waits for follower 1 (sync) before replying; follower 2 (async) applies the change much later.
SynchronousAsynchronous
Up-to-date copyGuaranteed on follower; survives leader lossNot guaranteed; unreplicated writes lost if leader dies
Follower down/slowLeader must block all writesLeader keeps accepting writes
Durability of acked writeOn at least two nodesNot guaranteed even if confirmed to client
  • All-synchronous is impractical: any one outage halts the system.
  • Semi-synchronous: one follower synchronous, the rest asynchronous; if the sync one gets slow, an async one is promoted to sync. Guarantees an up-to-date copy on two nodes.
  • Fully asynchronous is common, especially with many or geographically spread followers, despite weakened durability.
  • Research: chain replication is a synchronous variant that avoids data loss with good performance (used in Microsoft Azure Storage). Replication consistency is closely tied to consensus (Chapter 9).

Setting Up New Followers

Needed to add replicas or replace failed nodes. Copying data files does not work (data is in flux); locking the database for writes defeats availability. Instead, without downtime:

1. Snapshot consistent, no lock 2. Copy to new follower 3. Request backlog since log position 4. Caught up stream live changes Snapshot tied to exact log position: PostgreSQL log sequence number, MySQL binlog coordinates
Adding a follower without downtime: snapshot, copy, replay the backlog from the snapshot's log position.
  • Snapshots are usually built in (needed for backups); sometimes third-party tools, e.g. innobackupex for MySQL.
  • Practical steps vary: fully automated in some systems, an arcane manual multi-step workflow in others.

Handling Node Outages

Nodes go down from faults or planned maintenance (e.g. a kernel security patch reboot). Goal: keep the whole system running and keep the impact of one outage small.

Follower failure: catch-up recovery. Each follower keeps a local log of changes received. After a crash or network break it knows its last processed transaction, requests all later changes from the leader, applies them, and is caught up.

Leader failure: failover. Promote a follower to leader, reconfigure clients to write to it, and make other followers consume from it. Manual or automatic. Automatic failover steps:

1. Detect failure timeout, e.g. 30 s no foolproof way 2. Choose leader election or controller most up-to-date wins 3. Reconfigure writes to new leader old leader → follower Risks: lost async writes · split brain · wrong timeout
Automatic failover. Agreeing on a new leader is a consensus problem (Chapter 9).

What goes wrong with failover:

  • With async replication the new leader may lack some old-leader writes. If the old leader rejoins, those writes may conflict; usually they are discarded, violating clients' durability expectations.
  • Discarding is worse when outside systems depend on the data. GitHub incident: an out-of-date MySQL follower was promoted; its lagging autoincrement counter reused primary keys that were also used in Redis, so private data was shown to the wrong users.
  • Split brain: two nodes both believe they are leader. If both accept writes without conflict resolution, data is lost or corrupted. Shutting one down (fencing, STONITH) helps, but a badly designed mechanism can shut down both.
  • Timeout: too long means slow recovery; too short means unnecessary failovers from load spikes or network glitches, which make an already struggling system worse.

No easy solutions, so some operations teams fail over manually even when automation exists. Node failures, unreliable networks and the consistency/durability/availability/latency trade-offs are fundamental (Chapters 8 and 9).

Implementation of Replication Logs

Statement-based replication. The leader logs each write statement (INSERT, UPDATE, DELETE); followers parse and execute it as if from a client. Breaks when:

  • Nondeterministic functions (NOW(), RAND()) give different values per replica.
  • Autoincrement columns or statements that depend on existing data (UPDATE … WHERE <condition>) must run in exactly the same order everywhere, limiting concurrent transactions.
  • Side effects (triggers, stored procedures, UDFs) differ unless fully deterministic.

Workaround: the leader substitutes fixed values for nondeterministic calls, but edge cases abound. MySQL used it before 5.1; it now switches to row-based on any nondeterminism. VoltDB uses it safely by requiring deterministic transactions. Its advantage: compactness.

Write-ahead log (WAL) shipping. Storage engines already append every write to a log (the LSM segments themselves, or a B-tree's WAL). The leader sends that same log to followers, which build identical data structures. Used in PostgreSQL and Oracle.

  • Downside: the WAL is very low level (which bytes changed in which disk blocks), so replication is coupled to the storage engine.
  • Leader and followers usually cannot run different versions, so upgrades need downtime. A protocol that allows newer followers enables zero-downtime upgrades: upgrade followers, then fail over to one.

Logical (row-based) log replication. A separate log format for replication, decoupled from storage internals: a logical log. For relational databases, records at row granularity:

  • Insert: new values of all columns.
  • Delete: enough to identify the row (primary key, or all old column values if none).
  • Update: row identity plus new values of all (or changed) columns.
  • A multi-row transaction produces several records plus a commit record. MySQL's binlog in row-based mode works this way.

Benefits: easier backward compatibility (different versions or even storage engines on leader and follower), and easy for external applications to parse, e.g. to feed a data warehouse or custom indexes and caches. That is change data capture (Chapter 11).

Trigger-based replication. Moves replication to the application layer when you need a subset of data, replication between different databases, or custom conflict resolution. Oracle GoldenGate reads the database log for applications. Alternatively a trigger runs custom code on each write, logs the change into a separate table, and an external process replicates it (Databus for Oracle, Bucardo for Postgres). Higher overhead and more bugs than built-in replication, but flexible.

Statement SQL text compact NOW(), RAND() break it WAL shipping bytes in blocks exact copy engine-coupled same version Logical (row) row changes decoupled versions differ OK enables CDC Trigger-based app code most flexible overhead bug-prone inside the database application layer
The four replication log methods and the main strength and weakness the book gives for each.

Problems with Replication Lag

For read-mostly workloads (common on the web), a read-scaling architecture adds many followers and spreads reads across them. This only works with asynchronous replication: fully synchronous to many nodes would be very unreliable.

  • Reading from a lagging async follower returns outdated data, so leader and follower can answer the same query differently.
  • The inconsistency is temporary: stop writing and followers catch up. This is eventual consistency. Async relational followers have it too, not just NoSQL.
  • "Eventually" is deliberately vague: no limit on lag. Replication lag is normally a fraction of a second, but can reach seconds or minutes near capacity or with network problems.

Reading Your Own Writes

A user submits data (written to the leader) then views it (read from a follower). If the follower has not caught up, the user's data seems lost.

User 1234 Leader Follower 2 insert comment ok arrives late read no results!
Figure 5-3 (simplified): a read from a stale replica right after a write. The fix is read-after-write consistency.

Read-after-write consistency (read-your-writes): a user who reloads always sees their own updates. No promise about other users' updates. Techniques with leader-based replication:

  • Read things the user may have modified from the leader, the rest from followers. Needs a way to know without querying: e.g. read the user's own profile from the leader, others' profiles from followers.
  • If most things are user-editable, that negates read scaling. Use other criteria: read from the leader for one minute after the user's last update, or refuse queries on followers more than one minute behind.
  • The client remembers the timestamp of its latest write; the serving replica must reflect updates up to that time, otherwise another replica serves it or the query waits. A logical timestamp (e.g. log sequence number) or system clock (then clock sync is critical).
  • Multiple datacenters: any request needing the leader must route to the leader's datacenter.

Cross-device read-after-write consistency (e.g. desktop browser and mobile app):

  • One device does not know the other's last-update timestamp, so that metadata must be centralized.
  • Devices may route to different datacenters (home broadband vs cellular). If reads must hit the leader, first route all of a user's devices to the same datacenter.

Monotonic Reads

Reads to different replicas can make time appear to go backward. User 2345 runs the same query twice: a low-lag follower returns user 1234's new comment, then a high-lag follower returns nothing. Likely when each page refresh goes to a random server.

User 1234 Leader Follower 1 Follower 2 User 2345 insert comment read 1: sees it read 2: gone
Figure 5-4 (simplified): a fresh read followed by a staler one. The fix is monotonic reads.
  • Monotonic reads: a user's successive reads never return older data after newer data. Weaker than strong consistency, stronger than eventual consistency.
  • Implementation: each user always reads from the same replica, chosen e.g. by a hash of the user ID rather than randomly. If that replica fails, reroute.

Consistent Prefix Reads

A violation of causality. Mr. Poons asks Mrs. Cake how far into the future she can see; she answers about ten seconds. An observer reading through followers gets her reply via a low-lag path and his question via a high-lag path, so the answer appears before the question.

Partition 1 1. Question Partition 2 2. Answer Observer sees Answer, then Question long lag short lag
Figure 5-5 (simplified): partitions replicated at different speeds let an observer see the answer before the question.
  • Consistent prefix reads: if writes happen in some order, every reader sees them in that order.
  • Mainly a problem in partitioned databases: partitions operate independently with no global write order, so a reader sees some parts older and some newer. A single write order always gives a consistent prefix.
  • Fixes: write causally related data to the same partition (not always efficient), or algorithms that track causal dependencies (see happens-before, below).

Solutions for Replication Lag

  • Ask how the application behaves if lag grows to minutes or hours. If that is a bad user experience, design for a stronger guarantee such as read-after-write.
  • Pretending async replication is synchronous is a recipe for problems.
  • Application-level fixes (e.g. some reads on the leader) are complex and easy to get wrong. Better if the database "does the right thing": that is why transactions exist.
  • Many distributed databases dropped transactions, claiming they cost too much performance and availability and that eventual consistency is inevitable at scale. The book calls this partly true but overly simplistic (Chapters 7, 9, Part III).

Multi-Leader Replication

Single-leader's main downside: all writes go through one leader; if you cannot reach it, you cannot write. Multi-leader (master–master, active/active) lets several nodes accept writes; each leader also acts as a follower of the others. (With partitioning, each partition has one leader in a single-leader setup.)

Use Cases for Multi-Leader Replication

Rarely worth the complexity inside one datacenter.

Multi-datacenter operation. A leader in each datacenter; normal leader–follower replication inside each; leaders replicate to each other across datacenters.

Datacenter 1 Datacenter 2 Leader Leader Follower Follower Follower Follower async conflict resolution
Figure 5-6 (simplified): a leader per datacenter, leaders replicate to each other asynchronously and must resolve conflicts.
Single-leader across DCsMulti-leader across DCs
PerformanceEvery write crosses the internet to the leader's DC; adds latencyWrites processed locally, replicated async; inter-DC delay hidden from users
DC outageFailover promotes a follower in another DCEach DC runs independently; catches up on return
Network problemsVery sensitive: writes go synchronously over the inter-DC linkTolerates temporary interruptions; writes still processed
  • Often via external tools: Tungsten Replicator (MySQL), BDR (PostgreSQL), GoldenGate (Oracle).
  • Big downside: the same data may be modified concurrently in two DCs, so write conflicts must be resolved.
  • Often retrofitted, with pitfalls around autoincrementing keys, triggers and integrity constraints. Often considered dangerous territory to avoid if possible.

Clients with offline operation. E.g. calendar apps on phone, laptop and other devices must read and write while offline, then sync. Each device's local database is a leader; sync is async multi-leader replication with lag of hours or days. Architecturally the same as multi-DC taken to the extreme: each device is a "datacenter" on a very unreliable network. Broken calendar sync implementations show how hard it is. CouchDB is designed for this mode.

Collaborative editing. Etherpad and Google Docs allow concurrent editing. Edits apply instantly to the local replica (browser state) and replicate async to the server and other editors.

  • To guarantee no conflicts, lock the document before editing: equivalent to single-leader with transactions on the leader.
  • For faster collaboration, make the unit of change tiny (a keystroke) and skip locks: this brings all multi-leader challenges, including conflict resolution.

Handling Write Conflicts

The biggest multi-leader problem. Wiki example: user 1 changes a page title A→B, user 2 changes A→C at the same time. Both succeed at their local leader; the conflict is detected when changes replicate. Cannot happen with a single leader.

User 1 Leader 1 Leader 2 User 2 title = B title = C ok ok conflict detected
Figure 5-7 (simplified): two leaders accept concurrent updates to the same record; the conflict surfaces only on async replication.

Synchronous versus asynchronous conflict detection. A single leader makes the second writer block or abort and retry. Multi-leader accepts both and finds the conflict later, possibly too late to ask the user. Synchronous detection (wait for all replicas before acking) gives up independent writes; then just use single-leader.

Conflict avoidance. Simplest and often recommended (many implementations handle conflicts poorly): route all writes for a record through one leader. E.g. route each user to a "home" datacenter (maybe the geographically nearest); for that user it is effectively single-leader. Breaks down when the designated leader changes: a datacenter fails, or a user moves closer to another datacenter.

Converging toward a consistent state. Single-leader applies writes in sequence, so the last write sets the final value. Multi-leader has no defined order: in the wiki example leader 1 ends with C, leader 2 with B. Every scheme must make replicas eventually equal, so resolution must be convergent. Options:

  • Give each write a unique ID (timestamp, random number, UUID, hash of key and value); highest wins, others discarded. With timestamps this is last write wins (LWW): popular but dangerously prone to data loss.
  • Give each replica an ID; the higher-numbered replica's writes win. Also loses data.
  • Merge values, e.g. sort and concatenate: "B/C".
  • Record the conflict in an explicit data structure keeping all information; application code resolves it later (perhaps by asking the user).

Custom conflict resolution logic. Most multi-leader tools let application code resolve conflicts:

  • On write: a handler runs as soon as a conflict appears in the replicated log (Bucardo: a Perl snippet). Runs in the background, must be fast, cannot prompt a user.
  • On read: all conflicting writes are stored and returned on the next read; the app (or the user) resolves and writes back. CouchDB works this way.
  • Resolution is per row or document, not per transaction: each write in a multi-write transaction is resolved separately.

Automatic Conflict Resolution. Custom code gets complicated and error-prone. Amazon's shopping cart handler once preserved added items but not removals, so removed items reappeared. Research directions:

  • CRDTs (conflict-free replicated datatypes): sets, maps, ordered lists, counters that concurrent users can edit and that resolve conflicts sensibly. Some are in Riak 2.0. They use two-way merges.
  • Mergeable persistent data structures: track history explicitly, like Git, with a three-way merge.
  • Operational transformation: behind Etherpad and Google Docs; designed for concurrent editing of an ordered list, such as the characters of a document.
  • Database implementations are still young but may make multi-leader sync much simpler.

What is a conflict? Some are obvious (same field set to two values). Others are subtle: a meeting room booking system must prevent overlapping bookings for one room, yet two bookings made on two different leaders can conflict even if each checked availability first. Covered further in Chapters 7 and 12.

Multi-Leader Replication Topologies

A replication topology is the set of paths along which writes propagate. Two leaders allow only one. With more:

(a) Circular (b) Star root (c) All-to-all MySQL default generalizes to tree most general
Figure 5-8 (simplified): circular, star and all-to-all multi-leader topologies.
  • All-to-all: every leader sends to every other. Most general.
  • Circular: each node receives from one and forwards (plus its own writes) to one other. MySQL's default.
  • Star: a root forwards writes to all others; generalizes to a tree.
  • In circular and star, writes pass through several nodes. To stop infinite loops, each node has a unique ID and each write is tagged with the IDs it has passed; a node ignores writes tagged with its own ID.
  • Circular/star: one failed node can block replication between others until fixed; rerouting is usually manual. Denser topologies (all-to-all) avoid a single point of failure.
  • All-to-all: faster links let messages overtake others.
Client A Leader 1 Leader 2 Leader 3 Client B insert insert, slow update update arrives first
Figure 5-9 (simplified): leader 2 receives B's update before the insert it depends on.
  • A causality problem like consistent prefix reads: the update depends on the insert. Timestamps are not enough because clocks are not reliably in sync.
  • Version vectors can order these events (see Detecting Concurrent Writes).
  • Many systems implement conflict detection poorly: at the time of writing PostgreSQL BDR gives no causal ordering, and Tungsten Replicator does not even try to detect conflicts. Read the docs and test the guarantees.

Leaderless Replication

Single- and multi-leader rely on a leader to order writes. Leaderless systems let any replica accept client writes. Early replicated systems were leaderless; the idea returned with Amazon's in-house Dynamo. Riak, Cassandra and Voldemort follow it, hence "Dynamo-style". (AWS DynamoDB is a different, single-leader architecture.)

  • The client sends writes to several replicas directly, or a coordinator node does it, but without enforcing a write order. This has profound consequences.

Writing to the Database When a Node Is Down

Three replicas, one down for a reboot. Leader-based might need failover; leaderless has no failover. User 1234 sends the write to all three in parallel; two acknowledge; two of three is enough, so the write succeeds and the missed replica is ignored.

When the node returns it serves stale values. So reads also go to several nodes in parallel, and version numbers decide which response is newer.

User 1234 write v7 User 2345 read Replica 1: v7 Replica 2: v7 Replica 3: v6 ✗ 2 of 3 ok Read from all 3 v7, v7, v6 newest = v7 Read repair write v7 back to replica 3
Figure 5-10 (simplified): quorum write while replica 3 is down, then a quorum read that spots and repairs the stale v6.

Read repair and anti-entropy. Two ways a returning node catches up:

  • Read repair: a parallel read spots a stale response (replica 3 returns v6, others v7) and writes the newer value back. Works well for frequently read values.
  • Anti-entropy process: background process compares replicas and copies missing data. No write order and possibly a long delay, unlike a replication log.
  • Not every system has both (Voldemort lacks anti-entropy). Without it, rarely read values may be missing from some replicas, reducing durability.

Quorums for reading and writing. With n replicas, a write needs w confirmations and a read queries at least r nodes. If w + r > n, at least one node read is up to date. These are quorum reads and writes (strict quorum); r and w are minimum votes.

  • Common: n odd (3 or 5), w = r = (n + 1) / 2 rounded up.
  • Few writes, many reads: w = n, r = 1. Faster reads, but one failed node fails all writes.
  • The cluster may have more than n nodes; each value lives on only n of them (partitioning, Chapter 6).
  • w < n: writes survive an unavailable node. r < n: reads do.
  • n=3, w=2, r=2 tolerates one unavailable node; n=5, w=3, r=3 tolerates two.
  • Requests normally go to all n; w and r say how many replies to wait for.
  • Fewer than w or r available: error. The cause (crash, full disk, network) does not matter; only whether a success came back.
n = 5, w = 3, r = 3 write succeeded on w = 3 read from r = 3 new new new old old w + r = 6 > 5: at least one node read has the latest write
Figure 5-11 (simplified): if w + r > n, the read set and the write set must overlap.

Limitations of Quorum Consistency

  • Quorums need not be majorities; only overlap of read and write sets matters. Majorities (more than n/2) are common because they tolerate up to n/2 failures. Other assignments allow flexibility in distributed algorithm design.
  • w + r ≤ n: stale reads more likely, but lower latency and higher availability; unavailable only when reachable replicas fall below w or r.

Even with w + r > n, stale values can be returned:

  • A sloppy quorum may put the w writes on different nodes than the r reads, so no guaranteed overlap.
  • Concurrent writes have no clear order; the only safe fix is merging. LWW by timestamp can lose writes to clock skew.
  • A write concurrent with a read may be on only some replicas; the read may return old or new.
  • A write that succeeded on fewer than w replicas is reported failed but not rolled back where it did succeed, so later reads may or may not return it.
  • If a node with the new value fails and is restored from a replica with the old value, the new value may fall below w copies.
  • Even when everything works, timing edge cases exist (Linearizability and quorums, Chapter 9).

So Dynamo-style databases suit workloads that tolerate eventual consistency. w and r tune the probability of stale reads; they are not absolute guarantees. You usually do not get read-your-writes, monotonic reads or consistent prefix reads; stronger guarantees need transactions or consensus.

Monitoring staleness. Even if stale reads are tolerable, alert when replication falls far behind (network problems, overloaded node).

  • Leader-based: same write order everywhere, each node has a log position; lag = leader position − follower position.
  • Leaderless: no fixed write order, so harder. With only read repair, a rarely read value may be ancient.
  • Research predicts the expected percentage of stale reads from n, w, r; not yet common. For operability, quantify "eventual".

Sloppy Quorums and Hinted Handoff

Quorums tolerate failed and slow nodes without failover (return after w or r replies), which suits high-availability, low-latency workloads that accept occasional stale reads. But a network interruption can cut a client off from enough nodes that it cannot assemble a quorum, though the nodes are alive. In a cluster with many more than n nodes, the client may still reach some nodes. The trade-off: return errors, or accept the write on reachable nodes outside the value's n "home" nodes?

Client home nodes (n = 3) A B C cut off Stand-in D holds write + hint w = 3 incl. D hinted handoff
Sloppy quorum: a reachable non-home node accepts the write; hinted handoff sends it home when the network heals.
  • Sloppy quorum: still need w and r successes, but they may come from non-home nodes. (The book's analogy: locked out of your house, you sleep on the neighbor's couch.)
  • Hinted handoff: after the interruption, writes held for other nodes are sent to their home nodes.
  • Raises write availability: any w reachable nodes will do. But even with w + r > n a read may miss the latest value until handoff completes. It is only a durability assurance: the data is on w nodes somewhere.
  • Optional in all common Dynamo implementations: on by default in Riak, off by default in Cassandra and Voldemort.

Multi-datacenter operation. Leaderless also suits multiple datacenters, being built to tolerate concurrent writes, network interruptions and latency spikes.

  • Cassandra, Voldemort: n spans all DCs; config says how many replicas per DC. Writes go to all replicas, but the client usually waits only for a quorum in its local DC; remote writes are often async.
  • Riak: client traffic stays in one DC, n counts replicas within one DC; cross-DC replication between clusters is async in the background, similar to multi-leader.

Detecting Concurrent Writes

Dynamo-style databases let several clients write the same key concurrently, so conflicts occur even with strict quorums, and also during read repair or hinted handoff. Events arrive in different orders at different nodes. Example: clients A and B write key X on three nodes:

  • Node 1 gets A's write, never B's (transient outage).
  • Node 2 gets A then B. Node 3 gets B then A.
  • If each node simply overwrites, they stay permanently inconsistent: node 2 says X = B, the others say A.
Client A Node 1 Node 2 Node 3 Client B set X = A ✗ set X = B X = A X = B X = A
Figure 5-12 (simplified): with plain overwrites, concurrent writes leave nodes permanently disagreeing.

Replicas must converge. Most implementations are poor at this, so to avoid losing data the application developer must know the database's conflict handling internals.

Last write wins (discarding concurrent writes). Each replica keeps only the most "recent" value. But for concurrent writes neither happened "first"; the order is undefined. LWW forces an arbitrary order: attach a timestamp, keep the biggest, discard the rest.

  • Only conflict resolution in Cassandra; optional in Riak.
  • Converges at the cost of durability: of several concurrent writes all acked to clients (on w replicas), only one survives; the others are silently discarded. LWW may even drop non-concurrent writes (clock issues, Chapter 8).
  • Acceptable for e.g. caching. If losing data is not acceptable, LWW is a poor choice.
  • Only safe use: write each key once and treat it as immutable. Recommended Cassandra practice: a UUID as the key, so each write has a unique key.

The "happens-before" relationship and concurrency.

  • Figure 5-9's writes are not concurrent: B's update builds on A's insert, so B is causally dependent on A.
  • Figure 5-12's writes are concurrent: neither client knew about the other.
  • A happens before B if B knows about, depends on, or builds on A. Two operations are concurrent if neither happens before the other.
  • Three possibilities: A before B, B before A, or concurrent. A later operation may overwrite an earlier one; concurrent ones are a conflict to resolve.

Concurrency, Time, and Relativity. Concurrency is not about overlapping in physical time (hard to tell anyway, given clock problems). Operations are concurrent if they are unaware of each other. Some compare this with special relativity: distant events cannot affect each other faster than light. In computers, slow or interrupted networks can make operations far apart in time still concurrent.

Capturing the happens-before relationship. Start with a single replica. Two clients add items to one shopping cart (the book offers air traffic controllers adding aircraft as a less inane analogy):

  1. Client 1 adds milk. Server stores it as version 1, echoes value and version.
  2. Client 2 adds eggs, unaware of milk. Server stores eggs as version 2 alongside milk as a separate value; returns both and version 2.
  3. Client 1 sends [milk, flour] with version 1. It supersedes [milk] but is concurrent with [eggs]. Server: version 3 [milk, flour], keeps [eggs].
  4. Client 2 merges [milk] and [eggs], adds ham, sends [eggs, milk, ham] with version 2. Overwrites [eggs]; concurrent with [milk, flour]. Values: v3 [milk, flour], v4 [eggs, milk, ham].
  5. Client 1 merges its v3 values, adds bacon, sends [milk, flour, eggs, bacon] with version 3. Overwrites [milk, flour]; keeps concurrent [eggs, milk, ham].
Client 1 Server Client 2 milk v1 eggs v2 milk, flour (v1) v3 eggs, milk, ham (v2) v4 milk, flour, eggs, bacon (v3) v5 siblings: v4 and v5 each write carries the version of its prior read
Figure 5-13 (simplified): each write names the version it was based on, so the server knows what it overwrites and what is concurrent.
v1 milk v2 eggs v3 +flour v4 +ham v5 +bacon final siblings v4 and v5 arrow = later write knew about the earlier one; no write is lost
Figure 5-14 (simplified): graph of causal dependencies in the cart example.

Clients are never fully up to date, yet old versions are eventually overwritten and no writes are lost. The server decides concurrency from version numbers alone, without interpreting values. The algorithm:

  • The server keeps a version number per key, increments it on every write, and stores it with the value.
  • A read returns all values not yet overwritten plus the latest version. A client must read before writing.
  • A write includes the version from the prior read and merges all values received then. (The write response can act like a read, enabling chained writes.)
  • On a write with version v, the server overwrites all values with version ≤ v (they were merged) and keeps higher-versioned values (concurrent).
  • A write without a version is concurrent with everything: it overwrites nothing and is returned as one of the values later.

Merging concurrently written values. No data is silently dropped, but clients must merge concurrent values, which Riak calls siblings. Same problem as multi-leader conflict resolution.

  • Picking one by version or timestamp (LWW) loses data.
  • Cart: take the union. Final siblings [milk, flour, eggs, bacon] and [eggs, milk, ham] merge to [milk, flour, eggs, bacon, ham], no duplicates.
  • With removals, a union brings back an item removed in only one sibling. So removal leaves a tombstone: a deletion marker with a version number.
  • Hand-written merging is complex and error-prone; Riak's datatype support uses CRDTs that merge siblings automatically, including deletions.

Version vectors. With multiple replicas and no leader, one version number is not enough: use a version number per replica as well as per key.

  • Each replica increments its own number on writes it processes and tracks the numbers it has seen from other replicas. That tells it what to overwrite and what to keep as siblings.
  • The collection of these numbers is a version vector. Notable variant: the dotted version vector in Riak 2.0.
  • Sent to clients on read and back on write (Riak encodes it as a string called causal context). Lets the database tell overwrites from concurrent writes.
  • Reading from one replica and writing back to another is safe: siblings may appear, but nothing is lost if siblings are merged correctly.
  • A version vector is sometimes called a vector clock, but they are not quite the same; for comparing replica state, version vectors are the right structure.
One counter per replica, per key stored value R1:2 R2:1 R3:0 incoming write's context R1:2 R2:1 R3:1 Write has seen stored value → overwrite Neither has seen the other → keep both as siblings
Version vectors: the per-replica counters show whether a write overwrites a value or is concurrent with it. (Illustrative values; the book gives no numeric example.)

Summary

  • Replication serves high availability (survive a machine, several, or a whole datacenter down), disconnected operation (work through network interruptions), latency (data near users) and scalability (more reads than one machine handles).
  • A simple goal that is remarkably tricky: you must think about concurrency and every failure, at minimum unavailable nodes and network interruptions (not even counting silent data corruption from bugs).
  • Single-leader: writes to one leader, which streams change events to followers; reads anywhere, possibly stale.
  • Multi-leader: writes to any of several leaders, which stream changes to each other and to followers.
  • Leaderless: writes to several nodes and reads from several in parallel to detect and correct stale data.
  • Single-leader is popular: easy to understand, no conflict resolution. Multi-leader and leaderless are more robust to faulty nodes, network interruptions and latency spikes, but harder to reason about with very weak consistency.
  • Sync vs async replication profoundly changes fault behavior. Async is fast when healthy; plan for growing lag and server failures. Promoting an async follower can lose recently committed data.
  • Consistency models for replication lag: read-after-write (see your own submissions), monotonic reads (never see an earlier point after a later one), consistent prefix reads (causal order, e.g. question before answer).
  • Multi-leader and leaderless allow concurrent writes, so conflicts occur. A database can determine whether one operation happened before another or they were concurrent, and conflicts can be resolved by merging concurrent updates.
  • Next (Chapter 6): partitioning, the counterpart of replication.

Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.