Replication
Designing Data-Intensive Applications · Chapter 5 · Recall lab
Part I of the book was about one machine. Part II begins here, with the first thing you do once there is more than one: keep a copy of the same data on several machines connected by a network. If the data never changed that would be easy, a copy made once. All of the difficulty in replication lies in handling changes to replicated data, and this chapter is three algorithms for doing it, each with its own idea of who is allowed to accept a write.
The same data, on several machines, while it changes
Part II is about data spread across several machines, and the book gives three reasons you would want that: scalability past one machine’s load, fault tolerance and high availability when one machine goes down, and latency, with servers near users around the world. There are two ways to spread data: replication, a copy on several nodes, which this chapter covers, and partitioning, a big database split into subsets, which is chapter 6. They often go together.
Latency
Keep data geographically close to your users, so a request doesn’t cross an ocean.
Availability
Let the system continue working even if some of its parts have failed.
Read throughput
Scale out the number of machines that can serve read queries.
For this chapter, assume each node is small enough to hold a full copy of the dataset. The questions are then the ones every replicated system has to answer, and the answers sort into three families that differ in one thing: which nodes accept writes.
Three ways to replicate, one write each
The pulses in each panel are one write spreading a hop at a time. None of these ideas is new. Replication has been studied since the 1970s, and the fundamental constraints of networks have not changed since. What has changed is how widely they are used, and how often the trade-offs, such as synchronous against asynchronous replication or how to handle a failed replica, are left as configuration options with many misunderstandings around them. Eventual consistency is one of them, and this chapter is mostly about what it does and doesn’t promise.
Every write goes through one node
Each node that stores a copy of the database is a replica. With several, the obvious question is how to make sure all the data ends up on all of them. Every write has to be processed by every replica, or they would no longer hold the same data. The most common answer is leader-based replication, also called active/passive or master–slave.
1 · the leader
One replica is designated the leader (master, primary). Clients that want to write must send their requests to the leader, which first writes the new data to its local storage.
2 · the followers
The others are followers (read replicas, slaves, secondaries, hot standbys). The leader sends each change to all of them as part of a replication log or change stream, and each applies the writes in the same order as the leader processed them.
3 · reads and writes
A client that wants to read can query the leader or any follower. Writes are only accepted on the leader; from the client’s point of view, the followers are read-only.
This mode is built into many relational databases (PostgreSQL since 9.0, MySQL, Oracle Data Guard, SQL Server’s AlwaysOn Availability Groups), into some non-relational ones (MongoDB, RethinkDB, Espresso), and it isn’t restricted to databases: distributed message brokers such as Kafka and RabbitMQ’s highly available queues use it, and so do some network filesystems and replicated block devices such as DRBD.
Does the leader wait?
An important detail of a replicated system is whether replication happens synchronously or asynchronously. In relational databases this is often configurable; other systems are hardwired to one or the other. The book’s example: user 1234 updates a profile picture. The leader receives the update, and at some point forwards the change to the followers, and at some point tells the user it succeeded. The question is the order of those last two.
One update, four configurations, timed
The arrows in each panel are drawn from one table of link delays, and the user’s wait is read off the same table: 65 ms fully synchronous, 40 ms semi-synchronous, 23 ms asynchronous. The ordering is the point, more than the numbers. Normally replication is quite fast (most databases apply changes to followers in less than a second), but there is no guarantee of how long it might take. A follower may fall behind by minutes or more: recovering from a failure, running at maximum capacity, or across a network problem.
Weakening durability can be a good trade
A fully asynchronous configuration means a write is not guaranteed to be durable, even if it has been confirmed to the client. It may sound like a bad trade-off, but it is nevertheless widely used, especially if there are many followers or they are geographically distributed.
Losing data on a failover is a serious problem
For asynchronous systems, losing data if the leader fails is a serious problem, so researchers keep investigating replication methods that lose no data and still have good performance. Chain replication is one, a variant of synchronous replication implemented in a few systems such as Microsoft Azure Storage. Chapter 9 relates it to consensus.
Copying a database that won't hold still
From time to time you need a new follower: to increase the number of replicas, or to replace a failed node. Simply copying data files from one node to another is typically not sufficient, because clients keep writing while the copy runs. And locking the database to make the files consistent goes against the goal of high availability. Setting up a follower can usually be done without downtime.
A new follower, from an empty disk to caught up
The cells are positions in the leader’s log. What makes the whole thing work is the one number the snapshot carries, position 5 here: it is the only way the follower can ask for exactly the changes it has not got, without missing one or applying one twice.
Followers catch up; leaders are replaced
Any node can go down, unexpectedly from a fault, or deliberately for a reboot to install a kernel security patch. Being able to reboot individual nodes without downtime is a big advantage for operations, so the goal is to keep the whole system running despite individual node failures, and to keep the impact of an outage as small as possible.
Follower failure: catch-up recovery
Each follower keeps a log of the changes it has received from the leader on its local disk. If it crashes and restarts, or the network between it and the leader is interrupted, it knows the last transaction it processed before the fault. It connects to the leader, requests every change since then, applies them, and continues as before. It is the new follower’s step 3, from a position it already had.
The leader is the harder case. One of the followers has to be promoted to be the new leader, clients have to be reconfigured to send their writes to it, and the other followers have to start consuming changes from it. That process is failover, and it can be done by hand, by an administrator, or automatically, in three steps. Step through it on a cluster that hands out autoincrementing primary keys.
An automatic failover, and what the new leader does not know
Failover is fraught with things that can go wrong
- Asynchronous replication loses the tail. The new leader may not have received all the writes from the old one: here node B was 2 behind. If the old leader rejoins, what should happen to those writes? The new leader may have received conflicting writes in the meantime. The most common solution is for the old leader’s unreplicated writes to simply be discarded, which may violate clients’ durability expectations.
- Discarding writes is especially dangerous when other storage systems are coordinated with the database. The keys 5 and 6 in the reel are the GitHub incident in miniature.
- Split brain. Two nodes both believing they are the leader, both accepting writes. Some systems shut one down when this is detected, and a carelessly designed mechanism can shut down both.
- The timeout. Below.
Choosing the timeout: drag it, and watch the same minute play out
1 unnecessary failover, triggered by a network glitch. The leader was alive each time, and a failover started under load makes a struggling system worse.
The real crash at 44 s is declared 10 s later. Until then nobody is accepting writes.
A longer timeout means a longer time to recovery when the leader really fails. A shorter one means unnecessary failovers: a temporary load spike can push a node’s response time over the timeout, or a network glitch can delay packets, and if the system is already struggling with high load or network problems, an unnecessary failover is likely to make the situation worse, not better. There are no easy solutions to these problems. For that reason, some operations teams prefer to perform failovers manually, even if the software supports automatic failover. They are the fundamental problems of distributed systems, node failures, unreliable networks, and trade-offs around replica consistency, durability, availability and latency, and chapters 8 and 9 go deeper.
What exactly is the leader sending?
“The leader sends every change to the followers” leaves open what a change is. There are four answers in practice, and they sit at four different levels: the statement the client typed, the bytes the storage engine wrote, the rows that changed, and whatever the application decides to log.
One write, four replication logs
INSERT INTO comments (body, created_at, token)
VALUES ('first!', NOW(), RAND());| replica | body | created_at | token |
|---|---|---|---|
| leader | first! | 09:14:07.412 | 0.511587 |
| follower 1 | first! | 09:14:07.480 | 0.210612 |
| follower 2 | first! | 09:14:09.035 | 0.629497 |
The leader can replace each nondeterministic call with a fixed value before logging, but there are so many edge cases that other methods are generally preferred. MySQL used statement-based replication before 5.1, and now switches to row-based whenever a statement is nondeterministic. VoltDB uses it safely by requiring transactions to be deterministic.
-- the WAL record, schematically: bytes in a disk block rel1663/16384/24576block2817offset0x01f0heap insert,48bytes:00 00 00 00 9e 1c 00 00 0c 66 69 72 73 74 21 …-- a B-tree page for the index on created_at changes too rel1663/16384/24581block40offset0x0a38…
The disadvantage is that the log is very low-level: which bytes changed in which disk blocks. Replication becomes tightly coupled to the storage engine, so if the on-disk format changes between versions, you typically cannot run different versions on the leader and the followers. That rules out the zero-downtime upgrade, where you upgrade the followers first and then fail over to one of them.
-- one record per row touched, then one for the commit
{ op: insert, table: comments,
row: { id: 41, body: 'first!', created_at: '09:14:07.412', token: 0.511587 } }
{ op: update, table: posts, key: { id: 7 }, set: { comment_count: 12 } }
{ op: delete, table: drafts, key: { id: 93 } }
{ op: commit, txid: 88104 }| replica | body | created_at | token |
|---|---|---|---|
| leader | first! | 09:14:07.412 | 0.511587 |
| follower 1 | first! | 09:14:07.412 | 0.511587 |
| follower 2 | first! | 09:14:07.412 | 0.511587 |
Because the values are already evaluated, every replica stores the same row, as the table shows. The format can stay backward compatible, so leader and followers can run different versions or even different engines. And it is easy for external applications to parse: a data warehouse, a custom index, a cache. That technique is called change data capture, and chapter 11 returns to it.
CREATE TRIGGER comments_replicate AFTER INSERT OR UPDATE ON comments FOR EACH ROW EXECUTE FUNCTION log_change(); -- log_change() appends the row to a changes table; -- an external process reads that table, applies -- custom logic, and writes to another system
Same query, same moment, different answers
Being able to tolerate node failures is only one reason for replication. The others are scalability and latency, and for workloads that are mostly reads and only a small percentage of writes, a common pattern on the web, there is an attractive option: create many followers and spread the read requests across them. This read-scaling architecture removes load from the leader. But it realistically only works with asynchronous replication: try to replicate synchronously to all of them and a single node failure or network outage would make the whole system unavailable for writing. And the more nodes you have, the likelier one is down.
So reads hit followers that may be behind. Run the same query on the leader and a follower at the same moment and you may get different results, because not all writes have reached the follower yet. The inconsistency is temporary: if you stop writing to the database and wait a while, the followers will eventually catch up. That effect is eventual consistency, and “eventually” is deliberately vague: there is no limit to how far a replica can fall behind. Normally it is a fraction of a second. Near capacity or across a network problem, it can be seconds or minutes.
Replication lag, on a scope: nine writes, two followers, one moment
The leader has w1–w7. Follower 1 has w1–w6, 1 behind. Follower 2 has w1–w4, 3 behind.
Read your writes: you just wrote w7 at 5.3 s. Reload from follower 1 and follower 2 and it is not there yet; it lands at 5.8 s and 7.7 s.
Monotonic reads: read follower 1, then follower 2, and w5–w6 vanish. Time appears to go backwards.
When the lag is that large, the inconsistency it introduces is not just theoretical; it is a real problem for applications. The scope already names the first two problems in its reading. The chapter gives three, and each one is a guarantee you can ask the system for.
What a user can tell is wrong
The book's three figures, drawn from their timings
Techniques: read anything the user may have modified from the leader and everything else from a follower, e.g. your own profile from the leader, other people’s from followers. If most things are editable, read from the leader for one minute after the user’s last update, and refuse queries on any follower more than a minute behind. Or have the client remember the timestamp (ideally a logical one, a log sequence number) of its most recent write, and only read from a replica that has caught up to it. Two complications: across datacenters, a request that must go to the leader must be routed to the leader’s datacenter; and if the same user is on several devices, the “last update” has to be centralised, and all of their devices routed to the same datacenter.
One way to achieve it: make sure each user always reads from the same replica, chosen by a hash of the user ID rather than at random. If that replica fails, the user’s queries are rerouted to another.
This is a particular problem in partitioned (sharded) databases, chapter 6’s subject: if the database always applied writes in the same order, reads would always see a consistent prefix, but different partitions operate independently and there is no global ordering of writes. One fix is to write causally related writes to the same partition, which cannot always be done efficiently. Algorithms that explicitly track causal dependencies come up later in this chapter.
Solutions for replication lag
When working with an eventually consistent system, it is worth asking how the application behaves if the lag increases to several minutes or even hours. If the answer is “no problem,” great. If the result is a bad experience for users, design the system to give a stronger guarantee. Pretending replication is synchronous when in fact it is asynchronous is a recipe for problems down the line.
The application can provide stronger guarantees than the database, performing certain reads on the leader for instance, but that is complex and easy to get wrong. It would be better if application developers didn’t have to worry about subtle replication issues and could just trust their database to “do the right thing.” That is why transactions exist. Many distributed databases abandoned them, claiming they are too expensive in performance and availability and that eventual consistency is inevitable in a scalable system. There is some truth in that, and it is overly simplistic. Chapters 7 and 9 return to it.
If there is only one leader, it is a single point of failure for writes
Leader-based replication has one major downside: there is only one leader, and all writes must go through it. If you can’t connect to it, for example because of a network interruption, you can’t write to the database. The natural extension is to allow more than one node to accept writes, each processing a write by forwarding it to every other node. That is multi-leader replication, also master–master or active/active, and each leader simultaneously acts as a follower to the other leaders.
It rarely makes sense within a single datacenter, because the benefits rarely outweigh the added complexity. It makes sense in three situations.
Multi-datacenter operation
A leader in each datacenter. Every write is processed locally and replicated asynchronously between datacenters, so the inter-datacenter delay is hidden from users. Each datacenter continues operating independently if another goes down. And a temporary interruption of the public-internet link between datacenters doesn’t prevent writes from being processed. Tungsten Replicator for MySQL, BDR for PostgreSQL, GoldenGate for Oracle.
Clients with offline operation
A calendar on your phone, laptop and other devices, usable whether or not you are online. Every device has a local database that acts as a leader, with asynchronous multi-leader replication, the sync, between them. The replication lag may be hours or days. Each device is a “datacenter” with an extremely unreliable network between them. CouchDB is designed for this mode.
Collaborative editing
Etherpad, Google Docs. Each user’s edits apply instantly to their local replica and replicate asynchronously. Locking the document first is equivalent to single-leader replication with transactions; for faster collaboration the unit of change is made very small, a single keystroke, and locking is avoided, which brings every multi-leader challenge with it.
Multi-leader replication across datacenters has a big downside: the same data may be concurrently modified in two datacenters, and those write conflicts must be resolved. And as it is often a retrofitted feature in many databases, there are subtle configuration pitfalls and surprising interactions with autoincrementing keys, triggers and integrity constraints. It is often considered dangerous territory that should be avoided if possible.
Both writes succeeded; only one can be the title
The book’s example is a wiki page edited simultaneously by two users. User 1 changes the title from A to B, user 2 from A to C. Each change is successfully applied to its local leader, and the conflict is detected only when the changes replicate asynchronously.
A write conflict between two leaders
In a single-leader database the second writer would either block and wait for the first to complete, or abort with an error and retry. In a multi-leader setup both writes are successful, and the conflict is only detected asynchronously at some later point in time, when it may be too late to ask the user to resolve it. You could make conflict detection synchronous, waiting for the write to replicate to all replicas before telling the user it succeeded, but you would lose the main advantage of multi-leader replication: letting each replica accept writes independently.
Conflict avoidance
The simplest strategy is to avoid them: if all writes for a particular record go through the same leader, conflicts cannot occur. Since many implementations of multi-leader replication handle conflicts quite poorly, this is frequently the recommended approach. If a user can only edit their own data, route that user’s requests to the same datacenter every time. From any one user’s point of view the configuration is essentially single-leader. It breaks down when the designated leader must change, because a datacenter failed or a user moved, and concurrent writes on different leaders become possible again.
Converging toward a consistent state
Five things two leaders can do with B and C
Automatic conflict resolution
Conflict resolution rules can quickly become complicated and custom code error-prone; Amazon’s shopping cart is the frequently cited example, where for a while removed items reappeared. Three lines of research: conflict-free replicated datatypes (CRDTs), sets, maps, ordered lists and counters that resolve concurrent edits sensibly, implemented in Riak 2.0; mergeable persistent data structures that track history explicitly, like Git, with a three-way merge; and operational transformation, behind Etherpad and Google Docs, designed for concurrent editing of an ordered list such as the characters of a document.
What is a conflict?
Some are obvious: two writes to the same field of the same record. Others are subtle. A meeting-room booking system must not book a room twice, and if two bookings for the same room at the same time are created on two different leaders, nothing in either write conflicts with the other as data, yet together they break the rule. Chapters 7 and 12 come back to it; there is no quick ready-made answer.
Which paths a write takes, and what one dead node cuts
A replication topology describes the communication paths along which writes are propagated from one node to another. With two leaders there is only one plausible topology: each sends its writes to the other. With more than two, there are choices. Each figure below propagates a write from leader 1 by following the links, one hop per pulse, then does it again with one node down.
Circular, star and all-to-all, healthy and with one failure
With leader 3 down, a write at leader 1 reaches only 1 of the 2 leaders still running: one failed node interrupts the flow of replication messages between nodes that are perfectly healthy, until it is fixed or the topology is reconfigured, which in most deployments is done by hand.
To prevent infinite loops, every write is tagged with the identifiers of all the nodes it has passed through; a node receiving a change tagged with its own identifier ignores it.
With the hub down, a write at leader 1 reaches only 0 of the 2 leaders still running: one failed node interrupts the flow of replication messages between nodes that are perfectly healthy, until it is fixed or the topology is reconfigured, which in most deployments is done by hand.
To prevent infinite loops, every write is tagged with the identifiers of all the nodes it has passed through; a node receiving a change tagged with its own identifier ignores it.
With leader 3 down, a write at leader 1 still reaches all 2 leaders still running, because no path depended on the failed node. The denser topology has better fault tolerance, and its own problem, which is the next figure.
All-to-all has its own problem. Some network links may be faster than others, so some replication messages may overtake others. Client A inserts a row on leader 1, client B updates it on leader 3, and leader 2 can receive the writes in the wrong order:
An update overtaking the insert it depends on
This is a problem of causality, similar to consistent prefix reads: the update depends on the prior insert, so every node must process the insert first. Simply attaching a timestamp to every write is not sufficient, because clocks cannot be trusted to be in sync (chapter 8). The tool for ordering these events correctly is the version vector, which closes this chapter. Conflict detection is poorly implemented in many multi-leader systems: at the time of writing PostgreSQL BDR does not provide causal ordering of writes, and Tungsten Replicator for MySQL doesn’t even try to detect conflicts. Read the documentation, and test thoroughly.
Any replica takes the write; the client does the bookkeeping
Single-leader and multi-leader replication share an idea: a client sends a write to one node, and the database system copies it to the others, in an order the leader decides. Some data storage systems abandon the concept of a leader and allow any replica to directly accept writes from clients. Some of the earliest replicated systems were leaderless; the idea was mostly forgotten during the dominance of relational databases, and became fashionable again after Amazon used it for its in-house Dynamo system. Riak, Cassandra and Voldemort are open source datastores inspired by it, so this kind of database is called Dynamo-style.
In some implementations the client sends its writes directly to several replicas; in others a coordinator node does it on the client’s behalf, but unlike a leader, the coordinator does not enforce any particular ordering of writes. That difference in design has profound consequences for how the database is used.
Writing to the database when a node is down
In a leader-based configuration, writes to a down node mean a failover. In a leaderless configuration, failover does not exist. The client sends the write to all three replicas in parallel; the two available ones accept it and the unavailable one misses it, and if two out of three acknowledgements is enough, the write is a success. The client simply ignores the missed one.
A write with one replica offline, and the read that comes after
Replica 3 comes back having missed the write, so any value read from it is stale. Which is why reads are also sent to several nodes in parallel, the responses carry version numbers, and the client takes the newest: here v7, from 2 of 3. Two mechanisms then get the missed write onto the node that missed it.
Read repair
When a client reads from several nodes in parallel, it can detect any stale responses and write the newer value back to that replica, which is the last arrow above. Works well for values that are frequently read.
Anti-entropy process
A background process constantly looks for differences between replicas and copies any missing data from one to another. Unlike the replication log in leader-based replication, it does not copy writes in any particular order, and there may be a significant delay. Not every system has one: without it, values that are rarely read may be missing from some replicas, and so have reduced durability.
w + r > n, and the many ways it is less than it looks
Generalise the example. With n replicas, every write must be confirmed by w nodes to be considered successful, and every read must query at least r nodes. As long as w + r > n, we expect to get an up-to-date value when reading, because at least one of the r nodes we read from must be up to date. Reads and writes that obey these numbers are called quorum reads and writes.
Try to make the read miss the write
Write succeeds. Sent to all 3 in parallel, it needs 2 acknowledgements; 3 replicas are up. In the worst case only 2 actually have it. Writes tolerate 1 unavailable replica.
Read sees v7. Even the read set chosen to dodge the write, replicas 1 and 3, must include replica 1, and the highest version wins. Reads tolerate 1 unavailable replica.
The dial does not show a lucky case: it lands the write on exactly w replicas and then picks the read set that avoids them as hard as it can. Whenever w + r > n, it fails to avoid them. A common choice is n odd, typically 3 or 5, with w = r = (n + 1) / 2 rounded up. A read-heavy workload might set w = n and r = 1, which makes reads faster at the cost of one failed node making every write fail. Normally reads and writes are always sent to all n replicas in parallel; w and r only decide how many responses to wait for. If fewer than w or r nodes are available, the operation returns an error, and it does not matter why a node is unavailable: crashed, out of disk, or behind a network interruption. Only whether it returned a successful response.
The n in a quorum is the number of replicas for one key, not the number of nodes in the cluster. In a partitioned cluster (chapter 6), a value is stored on only some of the nodes.
Limitations of quorum consistency
Quorums need not be majorities: all that matters is that the set of nodes used by the read and the set used by the write overlap in at least one node. Set w and r smaller so w + r ≤ n, as in the dial’s last preset, and stale reads become more likely in exchange for lower latency and higher availability. But even with w + r > n there are edge cases where stale values come back.
Monitoring staleness
In leader-based replication, the database typically exposes metrics for replication lag: subtract a follower’s current position in the log from the leader’s. With leaderless replication there is no fixed order in which writes are applied, which makes it harder, and if a database uses only read repair, there is no limit to how old a value might be. Eventual consistency is a deliberately vague guarantee, and for operability it is important to be able to quantify “eventual.”
Sloppy quorums and hinted handoff
Quorums are not as fault-tolerant as they could be. A network interruption can easily cut a client off from a large number of database nodes, which, to that client, might as well be dead. In a large cluster, with significantly more than n nodes, the client can probably still reach some nodes, just not the ones a value lives on. Return errors for every request that can’t reach a quorum? Or accept writes anyway, on nodes that are reachable but aren’t among the n home nodes?
Sloppy quorum
The latter. Writes and reads still require w and r successful responses, but those may include nodes outside the designated n. The book’s analogy: lock yourself out of your house, and you may knock on the neighbour’s door and ask whether you may stay on their couch temporarily. It increases write availability: as long as any w nodes are available, the database can accept writes.
Hinted handoff
Once the network interruption is fixed, any writes that one node temporarily accepted on behalf of another are sent to the appropriate home nodes. Until then, even with w + r > n, you cannot be sure to read the latest value. A sloppy quorum isn’t a quorum at all in the traditional sense, only an assurance of durability. Enabled by default in Riak, disabled by default in Cassandra and Voldemort.
Leaderless replication suits multi-datacenter operation too. Cassandra and Voldemort count replicas in all datacenters in n, send each write to all of them, and usually wait only for a quorum within the local datacenter. Riak keeps all client communication local to one datacenter, with n describing replicas within it, and replicates between datacenters asynchronously in the background, in a style similar to multi-leader replication.
Two clients, one key, no leader to decide
Dynamo-style databases allow several clients to concurrently write to the same key, which means conflicts occur even if strict quorums are used. It is the multi-leader problem again, and it can also arise during read repair or hinted handoff. The book’s figure: clients A and B write key X at the same time, and the requests arrive at each node in a different order.
Every node keeps whatever arrived last
Node 1 never receives B’s write because of a transient outage; node 2 gets A then B; node 3 gets B then A. If each node simply overwrote the value whenever it received a write, they would end up holding A, B, A, and stay that way: permanently inconsistent. To become eventually consistent, the replicas must converge, and the database’s replication implementations are of little help: you need to know a fair amount about the internals of your database to avoid losing data.
Last write wins: discarding concurrent writes
One approach: each replica only stores the most “recent” value. But since the writes are concurrent, their order is undefined, so an arbitrary one is forced: attach a timestamp to each write, keep the biggest. LWW is the only conflict resolution method in Cassandra and an optional feature in Riak. It achieves convergence at the cost of durability: several concurrent writes all reported successful to their clients, because each reached w replicas, and only one survives, the others silently discarded. It may even drop writes that are not concurrent, because of clock skew (chapter 8). The only safe way to use it is to ensure a key is written only once and thereafter treated as immutable: Cassandra’s recommendation is a UUID as the key, giving each write a unique key.
The happens-before relationship
How do you decide whether two operations are concurrent? The overtaking update earlier was not concurrent: B’s increment was applied to the value A inserted, so B’s operation builds on A’s and is causally dependent on it. The two writes to X just above are concurrent: when each client started, it did not know the other was writing the same key.
Happens-before
An operation A happens before B if B knows about A, or depends on A, or builds upon A in some way. If one happens before the other, the later one may overwrite the earlier.
Concurrent
Two operations are concurrent if neither happens before the other: neither knows about the other. Then there is a conflict to resolve. It is not about time: two operations can be concurrent even if one physically happened long after the other, as long as no information reached the second about the first.
Capturing the happens-before relationship
The book’s algorithm, for a single replica, tracks this with a version number per key: the server increments it on every write and stores it with the value, a client must read before writing and send back the version it read, and the version tells the server which state the write was based on. Below it is run, not drawn: two clients concurrently adding to one shopping cart.
Two clients, one cart, five writes
[milk]with no version| version | value on the server | why |
|---|---|---|
| 1 | [milk] | the new write |
[milk][eggs]with no version| version | value on the server | why |
|---|---|---|
| 1 | [milk] | kept · 1 > 0, concurrent |
| 2 | [eggs] | the new write |
[milk] and [eggs][milk, flour]based on version 1| version | value on the server | why |
|---|---|---|
| 1 | [milk] | overwritten · 1 ≤ 1 |
| 2 | [eggs] | kept · 2 > 1, concurrent |
| 3 | [milk, flour] | the new write |
[eggs] and [milk, flour][eggs, milk, ham]based on version 2| version | value on the server | why |
|---|---|---|
| 2 | [eggs] | overwritten · 2 ≤ 2 |
| 3 | [milk, flour] | kept · 3 > 2, concurrent |
| 4 | [eggs, milk, ham] | the new write |
[milk, flour] and [eggs, milk, ham][milk, flour, eggs, bacon]based on version 3| version | value on the server | why |
|---|---|---|
| 3 | [milk, flour] | overwritten · 3 ≤ 3 |
| 4 | [eggs, milk, ham] | kept · 4 > 3, concurrent |
| 5 | [milk, flour, eggs, bacon] | the new write |
[eggs, milk, ham] and [milk, flour, eggs, bacon]The server determines whether two operations are concurrent by looking at the version numbers alone; it never interprets the value. The run ends with 2 siblings at version 5, the book’s figure exactly. No data was silently dropped, but the clients now carry the extra work of merging siblings.
Merging concurrently written values
Picking one sibling by version number or timestamp is last write wins again, and loses data. For a cart, take the union: here [eggs, milk, ham] and [milk, flour, eggs, bacon] merge to [milk, flour, eggs, bacon, ham]. But if a sibling had an item removed, the union would bring it back. So a removal leaves a marker with an appropriate version number, a tombstone, saying the item was removed. Merging in application code is complex and error-prone, which is exactly what CRDTs are for.
Version vectors
With several replicas and no leader, one number isn’t enough: you need a version number per replica as well as per key. Each replica increments its own when processing a write, and keeps track of the numbers it has seen from each of the others. The collection is a version vector (Riak 2.0 uses a variant, the dotted version vector, and calls it the causal context). It travels to clients on reads and back on writes, and lets the database tell overwrites from concurrent writes, so it is safe to read from one replica and write back to another.
Version vectors and vector clocks are not quite the same thing, though they are often confused. They are similar, with subtle differences; when comparing the state of replicas, version vectors are the right data structure.
Did it stick?
1. What are the three reasons the chapter gives for replicating data?
2. Why is it impractical for every follower to be synchronous?
3. What makes it possible to set up a new follower without downtime?
4. In the GitHub incident, why did promoting an out-of-date follower disclose private data?
5. What is the trade-off in choosing the failover timeout?
6. Why does statement-based replication break?
7. What is the main operational drawback of write-ahead log shipping?
8. A user posts a comment, reloads, and the comment is gone; reloading again later, it is back. Which guarantee was missing on the first reload?
9. How can monotonic reads be achieved simply?
10. Which is NOT a reason given for multi-leader replication across datacenters?
11. With n = 5, w = 3, r = 3, how many unavailable replicas can reads and writes each tolerate, and why does a read see the latest value?
12. In the shopping cart algorithm, what does the server do with a write carrying version number k?
Answered 0 of 12 · 0 correct
The terms this chapter installs
Chapter 5 in one breath. Replication serves high availability, keeping the system running when a machine or a datacenter goes down; disconnected operation, letting an application keep working through a network interruption; latency, placing data near users; and scalability, handling more reads than one machine can. Despite being a simple goal, keeping a copy of the same data on several machines, it turns out to be remarkably tricky, requiring careful thought about concurrency and about everything that can go wrong.
Three approaches. Single-leader: clients send all writes to one node, which streams changes to the followers; reads on followers might be stale. Popular because it is fairly easy to understand and there is no conflict resolution to worry about. Multi-leader: several nodes accept writes and send changes to each other. Leaderless: clients send each write to several nodes and read from several in parallel, to detect and correct stale data. Multi-leader and leaderless can be more robust against faulty nodes, network interruptions and latency spikes, at the cost of being harder to reason about and providing only very weak consistency guarantees.
Replication can be synchronous or asynchronous, which has a profound effect on behaviour when there is a fault: asynchronous replication can be fast when the system is running smoothly, but figure out what happens when replication lag increases and servers fail. A few consistency models help decide how an application should behave under lag: read-after-write, users always see data they submitted themselves; monotonic reads, after seeing data at one point in time they don’t later see it from an earlier point; and consistent prefix reads, they see data in a state that makes causal sense. And the concurrency issues that are inherent in multi-leader and leaderless replication come down to one question, answered with version numbers: did one write know about the other? If it did, it overwrites; if it didn’t, they are siblings, and someone has to merge them.
Study aid built for recall practice. Concepts, examples, figures and named systems are Martin
Kleppmann’s, from Designing Data-Intensive Applications, chapter 5. Go back to the book for his
wording and the full reference list. The timings in the diagrams are illustrative, but nothing in
a caption is typed in by hand: src/lib/ddia5.ts draws every arrow from one table and computes
every verdict from the same one, and the shopping cart is the book’s algorithm actually run, which
reproduces its figure 5-13 sibling for sibling. The GitHub incident is real; its row numbers and
names here are a miniature.