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

The Trouble with Distributed Systems

A deliberately pessimistic tour of what goes wrong once software spans machines: unreliable networks, unreliable clocks and process pauses. It then covers how to reason about knowledge and truth when no node can be sure of anything.

Key takeaways

  • Partial failure (some parts broken, others fine, nondeterministically) is the defining trait of distributed systems.
  • In an asynchronous network, a missing reply is ambiguous: request lost, node dead or slow, or reply lost. A timeout is the only practical detector, and it cannot tell these apart.
  • Network delays are unbounded because packet switching with queueing trades predictability for utilization. No timeout value is "correct"; measure it, or adapt it (Phi Accrual).
  • Use monotonic clocks for durations. Time-of-day clocks drift, jump and carry an unknown error, so they are dangerous for ordering events (LWW silently drops writes).
  • A clock reading is really a confidence interval; Spanner's TrueTime exposes it and waits it out to order transactions.
  • Any process can pause for seconds or minutes (GC, VM suspend, swapping) without noticing. Leases checked against clocks are therefore unsafe on their own.
  • A node cannot trust its own judgment: decisions go to a majority quorum, and resources must reject stale lock holders using fencing tokens.
  • Reason with a system model (usually partially synchronous plus crash-recovery). Safety properties must always hold; liveness may carry caveats.

Faults and Partial Failures

Earlier chapters (failover, replication lag, weak isolation) were still too optimistic. This chapter assumes that anything that can go wrong will go wrong.

  • A single computer with good software is deterministic: it either works or fails totally (kernel panic). It is designed this way, preferring a crash to a wrong result, and it presents an idealized model of perfect computation.
  • Across a network that idealization is gone. Physical reality intrudes: switch failures, power failures for racks or whole datacenters, long-lived partitions, and even a truck driven into a datacenter's cooling system.
  • Partial failure: some parts are broken in unpredictable ways while others work. Partial failures are nondeterministic. An operation over several nodes may sometimes work and sometimes fail, and you may not even know whether it succeeded.
Single computer Works or Crashed deterministic, all-or-nothing Distributed system OK Down OK Slow? OK partial, nondeterministic
One machine fails as a whole; a distributed system fails in parts, unpredictably.

Cloud Computing and Supercomputing

  • High-performance computing (HPC): supercomputers with thousands of CPUs for scientific jobs such as weather forecasting. Cloud computing: multi-tenant datacenters, commodity machines on IP/Ethernet, elastic allocation, metered billing. Enterprise datacenters sit in between.
  • Supercomputers checkpoint state. When a node fails they stop the whole workload and restart from the last checkpoint. Partial failure escalates to total failure, like a single machine.

Internet services differ from supercomputers:

  • They are online and need low latency at all times, so stopping the cluster for repair is unacceptable. Batch jobs can be restarted cheaply.
  • Supercomputer nodes are specialized and reliable, talking over shared memory and RDMA. Cloud nodes are commodity machines: cheaper for the same performance, but with higher failure rates.
  • Datacenter networks use IP/Ethernet in Clos topologies for high bisection bandwidth. HPC uses meshes and toruses suited to known communication patterns.
  • With thousands of nodes, something is always broken. If the strategy is to give up on any fault, a large system spends much of its time recovering.
  • Tolerating failed nodes enables rolling upgrades, and in the cloud you can simply replace a badly performing VM.
  • Geo-distributed deployments talk over the slow, unreliable internet. Supercomputers assume their nodes are close together.

So we must accept partial failure and build fault tolerance into the software: a reliable system from unreliable components. Even a small system eventually hits faults, so fault handling is part of the design. Test unlikely faults deliberately; suspicion, pessimism and paranoia pay off.

Building a Reliable System from Unreliable Components

  • A system is not limited to the reliability of its weakest part. Error-correcting codes carry data accurately over a channel that flips bits. TCP over unreliable IP retransmits lost packets, removes duplicates and restores order.
  • There is always a limit. Codes fail when interference swamps the signal, and TCP cannot remove network delay.
  • The higher layer is still useful: it handles tricky low-level faults, so the remaining faults are easier to reason about.
TCP (more reliable) retransmit, dedupe, reorder IP (unreliable) drop, delay, duplicate, reorder delay still leaks up
A reliable layer on an unreliable base hides some faults, but not all (TCP cannot remove delay).

Unreliable Networks

The book focuses on shared-nothing systems. Each machine has its own memory and disk, and the network is the only channel. This is the dominant approach because it needs no special hardware, can use commodity cloud services, and gains reliability through redundancy across datacenters.

The internet and most datacenter networks are asynchronous packet networks. There is no guarantee when a packet arrives, or whether it arrives at all. When a request gets no response:

  1. The request was lost (for example, an unplugged cable).
  2. The request is waiting in a queue (the network or recipient is overloaded).
  3. The remote node failed (crashed or powered down).
  4. The remote node is temporarily unresponsive (for example, a long GC pause).
  5. The node processed it, but the response was lost (for example, a misconfigured switch).
  6. The node processed it, but the response is delayed.
(a) request lost (b) node down (c) response lost Client Node X Client Node X Client Node X Client sees the same thing in all three: no response yet
Figure 8-1, simplified: without a response you cannot tell which failure happened.
  • The sender cannot even tell whether a packet was delivered. Only a response says so, and that response can also be lost or delayed.
  • The usual remedy is a timeout. When it fires you still do not know whether the node got the request, and a queued request may still be delivered after you gave up.

Network Faults in Practice

  • Network problems are surprisingly common, even inside one company's datacenter. One study of a medium-sized datacenter found about 12 network faults per month: half disconnected a single machine, half a whole rack.
  • Another study found that redundant networking gear helps less than hoped, because it does not guard against human error (misconfigured switches), a major cause of outages.
  • Public clouds such as EC2 have frequent transient glitches. Other examples: a switch software upgrade causing a topology reconfiguration that delayed packets for over a minute, sharks biting undersea cables, and a NIC that dropped all inbound packets while outbound ones still worked. A link working in one direction says nothing about the other.
  • Network partition / netsplit: one part of the network cut off from the rest. The book says network fault to avoid confusion with storage partitions (shards).
  • Untested fault handling can do arbitrarily bad things: a cluster that deadlocks permanently even after the network recovers, or one that deletes all your data.
  • Handling faults need not mean tolerating them. Showing users an error during network trouble can be valid, but you must know how the software reacts and make sure it recovers. Deliberately trigger faults to test this (the idea behind Chaos Monkey).

Detecting Faults

Load balancers must take dead nodes out of rotation. Single-leader databases must promote a follower when the leader fails. Sometimes you get explicit feedback:

  • The machine is reachable but no process listens on the port: the OS refuses the connection with a RST or FIN. If the node crashed mid-request, though, you cannot know how much was processed.
  • The process crashed but the OS is alive: a script can notify other nodes so one takes over without waiting for a timeout (HBase does this).
  • With access to the datacenter switches' management interface, you can query link failures at the hardware level. This is not possible over the internet, in shared datacenters, or when the interface itself is unreachable.
  • A router sure that an IP is unreachable may send ICMP Destination Unreachable, but it has no special detection powers either.
  • Rapid feedback is useful but cannot be counted on. A TCP ack does not mean the application handled the packet; certainty requires a positive response from the application.
  • In general assume you get no response at all: retry a few times (TCP retries transparently; you may also retry at the application level), wait for a timeout, then declare the node dead.

Timeouts and Unbounded Delays

Long timeoutShort timeout
DetectionSlow: users wait or see errors meanwhileFast
RiskLow risk of false deathDeclares nodes dead during a mere load spike
  • Declaring a live node dead prematurely risks doing an action twice (for example, sending an email) when another node takes over.
  • Moving a "dead" node's responsibilities adds load to other nodes and the network. If the node was only overloaded, this can cause a cascading failure, in the extreme with every node declaring the others dead.
  • Thought experiment: if every packet arrived within d or was lost, and a live node always handled a request within r, then 2d + r would be a sound timeout.
  • Real systems have neither guarantee. Asynchronous networks have unbounded delays, and most servers cannot bound handling time. Being fast most of the time is not enough: with a low timeout, one transient spike in round-trip times throws the system off balance.
Client Server ≤ d ≤ r ≤ d timeout = 2d + r Only valid if d and r are bounded; real networks and servers bound neither
With bounded delays, 2d + r would be a safe timeout. Asynchronous networks give no such bound.

Network congestion and queueing. Packet delay varies mostly because of queueing, much as road travel time varies with traffic:

  • When several nodes send to one destination, the switch queues the packets and feeds them onto the link one by one: network congestion. If the queue fills, packets are dropped and must be resent, even though the network works.
  • At the destination, if all CPU cores are busy, the OS queues the request until the application is ready, which can take arbitrarily long.
  • In VMs, the OS is often paused for tens of milliseconds while another VM uses the core. The hypervisor buffers incoming data meanwhile.
  • TCP flow control (congestion avoidance, backpressure) limits the sender's own rate, adding queueing before data even enters the network.
  • TCP treats an unacknowledged packet as lost after a timeout computed from observed round-trip times, then retransmits. The application never sees the loss, only the delay.
Port 1 Port 2 Port 4 Switch queue for port 3 Port 3 full queue: drop
Figure 8-2, simplified: several senders to one destination fill its switch queue.
  • Queueing delay is widest near maximum capacity: spare capacity drains queues, while high utilization builds long queues quickly.
  • In public clouds and multi-tenant datacenters, links, switches, NICs and CPUs are shared. Batch jobs such as MapReduce can saturate links, and a noisy neighbor makes delays highly variable.
  • So choose timeouts experimentally: measure the round-trip distribution over a long period and many machines, then trade detection delay against premature timeouts.
  • Better still, adapt continually to observed response times and jitter. The Phi Accrual failure detector does this (used in Akka and Cassandra), and TCP retransmission timeouts work similarly.

Synchronous Versus Asynchronous Networks

Why not make the network reliable in hardware? Compare it with the fixed-line telephone network, where delayed audio and dropped calls are very rare.

  • A phone call sets up a circuit: a fixed, guaranteed bandwidth along the whole route for the call's duration. Example: ISDN runs at 4,000 frames per second, and a call gets 16 bits per frame in each direction, so it is guaranteed 16 bits every 250 microseconds.
  • This is a synchronous network. Space is already reserved at each hop, so there is no queueing, and maximum end-to-end latency is fixed: bounded delay.

Can we not simply make network delays predictable?

  • A circuit is reserved bandwidth that nobody else can use. A TCP connection opportunistically uses whatever bandwidth is available and uses none while idle.
  • Ethernet and IP are packet-switched, with no concept of a circuit, so they suffer queueing and unbounded delay.
  • Packet switching is optimized for bursty traffic. Web pages, email and file transfers have no fixed bandwidth need; they just want to finish fast. With a circuit you would have to guess a bandwidth: too low wastes capacity and is slow, too high and the circuit cannot be set up. TCP adapts its rate to available capacity.
  • Hybrids exist. ATM supported both, and InfiniBand has link-layer end-to-end flow control (it can still see link congestion). QoS (prioritization and scheduling) plus admission control (rate-limiting senders) can emulate circuits or give statistically bounded delay.
Circuit (static) Packet (dynamic) call A idle idle idle each slot reserved, even if unused senders jostle for the wire bounded delay low utilization expensive queueing, unbounded delay high utilization cheap
Static partitioning buys bounded latency with wasted capacity; dynamic sharing buys utilization with variable delay.

Latency and Resource Utilization. Variable delay is a consequence of dynamic resource partitioning.

  • A wire between telephone switches carries up to 10,000 calls. It is divided statically: a lone call gets the same fixed slot even when the other 9,999 are unused.
  • The internet shares bandwidth dynamically, and switches pick which packet goes next moment by moment. The cost is queueing; the gain is maximum utilization, which makes each byte cheaper.
  • CPUs are the same: sharing a core between threads means waiting in the run queue, but it uses hardware better than fixed cycle allocations. Better utilization is also a big motivation for VMs.
  • Latency guarantees are possible with static partitioning (dedicated hardware, exclusive bandwidth) but cost more. Multi-tenancy with dynamic partitioning is cheaper but has variable delay.
  • Variable delay is a cost/benefit trade-off, not a law of nature. QoS is not enabled in multi-tenant datacenters, public clouds or the internet, so assume congestion, queueing and unbounded delay. There is no "correct" timeout; determine it experimentally.

Unreliable Clocks

Applications use clocks for durations (has this request timed out? p99 response time? queries per second over five minutes? time a user spent on the site?) and for points in time (when was the article published? when to send the reminder? when does the cache entry expire? log timestamps).

  • Messages take a variable time to travel, so it is hard to order events across machines.
  • Each machine's clock is a hardware device, usually a quartz crystal oscillator, and runs slightly fast or slow.
  • NTP (Network Time Protocol) adjusts clocks to time reported by a group of servers, which in turn get time from a more accurate source such as GPS.

Monotonic Versus Time-of-Day Clocks

Time-of-day clockMonotonic clock
ReturnsDate and time on a calendar (wall-clock time): seconds since the epoch (midnight UTC, 1 Jan 1970), ignoring leap secondsAn arbitrary counter (for example, nanoseconds since boot); only differences mean anything
APIsclock_gettime(CLOCK_REALTIME), System.currentTimeMillis()clock_gettime(CLOCK_MONOTONIC), System.nanoTime()
NTP effectSynced, so timestamps are (ideally) comparable across machines; can be forcibly reset and jump backwardNTP may slew the rate (default up to 0.05%) but never makes it jump
ResolutionHistorically coarse (10 ms steps on older Windows)Usually microseconds or better
Use forPoints in timeDurations and timeouts; never compare across machines
  • Jumps and ignored leap seconds make time-of-day clocks unsuitable for measuring elapsed time.
  • Multi-socket servers may have a timer per CPU. The OS tries to present a monotonic view, but take that guarantee with a pinch of salt.
  • Monotonic clocks are usually fine for timeouts in a distributed system, because they assume no cross-node synchronization.
real time clock value NTP reset: jumps back time-of-day monotonic rate slewed, never jumps
Time-of-day clocks may jump backward; monotonic clocks only move forward.

Clock Synchronization and Accuracy

Time-of-day clocks need NTP or another external source, and both hardware clocks and NTP are fickle:

  • Quartz drifts, varying with temperature. Google assumes 200 ppm: 6 ms drift if resynced every 30 s, 17 s if resynced once a day.
  • If a clock is too far from the NTP server, the client may refuse to sync, or the clock is forcibly reset and applications see time jump.
  • A node accidentally firewalled from NTP can go unnoticed for some time.
  • NTP is only as good as the network delay. Over the internet, a minimum error of 35 ms was achieved, with spikes to about a second; large delays can make the client give up.
  • Some NTP servers are wrong by hours. Clients query several servers and ignore outliers, but you are still betting correctness on a stranger's word.
  • Leap seconds make a 59- or 61-second minute and have crashed many large systems. Smearing (servers applying the adjustment gradually over a day) may be the best fix, though server behavior varies.
  • In VMs the clock is virtualized. While another VM uses the core, a VM pauses for tens of milliseconds, which looks like the clock jumping forward.
  • On devices you do not control (mobile, embedded), the clock cannot be trusted at all; users set wrong dates, for example to cheat time limits in games.
  • High accuracy is possible with enough investment. Draft MiFID II regulation requires high-frequency trading funds to be within 100 microseconds of UTC, to debug "flash crashes" and detect manipulation. This takes GPS receivers, PTP (Precision Time Protocol), careful deployment and monitoring.
  • A misconfigured NTP daemon or blocked NTP traffic lets drift error grow quickly.

Relying on Synchronized Clocks

  • Clocks look simple but have pitfalls: a day may not have 86,400 seconds, time-of-day clocks can move backward, and nodes can disagree widely. As with networks, robust software must be prepared for incorrect clocks.
  • Bad clocks go unnoticed. A bad CPU or network fails loudly, but a drifting clock lets most things keep working, so the likely result is silent, subtle data loss rather than a crash.
  • If software needs synchronized clocks, monitor clock offsets between all machines and declare dead (remove) any node that drifts too far.

Timestamps for ordering events. Figure 8-3 uses a multi-leader database. Client A writes x = 1 on node 1, which replicates to node 3. Client B increments x on node 3 (x = 2). Both writes then replicate to node 2. Each write is tagged with the origin node's time-of-day clock, and the skew is under 3 ms, better than you can expect in practice.

Node 1 Node 3 Node 2 A: x = 1 ts 42.004 B: x += 1 (x = 2) ts 42.003 LWW keeps 42.004: x = 1 B's increment lost
Figure 8-3, simplified: B's write is causally later but gets an earlier timestamp, so LWW drops it.
  • Node 2 sees x = 1 at 42.004 and x = 2 at 42.003, wrongly keeps x = 1, and drops B's increment.
  • This strategy is last write wins (LWW), widely used in multi-leader and leaderless databases such as Cassandra and Riak. Generating timestamps on the client instead does not fix it:
  1. Writes disappear: a node with a lagging clock cannot overwrite values from a fast-clock node until the skew has elapsed. Arbitrary amounts of data are dropped silently, with no error to the application.
  2. LWW cannot tell sequential writes in quick succession from truly concurrent ones. Causality tracking such as version vectors is needed.
  3. Two nodes can produce the same timestamp (especially at millisecond resolution). A tiebreaker such as a large random number is needed, and it can also violate causality.
  • "Most recent" depends on a local clock that may be wrong. Even with tight NTP, a packet sent at 100 ms (sender clock) can arrive at 99 ms (receiver clock), as if it arrived before it was sent.
  • NTP cannot be made accurate enough to prevent this: its accuracy is limited by network round-trip time, and correct ordering would need a clock much more accurate than the network delay being measured.
  • Logical clocks, based on incrementing counters, are a safer way to order events. They capture only relative order, not time. Time-of-day and monotonic clocks are physical clocks.

Clock readings have a confidence interval.

  • Microsecond or nanosecond resolution does not mean that accuracy. Quartz drift is easily several milliseconds even when syncing with a local NTP server every minute. Over the public internet, the best is probably tens of milliseconds, spiking past 100 ms under congestion.
  • So treat a reading as a range: for example, 95% confident the time is between 10.3 and 10.5 seconds past the minute. At ±100 ms the microsecond digits mean nothing.
  • Uncertainty can be computed. A local GPS or atomic (caesium) clock reports its error range. From a server, it is drift since the last sync, plus the server's uncertainty, plus the round-trip time.
  • Most APIs hide it: clock_gettime() does not say whether the error is five milliseconds or five years.
  • Exception: Google's TrueTime API in Spanner returns [earliest, latest]. The width depends partly on time since the last sync with an accurate source.

Synchronized clocks for global snapshots.

  • Snapshot isolation usually needs a monotonically increasing transaction ID: writes with a higher ID than the snapshot are invisible to it. On one node a counter suffices.
  • Across many machines and datacenters, a global ID needs coordination and must reflect causality (if B reads A's write, B's ID must be higher). With many small, fast transactions it becomes an untenable bottleneck. Generators like Twitter's Snowflake hand out blocks of IDs, but cannot guarantee causal order.
  • Could synchronized timestamps serve as IDs? Only if accuracy were known. Spanner does this with TrueTime: if intervals A and B do not overlap (A_latest < B_earliest), B definitely happened after A. Overlap means the order is unknown.
  • Spanner waits out the confidence interval before committing a read-write transaction, so any later reader's interval cannot overlap. To keep the wait short, Google puts a GPS receiver or atomic clock in each datacenter, giving sync within about 7 ms.
  • Clock-based transaction semantics are active research and not yet in mainstream databases outside Google.
time No overlap: B after A, certain A [earliest, latest] B [earliest, latest] Overlap: order unknown A B Spanner commit wait wait interval width (~7 ms)
TrueTime intervals: only non-overlapping intervals prove order, so Spanner waits until they cannot overlap.

Process Pauses

A single-leader-per-partition database must know whether a node is still leader. One option is a lease from the other nodes: a lock with a timeout, held by one node at a time and renewed periodically. If the holder fails, it stops renewing and another node takes over at expiry. The book's request loop:

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);
    }
}
  • Problem 1: it compares an expiry set by another machine (for example, now + 30 s) with the local clock, so a few seconds of skew breaks it.
  • Problem 2: even with a local monotonic clock, it assumes little time passes between checking and process(request). If the thread pauses 15 seconds around lease.isValid(), the lease expires, another node becomes leader, and this thread processes the request unsafely without noticing until the next loop iteration.
Old leader lease valid paused 15 s (GC, VM...) lease expires process(request) New leader takes over, accepts writes
A pause between checking the lease and acting on it lets two nodes act as leader.

Pauses this long really happen:

  • Stop-the-world GC (for example, in the JVM) has lasted several minutes. Even "concurrent" collectors like HotSpot's CMS stop the world sometimes. Tuning helps, but robust guarantees must assume the worst.
  • VM suspend/resume can happen at any point for any length, including live migration, where pause length depends on how fast processes write memory.
  • Laptops and other end-user devices get suspended, for example when the lid closes.
  • OS context switches and hypervisor switches. CPU time taken by other VMs is steal time; under heavy load the paused thread may wait a while to run again.
  • Synchronous disk I/O, which can be hidden (the Java classloader lazily loading class files). I/O and GC pauses can combine. On network block devices such as Amazon's EBS, I/O also suffers network delay variability.
  • Swapping/paging: a memory access can page-fault to disk. Under pressure the OS may thrash, so paging is often disabled on servers (better to kill a process than to thrash).
  • SIGSTOP (Ctrl-Z) halts a process until SIGCONT, and an operations engineer might send it by accident.
  • All of these preempt a thread at any point without it noticing, like thread-safety problems on one machine. But mutexes, semaphores, atomic counters, lock-free structures and blocking queues do not translate: a distributed system has no shared memory, only messages over an unreliable network.
  • A node must assume it can be paused at any point, even mid-function. Meanwhile others may declare it dead, and it resumes without knowing it slept.

Response time guarantees.

  • Pause causes can be eliminated with enough effort. Hard real-time systems (aircraft, rockets, robots, cars) have deadlines whose violation can fail the whole system. You do not want an airbag delayed by a GC pause.
  • In embedded systems, "real-time" means designed and tested to meet timing guarantees in all circumstances. On the web it vaguely means pushing data or stream processing without hard constraints.
  • Real-time needs the whole stack: an RTOS with guaranteed CPU allocation, libraries with documented worst-case execution times, restricted or disallowed dynamic allocation (real-time GCs exist, but must not get too much work), and enormous testing.
  • This is very expensive and restricts languages and tools, so it is mostly used in safety-critical embedded devices. Real-time is not high-performance; throughput may be lower because timeliness comes first.
  • For most server-side systems real-time guarantees are not economical, so they live with pauses and clock instability.

Limiting the impact of garbage collection. Runtimes can track allocation rate and free memory, which gives them some flexibility over when to collect.

  • Treat GC as a brief planned outage. When the runtime warns of an upcoming pause, stop sending the node new requests, let it drain, then collect while it is idle. This hides pauses from clients and cuts high-percentile latency. Some latency-sensitive financial trading systems do this.
  • Variant: GC only short-lived objects (fast to collect) and restart processes periodically before long-lived objects need a full GC, one node at a time with traffic shifted away, like a rolling upgrade.
  • These reduce the impact of GC pauses but cannot fully prevent them.

Knowledge, Truth, and Lies

  • With no shared memory, an unreliable network, partial failures, unreliable clocks and pauses, a node cannot know anything for sure. It can only guess from the messages it receives, or does not receive. Network and node problems cannot be reliably distinguished.
  • We do not need to settle the philosophy. State the assumptions as a system model, design the system to meet them, and prove algorithms correct within that model. Reliable behavior is achievable even when the model guarantees little, though it is not straightforward.

The Truth Is Defined by the Majority

  • Asymmetric fault: a node receives everything, but its outgoing messages are dropped. The others time out and declare it dead while it is working fine ("I'm not dead!"), and nobody hears it.
  • A milder case: the node notices its messages are not acknowledged and realizes there is a network fault, but it still cannot stop being declared dead.
  • A GC case: a one-minute stop-the-world pause gets the node declared dead. It then resumes as if nothing happened, unaware that a minute has passed.
  • Moral: a node cannot trust its own judgment, and the system cannot rely on any single node. Algorithms use a quorum: decisions need a minimum number of votes, including the decision that a node is dead. A node declared dead by a quorum must step down.
  • Usually the quorum is an absolute majority (more than half). Three nodes tolerate one failure; five tolerate two. It is safe because there can be only one majority at a time, so two majorities cannot make conflicting decisions.
Majority (3 of 5): decision stands N1 N2 N3 N4 N5 "dead": steps down minority
A majority decides, even against a node that feels alive; only one majority can exist at a time.

The leader and the lock. Systems often need exactly one of something: one leader per partition (to avoid split brain), one holder of a lock on a resource (to avoid corrupting concurrent writes), one owner of a username.

  • A node believing it is "the chosen one" does not mean a quorum agrees. It may have been declared dead (network interruption, GC pause) and replaced.
  • If it keeps acting in that role and others believe it, the whole system can do the wrong thing.
  • Figure 8-4 shows a real bug HBase used to have. A storage file must be written by one client at a time, so a client gets a lease from a lock service first. Client 1 pauses and its lease expires. Client 2 gets the lease and writes. Client 1 resumes, still believes its lease is valid, and writes too, corrupting the file.
Client 1 Lock svc Client 2 Storage lease GC pause lease expires lease write write (stale) file corrupted
Figure 8-4, simplified: a client that wakes from a pause still thinks its expired lease is valid.

Fencing tokens. A node falsely believing it is the chosen one must not be able to disrupt the system. Fencing does this:

  • Each time the lock service grants a lock or lease, it returns a fencing token, a number that increases with every grant. Every write to storage must carry the client's current token.
  • Figure 8-5: client 1 gets token 33 and pauses, and its lease expires. Client 2 gets 34 and writes with it. Client 1 wakes and writes with 33. Storage has already processed 34, so it rejects 33.
  • With ZooKeeper as the lock service, the transaction ID zxid or node version cversion works as a token, since both are guaranteed to increase monotonically.
  • The resource must check tokens itself; clients checking their own lock status is not enough. If the resource lacks support, work around it (for example, put the token in the filename), but some check is required.
  • Server-side checking is a good thing: a service should not assume its clients behave well, because clients are often run by people with different priorities. It should protect itself from accidentally abusive clients.
Client 1 Lock svc Client 2 Storage token 33 pause token 34 write, 34 accepted write, 33 rejected: 33 < 34
Figure 8-5, simplified: storage accepts writes only in increasing token order, fencing off the stale client.

Byzantine Faults

  • Fencing catches nodes that err inadvertently. A node that wanted to subvert the system could just send a fake token.
  • The book assumes nodes are unreliable but honest: slow, unresponsive or outdated, but if they respond, they follow the protocol to the best of their knowledge.
  • A Byzantine fault is a node that "lies" with arbitrary faulty or corrupted responses (for example, claiming a message it never got). Reaching consensus in this setting is the Byzantine Generals Problem.
  • It generalizes the Two Generals Problem: two generals agreeing on a plan by messengers that can be delayed or lost. In the Byzantine version, n generals include unknown traitors who send false messages. (The name means "excessively complicated, devious", not anything about real Byzantine generals.)
  • Byzantine fault-tolerant: works correctly even if some nodes malfunction or attackers interfere with the network. This matters in:
    • Aerospace, where radiation can corrupt memory or CPU registers and failure is catastrophic, so flight control must tolerate Byzantine faults.
    • Multi-organization systems, where participants may cheat. Peer-to-peer networks like Bitcoin and other blockchains let mutually untrusting parties agree on transactions without a central authority.
  • In the book's systems, assume no Byzantine faults. Your organization controls the datacenter nodes, and radiation is low. BFT protocols are complicated, fault-tolerant embedded systems need hardware support, and the cost is impractical for most server-side data systems.
  • Web apps must expect malicious clients (browsers), hence input validation, sanitization and output escaping against SQL injection and XSS. The server is simply the authority, with no BFT protocol. BFT matters more in peer-to-peer networks, which have no such authority.
  • BFT does not help against bugs if every node runs the same software. Most BFT algorithms need a supermajority of more than two-thirds working (with 4 nodes, at most 1 may fail), so you would need four independent implementations.
  • It does not stop attackers either: compromise one node and you can likely compromise all of them. Authentication, access control, encryption and firewalls remain the main defenses.

Weak forms of lying. It is still worth guarding cheaply against invalid messages from hardware issues, bugs and misconfiguration (this is not full BFT):

  • Packets get corrupted. TCP/UDP checksums usually catch it but sometimes miss, so add application-level checksums.
  • Sanitize inputs in public apps: check value ranges, and limit string sizes to prevent denial of service through large allocations. Internal services should still sanity-check values (for example, in protocol parsing).
  • Configure NTP clients with multiple servers. The client estimates each server's error and checks that a majority agree on a time range, so a misconfigured server is excluded as an outlier.

System Model and Reality

Algorithms (for example, consensus in Chapter 9) must tolerate these faults without depending too heavily on hardware and software details. A system model formalizes which faults an algorithm may assume.

Timing modelAssumesRealistic?
SynchronousBounded network delay, pauses and clock error (known upper bounds, not zero)No: unbounded delays and pauses happen
Partially synchronousSynchronous most of the time, but bounds are sometimes exceeded by arbitrary amountsYes, for many systems
AsynchronousNo timing assumptions, not even a clock (no timeouts)Very restrictive to design for
Node modelAssumes
Crash-stopA node fails only by crashing, and is then gone forever
Crash-recoveryA node may crash and come back after an unknown time; stable storage survives crashes, in-memory state is lost
Byzantine (arbitrary)A node may do anything, including deceive others
node faults → Crash-stop Crash-recovery Byzantine Synchronous Partially sync Asynchronous most useful for real systems unrealistic restrictive
System models combine a timing model with a node-fault model; partially synchronous plus crash-recovery fits most real systems.

Correctness of an algorithm. Define correctness by properties, the way "sorted" means each element is smaller than the ones to its right. For fencing tokens:

  • Uniqueness: no two token requests return the same value.
  • Monotonic sequence: if request x completed before y began, then t_x < t_y.
  • Availability: a node that requests a token and does not crash eventually receives a response.

An algorithm is correct in a system model if it always satisfies its properties in every situation the model allows. But if every node crashes, nothing can make progress, which leads to the next distinction.

Safety and liveness. Uniqueness and monotonic sequence are safety properties; availability is a liveness property. Liveness definitions often contain "eventually", and eventual consistency is a liveness property.

SafetyLiveness
InformallyNothing bad happensSomething good eventually happens
When violatedAt a specific point in time, and it cannot be undoneMay not hold now, but can still be satisfied later
RequirementMust hold in all situations of the model, even if all nodes crash or the network failsMay carry caveats (for example, only if a majority is up and the network eventually recovers)
  • The informal definitions are subjective; the real definitions are precise and mathematical.
  • The partially synchronous model requires that the system eventually returns to a synchronous state: any network interruption lasts a finite time.
Safety duplicate token issued damage done, cannot undo Liveness request sent not yet satisfied eventually replied
A safety violation happens at an identifiable moment and is permanent; liveness can still be met in the future.

Mapping system models to the real world. Models are simplified abstractions, and reality bites back:

  • Crash-recovery assumes stable storage survives. But disks get corrupted or wiped by hardware errors or misconfiguration, and firmware bugs can fail to recognize correctly attached drives on reboot.
  • Quorum algorithms assume a node remembers what it claims to have stored. A node with amnesia breaks the quorum condition and thus correctness. A model where storage mostly survives would be harder to reason about.
  • Real implementations may still need code for "impossible" cases, even if it is just printf("Sucks to be you") and exit(666), leaving a human operator to clean up. This is arguably the difference between computer science and software engineering.
  • Abstract models are still very valuable. They distill real complexity into a manageable set of faults, and they let us prove properties hold.
  • A correct proof does not guarantee a correct implementation, but analysis finds problems that might otherwise hide until assumptions (for example, about timing) break. Theoretical analysis and empirical testing are equally important.

Summary

  • Any packet may be lost or arbitrarily delayed, and so may the reply. With no reply, you cannot know whether the message got through.
  • A node's clock may be badly out of sync despite NTP, may jump forward or back, and its error interval is usually unknown, so relying on it is dangerous.
  • A process may pause for a long time at any point (for example, stop-the-world GC), be declared dead, and resume without realizing it.
  • Partial failure is the defining characteristic of distributed systems. Anything involving other nodes may fail, go slow or time out, so tolerance must be built into the software.
  • Detection is hard. Most systems rely on timeouts, which cannot tell network from node failures, and variable delay causes false suspicion. Degraded "limping" nodes (a Gigabit NIC dropping to 1 Kb/s through a driver bug) can be harder to handle than dead ones.
  • Tolerating faults is hard too. There is no shared state or common knowledge, nodes cannot even agree on the time, and information flows only over the unreliable network. Major decisions need a quorum, not a single node.
  • If a problem fits on a single machine, keep it there and avoid opening Pandora's box; one computer can do a lot. But fault tolerance and low latency (data close to users) still need distribution.
  • Unreliability is not a law of nature. Hard real-time and bounded network delay are possible, but expensive and lower utilization. Most non-safety-critical systems choose cheap and unreliable over expensive and reliable.
  • Supercomputers stop entirely when a component fails. Distributed systems can, in theory, run forever by handling faults and maintenance per node, though a bad config pushed to every node still brings them down.
  • This chapter was about problems; Chapter 9 turns to algorithms that cope with them.

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