The Trouble with Distributed Systems
Designing Data-Intensive Applications · Chapter 8 · Recall lab
The last few chapters kept saying “and if something goes wrong.” This chapter is about what goes wrong. It is deliberately pessimistic: an experienced operator will tell you that anything that can go wrong will go wrong, and working with distributed systems is fundamentally different from writing software on a single computer, because there are so many new and exciting ways for things to fail. The job of an engineer is to build systems that do their job anyway.
Some parts broken, others fine, and no telling which
A program on a single computer is deterministic: the same operation gives the same result, and if the hardware is faulty the usual consequence is total failure, a kernel panic or a blue screen. Computers are designed that way on purpose; a wrong result is worse than a crash. A distributed system has no such luxury. Some parts can be broken in unpredictable ways while others work fine: a partial failure, and partial failures are nondeterministic. You may not even know whether something succeeded.
The book’s list of what operators have seen is worth reading slowly: long-lived network partitions in a datacenter, power distribution unit failures, switch failures, accidental power cycles of whole racks, whole-datacenter backbone failures, whole-datacenter power failures, and a hypoglycemic driver smashing a Ford pickup truck into a datacenter’s HVAC system.
Supercomputers
High-performance computing runs batch jobs that checkpoint their state to durable storage. If a node fails, the common answer is to stop the whole cluster and restart from the last checkpoint. That makes a supercomputer more like a single-node computer: partial failure is escalated into total failure.
Internet services
Online and expected to serve users at low latency, so stopping the cluster is not acceptable. Built from commodity machines that fail more often, over IP and Ethernet rather than specialized topologies, at a size where something is always broken, upgraded with rolling restarts, and often spread across the internet. They have to tolerate partial failure in software.
Building a reliable system from unreliable components is an old idea. Error-correcting codes transmit digital data accurately over a channel that occasionally flips bits; TCP gives you ordered, reliable delivery over an IP layer that drops, delays and duplicates packets. The result is more reliable than its parts, though never perfectly so: TCP can hide a lost packet, not a slow network.
You sent a request. Then what?
The systems in this book are shared-nothing: machines with their own memory and disks, which can only communicate over a network. The internet and most datacenter networks are asynchronous packet networks: a node can send a message to another, and the network gives no guarantee when it will arrive, or whether it will arrive at all. Here are six things that can happen to one request, and what the client sees in each.
One request, six fates, figure 8-1
Someone unplugged a cable, a switch dropped it, a buffer overflowed. The node never heard of it.
What the client sees at its timeout: no reply. Did the operation happen? No.
The network or the receiving node is overloaded, and the request sits in a queue. It will be delivered, and acted on, later.
What the client sees at its timeout: no reply. Did the operation happen? Yes. A reply does turn up, after the client has given up on it.
It crashed, or it was powered down. The request arrived at a machine that is not running.
What the client sees at its timeout: no reply. Did the operation happen? No.
A long garbage collection pause, say. It will carry on as if nothing happened, and answer late.
What the client sees at its timeout: no reply. Did the operation happen? Yes. A reply does turn up, after the client has given up on it.
The request was processed, and then the response was lost on the network, perhaps because a switch was misconfigured.
What the client sees at its timeout: no reply. Did the operation happen? Yes.
The response is delayed in the network, or the client’s own machine is overloaded and has not read it yet.
What the client sees at its timeout: no reply. Did the operation happen? Yes. A reply does turn up, after the client has given up on it.
The six side by side, as the client sees them
| fate | did the operation happen? | reply before the timeout? |
|---|---|---|
| Request lost | no | no |
| Request queued | yes | no, it comes later |
| Node crashed | no | no |
| Node paused | yes | no, it comes later |
| Reply lost | yes | no |
| Reply delayed | yes | no, it comes later |
The operation ran in 4 of the 6, and the client saw a reply in time in 0. The sender cannot even tell whether the packet was delivered; the only option is for the recipient to send a reply, which may itself be lost or delayed. The usual way of handling it is a timeout, and when it fires you still do not know whether the remote node got the request.
Network faults in practice
One study of a medium-sized datacenter found about 12 network faults a month, half disconnecting a single machine and half an entire rack. Redundant networking gear helps less than hoped, because it does not guard against human error, such as misconfigured switches, a major cause of outages. A switch software upgrade can trigger a topology reconfiguration that delays packets for over a minute. Sharks bite undersea cables. An interface can drop all inbound packets while sending outbound ones fine. When one part of the network is cut off from the rest, that is a network partition.
Detecting faults
Sometimes you get explicit feedback: a TCP RST or FIN if nothing is listening on the port, a script that notifies others when a process crashes (HBase does this), a switch’s management interface reporting a dead link, an ICMP Destination Unreachable. But you cannot count on it. If you want to be sure a request succeeded, you need a positive response from the application itself. Handling a fault can be as simple as showing an error, but you need to know how the software reacts, which is why people trigger network problems deliberately and test.
How long is long enough?
A long timeout means a long wait until a node is declared dead, and users waiting or seeing errors meanwhile. A short one detects faults faster and declares nodes dead that were only slow. That is not harmless: if the node was in the middle of an action, such as sending an email, another node takes over and does it again, and moving its load onto other nodes can cascade, until every node has declared every other one dead.
If the network guaranteed delivery within a time d, and every healthy node answered within a time r, then 2d + r would be a sound timeout. Asynchronous networks have unbounded delays, and most servers cannot promise a maximum response time either. The variability comes mostly from queues: a switch queueing packets bound for a busy link, an operating system queueing a request while every CPU core is busy, a hypervisor pausing a virtual machine for tens of milliseconds, TCP’s own flow control holding data back before it enters the network, and TCP’s retransmission timer turning a lost packet into a delay. Move the load and the timeout below.
Four thousand round trips against a timeout
Median 6.0 ms, p99 24 ms, p99.9 396 ms. 3.8 in every 1,000 healthy requests take longer than the timeout, and each one would make a live node look dead.
The bump far to the right is the rare long pause: a garbage collection, or a virtual machine that was not scheduled. No timeout short enough to be useful avoids all of them.
The sensible approach is to choose timeouts experimentally: measure the distribution of round-trip times over an extended period and across many machines. Better still, measure continuously and adjust the timeout automatically, which is what a Phi Accrual failure detector does, in Akka and Cassandra; TCP’s retransmission timeouts work similarly. In a public cloud, a noisy neighbor using a lot of shared resources can push your delays around too. Latency-sensitive applications such as videoconferencing and VoIP use UDP instead of TCP, trading reliability for less variability: data that arrives late is worthless, so it is not retried.
Why telephone calls do not have this problem
A call over the fixed-line network establishes a circuit: a fixed, guaranteed amount of bandwidth along the whole route. An ISDN call gets 16 bits in each of 4,000 frames a second, and nothing else can use them, so there is no queueing and the delay is bounded. That suits an audio call, which needs a constant number of bits a second.
Why datacenters do not use circuits
A web page, an email or a file transfer has no particular bandwidth requirement; it wants to finish as quickly as possible. A circuit would make you guess an allocation, too low and slow, too high and unavailable, while TCP adapts to whatever is free. Packet networks are optimized for bursty traffic. Variable delay is the cost of dynamic resource sharing and the high utilization it buys: a trade-off, not a law of nature.
Every machine has its own idea of the time
Applications need clocks for durations (has this request timed out, what is the 99th percentile response time, how many queries a second) and for points in time (when was this article published, when should the reminder go out, when does this cache entry expire). Each machine has its own clock, usually a quartz crystal oscillator, and none of them is perfectly accurate. The Network Time Protocol (NTP) adjusts them from servers that get the time from something better, such as a GPS receiver.
Time-of-day clocks
The current date and time: clock_gettime(CLOCK_REALTIME) on Linux, System.currentTimeMillis() in
Java, seconds since the epoch, midnight UTC on 1 January 1970, ignoring leap seconds. Synchronized
with NTP, so a timestamp from one machine ideally means the same as one from another. But if the
local clock is too far ahead, it may be forcibly reset and appear to jump back in time, which
makes it unsuitable for measuring elapsed time.
Monotonic clocks
clock_gettime(CLOCK_MONOTONIC), System.nanoTime(): guaranteed always to move forward. Its
absolute value is meaningless (perhaps nanoseconds since boot) and cannot be compared across
machines, but the difference between two readings on one machine is a good duration. NTP may
slew it, speeding it up or slowing it down by up to 0.05%, but never makes it jump. Usually
the right clock for a timeout.
Quartz drifts, running faster or slower depending on the temperature. Google assumes a drift of up to 200 parts per million for its servers. That one number is enough to work out how far a clock can wander between resyncs:
A quartz clock drifting between NTP resyncs
Just before each resync the clock is 6.0 ms ahead. That is the book’s figure: Google assumes 200 ppm for its servers, which is 6.0 ms after 30 seconds and 17 s after a day.
Every vertical line is the time-of-day clock jumping backwards when NTP resets it, which is why it must never be used to measure an elapsed time; a monotonic clock is slewed instead, by at most 0.05%.
And then everything else
If a clock differs too much from the NTP server, it may refuse to synchronize or be forcibly reset. A node can be accidentally firewalled off from NTP and nobody notices. NTP is only as good as the network delay: one experiment found a minimum error of 35 ms over the internet, with spikes of up to a second. Some NTP servers are simply wrong, by hours. Leap seconds have crashed large systems; smearing them over a day avoids that. In a virtual machine the clock is virtualized, and a VM paused for tens of milliseconds sees its clock jump forward. On devices you do not control, the user may set the clock to any date they like. Very good accuracy is possible (MiFID II requires high-frequency trading firms to stay within 100 microseconds of UTC), with GPS receivers, the Precision Time Protocol and careful monitoring. It does not come by default.
Timestamps that put events in the wrong order
An incorrect clock does not crash anything. Most things keep working while it drifts, and the damage is silent data loss. So if your software requires synchronized clocks, you must monitor the offsets between all machines and declare any node that drifts too far dead. The most common place clocks do damage is ordering: the chapter’s example is last write wins, the conflict resolution of chapter 5, deciding by timestamp.
Last write wins, with and without a few milliseconds of skew, figure 8-3
What last write wins gets wrong
Writes can mysteriously disappear: a node with a lagging clock cannot overwrite what a node with a fast clock wrote until the skew has elapsed. LWW cannot tell writes that happened in quick succession from truly concurrent ones (version vectors can). Two nodes can produce the same millisecond timestamp. And “most recent” depends on a local clock that may well be wrong. Logical clocks, incrementing counters that capture only relative order, are the safer tool.
A reading is a range, not a point
Nanosecond resolution is not nanosecond accuracy. A clock synced with a local NTP server every
minute is likely off by several milliseconds; over the public internet, tens of milliseconds, with
spikes past a hundred. A reading is better thought of as a confidence interval: 95% sure the
time is between 10.3 and 10.5 seconds past the minute. Most APIs hide this. Google’s TrueTime,
in Spanner, returns it: [earliest, latest].
Snapshot isolation needs a monotonically increasing transaction ID, which is easy on one node and a bottleneck across many. Spanner uses TrueTime instead. If two intervals do not overlap, one transaction definitely came after the other; if they do, nobody can say. So Spanner makes them not overlap:
TrueTime intervals and Spanner's commit wait
Google keeps its clocks within about 7 ms with a GPS receiver or atomic clock in every datacenter, and that ε is the price of every read-write transaction. Distributed transaction semantics built on clocks remain an area of research; no mainstream database outside Google implements them.
A thread can stop at any line, for any length of time
A node in a single-leader database needs to know it is still the leader before accepting writes. One approach is a lease: a lock with a timeout, which the leader must keep renewing. The book’s example is a request loop that renews the lease whenever less than 10 seconds remain, and only processes a request while the lease is valid.
Example 8-1: a lease that looks safe
while (true) {
request = getIncomingRequest();
// Ensure that the lease always has at least 10 seconds remaining
if (lease.expiryTimeMillis - System.currentTimeMillis() < 10000) {
lease = lease.renew();
}
if (lease.isValid()) {
process(request);
}
}Two things are wrong with it. It compares an expiry time set by another machine’s clock with the
local one, so a few seconds of skew breaks it. And even with a monotonic clock, it assumes very little
time passes between checking lease.isValid() and calling process(request). If the thread is paused
for 15 seconds right there, the lease has expired, another node is leader, and this one goes ahead
anyway. Nothing tells the thread it was paused. Here are the ways it can be:
A node in a distributed system must assume its execution can be paused for a significant length of time at any point, even in the middle of a function, while the rest of the world moves on and may declare it dead. On a single machine, multithreaded code has mutexes, semaphores, atomic counters and blocking queues; none of them translates across a network.
Hard real-time is expensive
Aircraft, rockets, robots and cars must respond within a deadline, or the system fails. That takes a real-time operating system, libraries that document worst-case execution times, restricted or forbidden dynamic memory allocation, and an enormous amount of testing. It also means low throughput: real-time is not high performance. For most server-side data processing, not worth it.
Limiting the damage of garbage collection
Treat a GC pause as a brief planned outage: the runtime warns that a node will soon need one, the application stops sending it requests, lets it drain, and collects with nothing in flight. Some latency-sensitive trading systems do this. Or use the collector only for short-lived objects and restart processes periodically, one at a time with traffic shifted away, before a full collection is ever needed.
The truth is defined by the majority
A node cannot know anything for sure. It can only guess from the messages it has received, or not received. Imagine a node that receives everything sent to it while its outgoing messages are dropped: everyone else declares it dead, however well it is working. Or a node that comes back from a long garbage collection pause to find the others have declared it dead, loaded it onto the hearse, and moved on. A node cannot trust its own judgment of the situation.
So distributed algorithms rely on a quorum: a decision needs votes from a minimum number of nodes, usually an absolute majority. Three nodes can tolerate one failure, five can tolerate two, and it is safe because there can only be one majority at a time. That matters whenever a system needs exactly one of something: one leader per partition, one holder of a lock, one owner of a username. A node believing it is the chosen one does not make it so.
A lease, a pause, and the token that catches it, figures 8-4 and 8-5
Byzantine faults
Fencing tokens catch a node acting in error. A node that deliberately lies could send a fake token. A system that keeps working when some nodes malfunction, disobey the protocol or are controlled by an attacker is Byzantine fault-tolerant, after the Byzantine Generals Problem of reaching agreement despite traitors. Byzantine algorithms need more than two-thirds of nodes to be honest (four nodes tolerate one), and they matter in aerospace, where radiation corrupts memory, and among organizations that do not trust each other, as in Bitcoin and other blockchains.
Why most systems do not bother
Inside one organization’s datacenter, all nodes are assumed honest, and Byzantine protocols are too costly to be practical. They do not help against bugs either, unless you write four independent implementations, nor against an attacker who can compromise one node and so probably all of them. Weak forms of lying are still worth guarding against: application-level checksums for corruption TCP misses, input validation and size limits, and NTP clients that ask several servers and discard the outlier.
Timing assumptions times failure assumptions
To reason about an algorithm despite all of this, you write down what it may assume: a system model. The book gives three models of timing and three of node failure. Each algorithm is proved correct, or not, in one combination.
Three timing models against three fault models
| Crash-stopA node fails only by crashing, and never comes back. | Crash-recoveryA node may crash and come back after some unknown time, keeping what was on stable storage and losing its memory. | ByzantineA node may do absolutely anything, including trying to trick and deceive the others. | |
|---|---|---|---|
| SynchronousBounded network delay, bounded process pauses, bounded clock error. Not realistic. | too optimistic | too optimistic | too optimistic |
| Partially synchronousBehaves synchronously most of the time, and sometimes exceeds the bounds by any amount. Realistic. | the model most useful for real systems | Byzantine fault tolerance: blockchains, aerospace | |
| AsynchronousNo timing assumptions at all, not even a clock, so no timeouts. Very restrictive. |
Safety
Nothing bad happens. Uniqueness of fencing tokens, and their monotonic order, are safety properties. If one is violated you can point at the moment it was broken, and it cannot be undone. Distributed algorithms usually require safety to hold in every situation the model allows: even if every node crashes, the algorithm must never return a wrong result.
Liveness
Something good eventually happens. A node that asks for a token and does not crash eventually gets one; eventual consistency is a liveness property. It may not hold at a given moment, but you can hope it will. Liveness is allowed caveats: only if a majority of nodes are up, only once the network recovers, which is what the partially synchronous model promises.
Models are simplifications. Crash-recovery assumes stable storage survives, and real disks get
corrupted, wiped by misconfiguration, or go unrecognized after a firmware bug. A quorum algorithm
breaks if a node forgets data it claimed to have stored. So real implementations still need code
for the impossible case, even if it amounts to printf("Sucks to be you") and exit(666), leaving a
human to clean up. Theoretical analysis and empirical testing are equally important.
Did it stick?
1. What is the defining characteristic of a distributed system, as opposed to a single computer?
2. A client sends a request and gets no reply. What can it conclude?
3. Why does adding redundant networking gear not reduce network faults as much as hoped?
4. What is the trade-off in choosing a timeout?
5. Why do packet networks have unbounded delays when telephone circuits do not?
6. Which clock should you use to measure how long a request took?
7. Google assumes its servers’ clocks drift by up to 200 ppm. How far can one drift between daily resyncs?
8. Why is last write wins with time-of-day timestamps dangerous?
9. How does Spanner use clock uncertainty to order transactions?
10. In Example 8-1, what goes wrong if the thread is paused for 15 seconds just before process(request)?
11. What does a fencing token do?
12. Which is a liveness property, rather than a safety property?
Answered 0 of 12 · 0 correct
The terms this chapter installs
Chapter 8 in one breath. Whenever you send a packet over the network it may be lost or delayed arbitrarily, and so may the reply, so if you hear nothing you have no idea whether it got through. A node’s clock may be significantly out of sync with the others, may jump forward or back, and relying on it is dangerous, especially without a confidence interval: a 200 ppm drift is 17 seconds a day. A process may pause for a substantial amount of time at any point in its execution, be declared dead, and come back to life without realizing it.
Partial failures are the defining characteristic of distributed systems, and software has to tolerate them. Detecting a fault mostly means timeouts, which cannot tell a network failure from a node failure and make live nodes look dead under variable delay; a node that is merely limping, its network interface down to a trickle by a driver bug, is harder still. Tolerating a fault is not easy either: there is no global variable, no shared memory, no common knowledge. Major decisions cannot be made by a single node, and need protocols that enlist the others and get a quorum to agree. That is the next chapter.
If you can keep things on a single machine, it is generally worth doing so. But fault tolerance and low latency, not only scalability, push systems apart, and the unreliability of networks, clocks and processes is not inevitable: hard real-time guarantees and bounded delays exist, at a high price in cost and utilization. Most systems choose cheap and unreliable over expensive and reliable, and build their reliability in software.
Study aid built for recall practice. Concepts, examples, figures and named systems are Martin
Kleppmann’s, from Designing Data-Intensive Applications, chapter 8. Go back to the book for his
wording and the full reference list. The timings in the diagrams and the queueing model’s
parameters are illustrative; the drift figures, the lease code and the fencing tokens 33 and 34 are
the book’s. Every verdict a caption states is computed by src/lib/ddia8.ts from the same numbers
its drawing uses.