Summary#
A distributed system is a set of computers that cooperate over a network and appear to their users as one system. We distribute to get more capacity than one machine has, to survive machine failures, and to be close to users around the world. The price is that the network and the machines can fail independently. Some parts work while others do not (partial failure), messages can be lost, delayed, duplicated or reordered, and clocks disagree. The classic fallacies of distributed computing list the assumptions that feel true on one machine and are false across a network, starting with "the network is reliable" and "latency is zero". A network partition splits nodes into groups that cannot talk to each other, and each group may think the other is dead. Failure models describe what can go wrong: nodes that crash, nodes that drop messages, nodes that are slow, and, at the extreme, Byzantine nodes that behave arbitrarily or maliciously. Because a remote node cannot be distinguished from a slow one, a timeout tells you only that you did not get an answer, never whether the operation happened. That unknown outcome is why retries need idempotency. Finally, every distributed algorithm is judged by safety (nothing bad ever happens, such as two leaders) and liveness (something good eventually happens, such as a leader being elected). Under real networks, you can always keep safety, but liveness may have to wait.
Why It Exists#
Every system starts on one machine, and one machine is wonderful. A function call either returns or throws. Memory is shared, so every part of the program sees the same data. There is one clock. If the machine dies, everything dies together, which is bad, but at least simple: there is no question about which parts are still running.
Three pressures eventually push a system past one machine:
- Scale. One machine has limits: a few hundred CPU cores, a few TB of memory, a few tens of GB per second of disk and network bandwidth. A service with 200,000 requests per second, or 500 TB of data, needs many machines. See Scaling Up vs Scaling Out.
- Fault tolerance. Machines fail. Disks die, power supplies burn out, kernels panic, and operators make mistakes. A service that must stay up when a machine fails needs copies of its data and its work on other machines, ideally in other racks, data centres or regions. See Availability and Reliability.
- Latency and location. Light in fibre takes about 70 ms to cross the Atlantic and back. A user in Sydney talking to a server in Virginia waits about 200 ms per round trip, before any work is done. Putting servers, caches or CDN edges near users removes most of that. A URL shortener, for example, can run its redirect logic at CDN points of presence with edge functions, so a popular short link is resolved within a few milliseconds of the user, without ever reaching the origin.
The moment the work is spread across machines connected by a network, the comfortable properties of one machine disappear. A call to another machine may succeed, fail, or never return. Data on two machines can disagree. Clocks drift apart. Most importantly, failures become partial: one machine can crash while the others continue, believing it is still alive, or believing it is dead when it is only slow.
Distributed systems theory exists to reason about this world precisely: what can go wrong, what is possible despite it, and what is provably impossible. Every later page in this part builds on the ideas here: Time and Ordering, Failure Detection and Gossip, Consensus, Leader Election and Distributed Locks.
How It Works#
The defining property of a distributed system is that components communicate only by sending messages over a network, and each component can fail independently of the others. Everything else follows from those two facts.
Every arrow in this diagram is a network call, and every box is a separate machine or set of machines. Each arrow can lose, delay, duplicate or reorder messages, and each box can crash, restart, pause or run slowly, independently of the others. A request that touches five boxes and six arrows has eleven things that can fail on its path. With a single machine, the same work would be a few function calls in one process.
Why distribute, and what it costs#
There are four main reasons to distribute a system, each with a matching cost:
| Reason | What you gain | What it costs |
|---|---|---|
| Scale out | Capacity beyond one machine: more requests, more data | Data must be partitioned; cross-partition operations become hard |
| Fault tolerance | Survive machine, rack, zone or region failures | Replicas must be kept in sync; failover must avoid split brain |
| Low latency for distant users | Serve from nearby regions, CDN edges | Data near users may be stale; writes may need to travel far |
| Organisational independence | Teams own and deploy separate services | Every service boundary becomes a network call that can fail |
The most important lesson is that you should not distribute until you need to. A single well-sized machine, with a replica for failover, handles more than most people expect: tens of thousands of simple queries per second on a modern database server, and several TB of data. Many successful products ran on one primary database for years. Distribute the parts that need it, when they need it, and keep the rest simple. See Monolith vs Microservices for the organisational side of the same trade-off.
Why distribute, in depth#
Scale has two dimensions: throughput and data size. Stateless work, like rendering pages or validating requests, scales out easily: add servers behind a load balancer, and any server can handle any request. State is the hard part. When data does not fit on one machine, or one machine cannot absorb all its writes, it must be partitioned across machines (see Partitioning and Sharding). Then every operation that touches several partitions, such as a transfer between two accounts on different shards, becomes a distributed operation, with all the problems described on this page.
Fault tolerance has a numerical basis. Suppose a server has 99.9% availability, which is about 8.8 hours of downtime a year. If a service needs any one of two independent servers, it is down only when both are down, about 0.1% times 0.1%, or 0.0001%, which is about 30 seconds a year. That is the power of redundancy. The catch is the word independent. Two servers in the same rack share a power supply and a switch, and two servers running the same buggy software share the bug. Real availability comes from removing correlated failures: separate racks, zones and regions, staggered deployments, and diverse dependencies.
Distribution can reduce availability. The opposite calculation matters just as much. If a request needs all of 10 services, each at 99.9%, it succeeds only 0.999 to the power 10, about 99.0% of the time, roughly 87 hours of downtime a year. Each service boundary on the critical path multiplies the failure rate. That is why distributed designs need timeouts, retries, fallbacks and circuit breakers (see Resilience Patterns), and why critical paths should touch as few services as possible.
Latency is set by physics. Light in fibre travels at about two-thirds of its speed in a vacuum, about 200 km per millisecond. A round trip within one data centre takes about 0.5 ms, between zones in a region 1 to 2 ms, across a continent 40 to 80 ms, and between continents 100 to 250 ms. No engineering removes those numbers. A design that needs a synchronous round trip between Europe and the US on every write has a floor of about 80 ms per write. See Numbers to Know and Multi-Region Data.
Edges trade consistency and cost for latency. Pushing logic to CDN edges, as with Cloudflare Workers or AWS Lambda@Edge, serves popular requests close to users. In exchange, cached data at hundreds of edge locations must be invalidated when it changes, edge functions have limits on run time, memory and libraries, costs can grow at high traffic, and debugging a system spread across hundreds of locations is harder. Whether that trade is worth it depends on how much latency matters to the product, how sensitive the company is to cost, and the traffic pattern. See CDN.
The fallacies of distributed computing#
In 1994, L. Peter Deutsch, then at Sun Microsystems, wrote down a list of false assumptions that programmers new to distributed applications tend to make. It grew to eight, with James Gosling usually credited for the last one. Each one is true, or close to true, inside a single process, and false across a network.
- The network is reliable. Packets are dropped, connections reset, switches fail, cables are cut, and cloud networks have brief outages. Any message can be lost.
- Latency is zero. A local function call takes nanoseconds. A network round trip takes from half a millisecond inside a data centre to hundreds of milliseconds across the world, and occasionally seconds when something is congested.
- Bandwidth is infinite. Links have limits, and they are shared. Sending a 100 MB response to thousands of clients, or replicating a large dataset, saturates links and slows everything else on them.
- The network is secure. Traffic can be read, modified or forged unless it is encrypted and authenticated. Assume the network is hostile (see Security Fundamentals).
- Topology does not change. Servers are added and removed, containers move, IP addresses change, and routes shift. Hard-coded addresses break.
- There is one administrator. Different teams, companies and cloud providers control different parts of the path, with different policies, maintenance windows and mistakes.
- Transport cost is zero. Serialising data, encrypting it and sending it costs CPU time and money. Cloud providers charge for data crossing zones and regions, and for data leaving the cloud.
- The network is homogeneous. Different hardware, operating systems, protocols, library versions and MTU sizes coexist, and they interact in surprising ways.
The fallacies, in depth#
"The network is reliable" is not hypothetical. Peter Bailis and Kyle Kingsbury collected public reports of real network failures in "The Network is Reliable" (ACM Queue, 2014): partitions inside single data centres, misconfigured switches, failed network cards that dropped only some traffic, and cloud network events that isolated parts of a fleet. Many led to data loss or split brain in well-known databases. The lesson is that any design which is only correct while the network works will eventually be incorrect.
What each fallacy means for design.
- Reliability: every remote call needs a timeout, a retry policy and a plan for the unknown outcome (below). Any message that matters must be acknowledged, and retried until it is.
- Latency: avoid sequential round trips. Fifty sequential calls at 2 ms each add 100 ms. Batch requests, fetch in parallel, move computation to the data, and cache.
- Bandwidth: paginate, compress, avoid sending whole objects when a field will do, and keep large blobs out of request paths (see Handling Large Blobs).
- Security: encrypt in transit with TLS, including internal traffic, and authenticate every service call.
- Topology: use service discovery and DNS, not fixed IPs, and expect instances to come and go during deployments and autoscaling.
- Administrators: treat external dependencies as unreliable and outside your control, with their own rate limits and outages.
- Transport cost: keep chatty services in the same zone, compress replication streams, and watch cross-zone and egress charges, which can exceed compute costs for data-heavy systems.
- Homogeneity: use well-defined, versioned protocols and schemas, and test across versions during rolling upgrades.
Checksums: data can be corrupted, not just lost. Network stacks include checksums, but the TCP checksum is only 16 bits, and corruption also happens in memory, on disks and in buggy software along the path. Systems that care about integrity add end-to-end checksums: storage systems such as HDFS and object stores checksum every block, Kafka checksums every record batch, and replication protocols verify data on arrival. A checksum turns silent corruption into a detected, retryable error.
Partial failure#
On one machine, failure is usually total: the process crashes and everything stops together. In a distributed system, failure is usually partial: some components fail while others carry on. A database replica dies but the primary continues. One of 40 app servers runs out of memory. One availability zone loses power. A network link between two racks drops 5% of packets. And the components that are still running often cannot tell what has failed.
Partial failure is what makes distributed systems hard. It is not that failures are more frequent; it is that they are nondeterministic and ambiguous. The same request can succeed one moment and fail the next, and when it fails, you often do not know where, or whether its effects happened.
Some characteristic forms:
- Crashed node: stops responding entirely.
- Slow node: still alive, but responding in 5 seconds instead of 5 ms, because of a long garbage-collection pause, disk contention, CPU throttling or swapping. Slow is often worse than dead, because it ties up callers' threads and connections.
- Gray failure: a node passes its health checks but fails real requests, for example, it answers pings but its disk is broken.
- Asymmetric connectivity: A can reach B, but B cannot reach A, or A can reach B and C, but B cannot reach C.
- Dependency failure: your service is healthy, but a downstream service it calls is not.
Partial failure, in depth#
Gray failures are the dangerous kind. A crashed node is easy: health checks fail, traffic moves away. A node that is half broken keeps receiving traffic and fails a fraction of it, often in a way that looks like the client's fault. Microsoft researchers described this pattern in "Gray Failure: The Achilles' Heel of Cloud-Scale Systems" (Peng Huang and colleagues, HotOS 2017): the failure detector's view of a component ("healthy") differs from the application's experience ("broken"). The fixes are to make health checks exercise real functionality, such as reading from disk and querying dependencies, and to detect failures from the callers' side, by tracking error rates and latency per instance and ejecting outliers (see Load Balancing).
Slow is the new down. A downstream service that hangs for 30 seconds is worse than one that fails at once. Each waiting request holds a thread, a connection and memory in the caller. With 200 threads and a 30-second hang, the caller can serve at most about 7 requests per second, and it soon stops responding itself. The failure cascades upstream. Timeouts, bulkheads (separate resource pools per dependency) and circuit breakers stop the spread (see Resilience Patterns).
Process pauses. A program can stop running for a while without crashing. Garbage-collection pauses in the JVM have historically reached seconds on large heaps. A virtual machine can be paused for live migration. The operating system can swap a process out under memory pressure, or a laptop can sleep. From the process's own point of view, no time has passed. From everyone else's, it disappeared and then came back. A pause is especially dangerous for a node that believes it holds a lease or a lock, because it may wake up and act on a lease that expired during the pause. That is covered under timeouts below, and in Distributed Locks.
Correlated failures. Failures cluster. A bad configuration is pushed to every server at once. A certificate expires everywhere at the same moment. A leap second triggers the same kernel bug across a fleet. A retry storm from thousands of clients hits a recovering service. Designs that assume independent failures, such as "two replicas will never fail together", underestimate risk badly. Deploy changes gradually, keep replicas in different failure domains, and add jitter to retries and timers so that clients do not act in lockstep.
Metastable failures. Some systems have a stable bad state. A brief overload causes timeouts, timeouts cause retries, retries add more load, and the system stays overloaded even after the original trigger is gone. This was described in "Metastable Failures in Distributed Systems" (Nathan Bronson and colleagues, HotOS 2021). The defences are load shedding, retry budgets that cap retries to a fraction of normal traffic, exponential backoff with jitter, and circuit breakers that give a struggling dependency room to recover.
Network partitions#
A network partition happens when the network splits the nodes into two or more groups that can communicate within each group but not between groups. A switch fails between two racks, a fibre link between two data centres is cut, a firewall rule is pushed by mistake, or a cloud zone loses connectivity to the others. Each side is healthy and running. Each side simply cannot reach the other.
The defining difficulty is that from inside a partition, a partitioned node looks exactly like a crashed node. Nodes on side A see that the nodes on side B have stopped answering, and cannot tell whether B is dead or merely unreachable. If both sides decide the other is dead and carry on accepting writes, the system now has two independent versions of the truth. This is called split brain.
In this picture, five nodes are split two and three. If both sides keep a leader and accept writes, a customer's balance can be changed differently on each side, and when the partition heals, the two histories conflict. The standard defence is a majority quorum: a side may act only if it can reach more than half of the nodes. Zone B, with three of five, can elect a leader and continue. Zone A, with two of five, must stop accepting writes. At most one side can ever hold a majority, so split brain cannot happen. The cost is that the minority side is unavailable for writes until the partition heals. This choice, between staying available on both sides and staying consistent, is exactly what the CAP Theorem describes.
Network partitions, in depth#
Partitions are not always clean. A textbook partition splits the network neatly in two. Real partitions are messier:
- Partial partitions: A can reach B and C, but B cannot reach C. Each node sees a different set of live peers. Leader election protocols can flap, with B and C repeatedly trying to replace each other.
- Asymmetric partitions: messages flow from A to B but not from B to A. A thinks B is alive because A's heartbeats get through, while B believes A is dead because nothing comes back.
- Flaky links: 10% packet loss looks like intermittent partitions, timeouts and retries, not a clean outage.
- Slow links: a link with 2 seconds of latency is effectively a partition for any protocol with a 1-second timeout.
Jepsen, the testing project started by Kyle Kingsbury, has shown again and again that databases claiming strong guarantees lost acknowledged writes or returned stale reads under these partial and asymmetric partitions. If you rely on a system's guarantees during partitions, check whether it has been tested this way.
What each side should do. The design decision during a partition depends on the data:
- Consistency first (CP): the minority side refuses writes, and possibly reads, until it rejoins. Used for leader election, locks, configuration, account balances and inventory counts, wherever two conflicting truths would be costly. ZooKeeper, etcd, and Spanner behave this way.
- Availability first (AP): both sides accept writes and reconcile later, using version vectors, last-writer-wins, or merge functions such as CRDTs (see Collaborative Editing and CRDTs). Used for shopping carts, likes, presence and activity data, where a temporary disagreement is acceptable. Dynamo-style databases such as Cassandra can be configured this way.
Healing is its own problem. When a partition heals, the system must reconcile. A CP system's minority side catches up by fetching the log from the leader, which is simple. An AP system must merge two divergent histories. If it uses last-writer-wins by timestamp, one side's writes silently disappear, and clock skew can make the "last" writer the wrong one (see Time and Ordering). Systems that cannot afford silent loss keep both versions and let the application or the user resolve them, as the original Dynamo shopping cart did by merging carts.
How long partitions last. Most partitions in a well-run data centre last seconds to minutes, but they are common across a large fleet. Cross-region links fail less often, but for longer. The practical consequence is that a CP system's minority side will regularly be unavailable for short periods, and an AP system will regularly need to reconcile. Neither is a rare corner case.
Failure models#
A failure model states precisely what kinds of misbehaviour an algorithm must tolerate. It matters because an algorithm proven correct under one model can be wrong under a weaker assumption. From most benign to most severe:
- Crash-stop (fail-stop): a node works correctly until it stops, and then it never comes back. Simple to reason about, but unrealistic for systems whose nodes reboot.
- Crash-recovery: a node can crash and later restart. Anything in memory is lost, but data written to stable storage, such as a disk with
fsync, survives. This is the model most real systems use. Raft, Paxos and databases all assume it, and they write their logs to disk before acknowledging. - Omission: a node fails to send or receive some messages, while otherwise behaving correctly. Lost packets and full buffers look like this.
- Timing (performance) failures: a node responds correctly, but too late, outside the time bounds the algorithm assumed. A long GC pause is a timing failure.
- Byzantine (arbitrary) failures: a node can do anything: send wrong or contradictory messages, lie about its state, or collude with other faulty nodes. This includes malicious nodes, and also corrupted memory or serious software bugs.
| Model | What a faulty node can do | Nodes needed to tolerate f faults | Where it is assumed |
|---|---|---|---|
| Crash-stop | Stop forever | f + 1 for redundancy; 2f + 1 for majority-based agreement | Theory, simple replication |
| Crash-recovery | Stop and restart, losing memory but not disk | 2f + 1 for consensus | Raft, Paxos, ZooKeeper, etcd, most databases |
| Omission | Drop some messages | 2f + 1 for consensus, with retries | Real networks |
| Byzantine | Anything, including lying | 3f + 1 | Blockchains, some aerospace and safety systems |
Failure models, in depth#
Why Byzantine fault tolerance needs 3f + 1 nodes. Leslie Lamport, Robert Shostak and Marshall Pease framed the problem in "The Byzantine Generals Problem" (ACM TOPLAS, 1982): several generals must agree on a plan by messenger, and some of them are traitors who send different messages to different generals. They proved that agreement is possible with oral (unsigned) messages only if fewer than a third of the generals are traitors. The intuition: to make progress, you must be able to act after hearing from n minus f nodes, because f may never answer. Among those, f may be liars. For the honest responses to outnumber the lying ones in any two such groups that overlap, you need n minus f minus f to be larger than f, so n is at least 3f + 1. With crash faults, nobody lies, so any two majorities overlap in at least one honest node, and 2f + 1 is enough. Practical Byzantine Fault Tolerance (Miguel Castro and Barbara Liskov, OSDI 1999) made BFT efficient enough for real systems.
Why most systems do not tolerate Byzantine faults. Inside one organisation's data centre, nodes are not assumed to be malicious. BFT protocols need more replicas, more message rounds (roughly quadratic message counts in classic protocols), and more CPU for signatures. So ordinary databases and coordination services use crash-recovery models, and handle the "accidentally Byzantine" cases with cheaper tools: checksums for corruption, authentication for untrusted inputs, input validation, and careful software engineering. Byzantine tolerance matters where participants genuinely do not trust each other, such as public blockchains, or where a single faulty computer could be catastrophic, such as some flight-control systems.
Stable storage is part of the model. Crash-recovery protocols are correct only if "written to disk" really means durable. If a node acknowledges a vote or a log entry, crashes, and comes back without it because the write was still in an operating-system buffer, the node has effectively lied, a Byzantine failure, and safety can break. This is why consensus implementations fsync before replying, and why disks or virtual disks that acknowledge writes before they are durable are dangerous for databases. See Storage Fundamentals.
System models for time. Failure models describe what nodes do. Timing models describe what we may assume about time:
- Synchronous: message delays and processing times have known upper bounds. Timeouts then detect failures perfectly. Real networks do not guarantee this.
- Asynchronous: no bounds at all. A message can take any finite time. Nothing can be inferred from silence.
- Partially synchronous: the system behaves asynchronously for unknown periods, but eventually becomes synchronous for long enough to make progress. Cynthia Dwork, Nancy Lynch and Larry Stockmeyer introduced this model in "Consensus in the Presence of Partial Synchrony" (Journal of the ACM, 1988). It is the model that matches real networks best, and the one that practical consensus protocols are designed for: always safe, and live whenever the network behaves well for long enough.
Timeouts and unknown outcomes#
When a node sends a request and no response arrives, there are many possible explanations:
- The request was lost before it reached the server.
- The server is down.
- The server is alive but slow, and will answer later.
- The server processed the request, and the response was lost on the way back.
- The server processed the request, then crashed before replying.
From the client's side, all five look identical: silence. The only tool the client has is a timeout: "if I have heard nothing after T milliseconds, I will stop waiting". But a timeout tells you only that you did not get an answer in time. It does not tell you whether the operation happened. In cases 4 and 5, it did. This is the unknown outcome problem, and it is the single most important practical idea in distributed systems.
The client cannot avoid retrying, because if it gives up, a charge that never reached the server is lost. And it cannot retry blindly, because if the first attempt succeeded, the customer is charged twice. The answer is to make retries safe: the client attaches an idempotency key, the same on every retry, and the server records the key with the result in the same transaction as the effect. A retry with a known key returns the stored result instead of repeating the work. See Idempotency and Delivery Semantics.
Timeouts and unknown outcomes, in depth#
You cannot get certainty by sending more messages. The Two Generals' Problem shows why. Two armies on opposite hills must attack at the same time, or both lose. They can communicate only by messengers who cross a valley where they may be captured. General A sends "attack at dawn". A cannot be sure B received it, so B sends an acknowledgement. But B cannot be sure the acknowledgement arrived, so A acknowledges the acknowledgement, and so on forever. Any finite exchange ends with a last message whose sender does not know if it arrived, and the protocol must be correct even if that last message is lost, so it could have been skipped, and by induction so could all of them. No protocol over an unreliable channel can guarantee that both sides know the same outcome. Practical systems accept this and design around it, with idempotent retries, durable logs, and reconciliation.
Choosing a timeout is a trade-off. A short timeout detects real failures quickly, but declares slow nodes dead and causes needless retries and failovers, which add load at exactly the wrong time. A long timeout avoids false alarms, but users wait, and resources are held. Practical guidance:
- Base timeouts on measured latency, for example a little above the p99 or p99.9 of the dependency, not on guesses.
- Make each layer's timeout shorter than its caller's, so the caller does not give up while work it no longer needs is still running below. If an API's budget is 1 second, a call to a dependency inside it might get 300 ms.
- Propagate deadlines with the request (gRPC does this), so that every service knows how much time remains, and stops work when the client has already given up.
- Add jitter, and cap retries. A retry storm can turn a brief blip into an outage.
Hedged requests. For reads that are safe to duplicate, sending a second request to another replica after a short delay (for example, at the p95 latency) and taking whichever answer arrives first cuts tail latency dramatically, at the cost of a few percent extra load. Jeffrey Dean and Luiz André Barroso described this in "The Tail at Scale" (Communications of the ACM, 2013). It works only for idempotent operations.
Unknown outcomes with external systems. Payment networks are the canonical case. A card charge request goes to a payment service provider, which talks to card networks and banks, and the final result may take seconds or even arrive later by webhook. If the call times out, the charge may or may not have happened. A safe design:
- Record intent before calling out. Write a payment row in state
PENDING, with an idempotency key, before sending the request. If the process crashes, the row shows there is something to check. - Use the provider's idempotency key on every attempt, so that a retry can never create a second charge.
- Never treat a timeout as a failure. Mark the payment
UNKNOWN, and resolve it by querying the provider's status API, or by waiting for its webhook. Only a definite answer moves it toSUCCEEDEDorFAILED. - Reconcile. Every day, compare your ledger with the provider's settlement reports, and investigate any difference. This catches whatever the online path got wrong.
- Keep an append-only ledger of every state change, so the history can be audited and replayed. See Multi-Step Processes and Distributed Transactions.
Leases and timeouts on the server side. Timeouts are also used to give a node temporary rights: a lease says "you are the leader, or you hold this lock, until time T". If the holder crashes, the lease expires and someone else can take over, without waiting forever. The danger is the holder that has not crashed, only paused. A Redis lock acquired with SET lock:concert:343 token NX EX 30 expires after 30 seconds. If the holder then pauses for 40 seconds in garbage collection, another client acquires the lock, and when the first client wakes up, it still believes it holds the lock and writes anyway. Two clients act at once, which is exactly what the lock was meant to prevent. Three facts limit the damage:
- Release safely. Store a random token as the lock value, and release with a check-and-delete script, so a client never deletes a lock that expired and was taken by someone else.
- Fencing tokens. Have the lock service hand out an increasing number with every grant, and have the storage layer reject writes carrying a number lower than one it has already seen. The paused client's late write carries the old number and is rejected. Redis has no built-in fencing, while ZooKeeper and etcd provide suitable increasing version numbers.
- Enforce the invariant where the data lives. Treat a lock in Redis as an efficiency tool that occasionally fails. For example, a ticketing system can hold a seat for 10 minutes with a Redis key that expires automatically, which is convenient because PostgreSQL has no row-level TTL. But the final booking still happens in a database transaction with a conditional update or optimistic concurrency, so even if the lock fails or expires mid-payment, the seat cannot be sold twice. At worst, one buyer gets an error and an automatic refund.
The details are on Distributed Locks and Leader Election. The general rule is that any decision based on time must assume the clock or the process may be wrong, and must be backed by a check that does not depend on time.
Ordering across servers. A related surprise is that messages from different servers have no natural order. If user A's message goes through server 1 and user B's reply goes through server 2, a third user may receive the reply first. Wall-clock timestamps from the two servers cannot fix it reliably, because the clocks disagree by milliseconds or more. Practical designs create order at a single point: route all messages of one conversation through one partition, such as a Kafka partition keyed by conversation ID, or a single owner process for that conversation, and assign each message an increasing sequence number there. Clients then sort by sequence number, and detect gaps (message 41 arrived, but 40 did not) to request what is missing. Order is guaranteed per conversation, which is what users notice, rather than globally, which would require a bottleneck. See Time and Ordering and Realtime Updates.
Safety versus liveness#
Every property we want from a distributed algorithm falls into one of two kinds.
- A safety property says nothing bad ever happens. "There is never more than one leader in a term." "A committed write is never lost." "Two clients never hold the same lock at once." "An account balance never goes negative." If a safety property is violated, you can point to the exact moment it happened, and nothing later can undo it.
- A liveness property says something good eventually happens. "A leader is eventually elected." "Every request eventually gets a response." "A lock that is released is eventually granted to a waiter." A liveness property can never be shown to be violated at any finite moment, because the good thing might still happen later.
Leslie Lamport introduced the distinction in 1977, and Bowen Alpern and Fred Schneider gave it a precise definition in "Defining Liveness" (Information Processing Letters, 1985), showing that every property is the combination of a safety property and a liveness property.
The practical point is this: when the network misbehaves, a good algorithm gives up liveness, never safety. During a partition, a Raft cluster's minority side cannot elect a leader, so it stops accepting writes. That is a temporary loss of liveness. But it never elects a second leader in the same term, and never loses a committed write. Those are safety properties, and they hold no matter how badly the network behaves. When the network recovers, liveness returns. A system that does the opposite, staying "available" by letting both sides elect leaders, may lose data permanently.
| Property | Kind | Example violation |
|---|---|---|
| At most one leader per term | Safety | Two nodes both accept writes as leader in term 7 |
| Committed entries are never lost | Safety | A write acknowledged to the client disappears after failover |
| Linearizable reads | Safety | A read returns a value older than one already returned to another client |
| A leader is eventually elected | Liveness | Elections split votes forever and no leader emerges |
| Every request gets a reply | Liveness | A request hangs with no timeout |
| A crashed node is eventually detected | Liveness | A dead node stays in the membership list for hours |
Safety and liveness, in depth#
The FLP impossibility result. Michael Fischer, Nancy Lynch and Michael Paterson proved in "Impossibility of Distributed Consensus with One Faulty Process" (Journal of the ACM, 1985) that in a fully asynchronous system, no deterministic algorithm can guarantee that consensus is always reached if even a single process may crash. The intuition: in an asynchronous system, a crashed process is indistinguishable from a slow one. There is always some schedule of message delays that keeps the algorithm in an undecided state, waiting on the one process whose vote would settle it, which might be dead or might answer any moment. FLP does not say consensus is impossible in practice. It says you cannot have guaranteed safety and guaranteed liveness in a purely asynchronous world with crashes. Practical protocols keep safety always, and get liveness by assuming partial synchrony (eventually, timeouts work), or by using randomisation, such as Raft's randomised election timeouts, which make endless split votes vanishingly unlikely. See Consensus.
CAP as a safety-liveness trade-off. The CAP theorem, conjectured by Eric Brewer in 2000 and proved by Seth Gilbert and Nancy Lynch in 2002, says that during a partition, a system cannot be both consistent (linearizable, a safety property) and available (every request to a non-failed node gets a response, a liveness property). Seen this way, CAP is a special case of the general rule: when the network fails, you must choose which property to give up. See CAP Theorem and PACELC.
Why the distinction helps in design reviews. It gives a precise vocabulary for "what happens when X fails?". For a leader election design, ask two separate questions. Safety: can two leaders ever act at the same time, even with pauses, partitions and clock jumps? If yes, what prevents damage, such as fencing tokens? Liveness: under what conditions does the system make progress, and how long can it be stuck? Answers like "the lease is 10 seconds, so failover takes at most about 15 seconds when the network is healthy" are concrete liveness bounds. Answers like "at most one leader because of the majority quorum, and stale leaders' writes are rejected by the term check" are safety arguments.
Testing both kinds. Safety violations are found by checking histories: record every operation's start, end and result under injected faults, then check whether some legal sequential order explains them. Jepsen and its checkers, such as Knossos and Elle, do exactly this. Liveness issues are found by measuring recovery: inject a partition or kill the leader, and measure how long until writes succeed again. Formal methods help too. Amazon engineers described using TLA+, Leslie Lamport's specification language, to find subtle bugs in designs of DynamoDB, S3 and other services ("How Amazon Web Services Uses Formal Methods", Chris Newcombe and colleagues, Communications of the ACM, 2015). TLA+ lets you state safety properties as invariants and liveness as temporal properties, and the model checker explores many interleavings automatically.
Coordination services as building blocks#
Because consensus and leader election are hard to implement correctly, most systems do not implement them. They rely on a small, well-tested coordination service, which runs a consensus protocol among 3 or 5 nodes and offers simple primitives: a strongly consistent key-value store, ephemeral entries that disappear when their owner's session dies, watches that notify on change, and increasing version numbers.
- Apache ZooKeeper, described in "ZooKeeper: Wait-free Coordination for Internet-scale Systems" (Patrick Hunt and colleagues, USENIX ATC 2010), uses its own atomic broadcast protocol, ZAB. Hadoop's HDFS and YARN use it for high-availability failover, HBase uses it to track region servers and the active master, and Apache Kafka used it for broker metadata and controller election for many years, before replacing it with its own Raft-based KRaft mode.
- etcd uses Raft, and is the store behind Kubernetes, holding every object of the cluster's state.
- Consul (HashiCorp) uses Raft for its catalog, plus gossip for membership, and offers service discovery and health checking.
- Google's Chubby lock service ("The Chubby Lock Service for Loosely-Coupled Distributed Systems", Mike Burrows, OSDI 2006) inspired ZooKeeper, and served Bigtable and GFS for master election.
With such a service, "elect a leader" becomes "create an ephemeral key; whoever creates it first is leader; others watch it", and "who is in the cluster?" becomes "list the ephemeral keys under /members". The hard parts, agreement under partitions and crashes, are solved once. See ZooKeeper and etcd.
The toolbox, at a glance. Most of the remaining pages in this part are tools for the problems described here:
| Problem | Tool | Page |
|---|---|---|
| Which nodes are alive? | Heartbeats, phi-accrual detectors, gossip, SWIM | Failure Detection and Gossip |
| In what order did things happen? | Lamport clocks, vector clocks, hybrid logical clocks, TrueTime | Time and Ordering |
| How do replicas agree? | Paxos, Raft, ZAB | Consensus |
| Who is in charge? | Leases, fencing tokens, coordination services | Leader Election |
| Who may act on a resource? | Locks with TTLs and fencing, or no lock at all | Distributed Locks |
| How do concurrent edits merge? | Version vectors, OT, CRDTs | Collaborative Editing and CRDTs |
| How do failures not cascade? | Timeouts, retries with backoff, circuit breakers, bulkheads | Resilience Patterns |
| Where is the request slow? | Distributed tracing, metrics, logs | Observability |
| How do services find each other? | Service discovery, DNS, registries | Leader Election and Coordination |
The ideas came from a small number of famous papers: Paxos, GFS, MapReduce, Bigtable, Dynamo, Chubby, ZooKeeper, Kafka, Spanner and the LSM-tree. Each one is summarised in Landmark Papers.
When to Use It#
These ideas apply whenever more than one machine is involved, which in practice is every production system. The signals that you are making a genuinely distributed design decision, and should reason with the concepts on this page, are:
- Data lives on more than one machine: replicas, shards, caches, search indexes, or a second region. Ask what happens when copies disagree, and what happens during a partition.
- A request crosses a service boundary: every remote call needs a timeout, a retry policy, and an answer for the unknown outcome.
- Something must be unique or exclusive: one leader, one lock holder, one booking per seat, one charge per order. That is a safety property, and timeouts alone cannot provide it.
- The system must stay up through machine or zone failures: you need redundancy across failure domains, and a rule, usually a majority, for who may act during a partition.
- Users are far apart: latency budgets are set by the speed of light, and multi-region writes force a consistency choice.
- An external party is involved, such as a payment network, a partner API or a third-party webhook: their failures and delays are outside your control, so outcomes must be reconciled.
When NOT to Use It#
- Do not distribute what fits on one machine. A single PostgreSQL server with a standby handles a large amount of traffic. Sharding it early adds distributed transactions, rebalancing and cross-shard queries for no benefit.
- Do not split a monolith into services just to "be distributed". Every new boundary turns a function call into a network call that can fail, and turns one transaction into a distributed one.
- Do not build your own consensus or leader election. Use etcd, ZooKeeper, Consul, or the database's built-in replication. Home-grown protocols almost always have safety bugs that appear only under partitions and pauses.
- Do not tolerate Byzantine faults unless participants truly distrust each other. Inside one company's infrastructure, crash-recovery protocols with checksums and authentication are the right level.
- Do not chase global ordering or global locks when per-key order is enough. Ordering every event in a system through one sequencer creates a bottleneck and a single point of failure. Order per conversation, per account or per partition instead.
How to Implement It#
These are the habits that turn the theory into designs that survive production.
- Draw every network hop on the request path, and for each one, write down what happens if it is slow, fails, or returns an unknown outcome.
- Set timeouts everywhere, based on measured latency, shorter at each lower layer, and propagate deadlines with requests.
- Make every retried operation idempotent, with idempotency keys stored in the same transaction as the effect, or with naturally idempotent operations, such as "set status to shipped".
- Retry with exponential backoff, jitter and a cap, and add a retry budget so that retries cannot multiply load during an outage.
- Choose a partition behaviour for each kind of data: refuse writes on the minority side (CP) for invariants such as money, inventory and leadership; accept and merge (AP) for data that tolerates temporary disagreement.
- Use majority quorums and a proven coordination service for anything that must be unique, and add fencing tokens wherever a lease holder writes to shared storage.
- Spread replicas across failure domains (racks, zones, regions), and deploy changes gradually, so failures stay independent.
- Reconcile anything that crosses an external boundary, comparing your records with the other side's on a schedule.
- Test failure: inject latency, packet loss, partitions, process pauses and clock jumps in staging, and measure both safety (no invariant broken) and liveness (time to recover).
// A remote call with a deadline, bounded retries, jitter and an idempotency key
async function callWithRetry<T>(
send: (key: string, signal: AbortSignal) => Promise<T>,
opts = { attempts: 4, perTryMs: 300, baseDelayMs: 100, maxDelayMs: 2000 }
): Promise<T> {
const key = crypto.randomUUID(); // same key on every attempt
let lastError: unknown;
for (let attempt = 0; attempt < opts.attempts; attempt++) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), opts.perTryMs);
try {
return await send(key, ctrl.signal); // server dedupes on key
} catch (err) {
lastError = err; // timeout: outcome unknown, retry is safe
if (!isRetryable(err)) throw err; // 4xx validation errors: do not retry
} finally {
clearTimeout(timer);
}
const cap = Math.min(opts.maxDelayMs, opts.baseDelayMs * 2 ** attempt);
await sleep(Math.random() * cap); // full jitter
}
throw lastError; // caller records UNKNOWN, reconciles later
}| Technology | Fits when |
|---|---|
| etcd | Strongly consistent configuration, leader election and locks, especially around Kubernetes |
| Apache ZooKeeper | Coordination for JVM-based data systems: HBase, Hadoop HA, older Kafka and Solr deployments |
| Consul | Service discovery and health checking, with a consistent key-value store and gossip membership |
| gRPC deadlines, Envoy or a service mesh | Consistent timeouts, retries, outlier ejection and circuit breaking between services |
| Resilience4j, Polly | Client-side retries, circuit breakers and bulkheads in Java and .NET services |
| Jepsen | Testing a database or queue for safety violations under partitions and pauses |
| Chaos engineering tools (Chaos Monkey, Gremlin, AWS Fault Injection Service) | Injecting failures into staging or production to verify resilience |
| TLA+ | Specifying and model-checking a new protocol or a subtle concurrent design before building it |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Single machine with a standby | Simple; one transaction; no partitions inside the data | Capacity ceiling; failover takes seconds to minutes | Data and load fit on one server |
| Distributed and consistent (CP) | No split brain; invariants hold | Minority side unavailable during partitions; higher write latency | Money, inventory, leadership, locks, configuration |
| Distributed and available (AP) | Always accepts reads and writes; low latency | Divergence; conflicts to merge; possible lost updates with LWW | Carts, likes, presence, analytics, caches |
| Short timeouts | Fast failure detection; resources released quickly | False positives; retry storms; needless failovers | Latency-critical, idempotent calls with healthy dependencies |
| Long timeouts | Few false alarms | Slow detection; threads and connections held; cascades | Expensive operations that rarely fail |
| Crash-fault tolerance (2f + 1) | Efficient; well understood | Assumes nodes do not lie | Infrastructure inside one trust domain |
| Byzantine tolerance (3f + 1) | Survives malicious or arbitrary nodes | More nodes, more messages, more CPU | Mutually distrusting parties, safety-critical systems |
Common Pitfalls#
- Treating a timeout as a failure. The operation may have succeeded. Mark it unknown, retry idempotently, or check the status.
- Retrying non-idempotent operations. Double charges, duplicate emails and duplicate orders all come from blind retries.
- No timeout at all. A default of "wait forever" on a socket or HTTP client turns a slow dependency into a full outage.
- Retry storms. Every layer retrying three times multiplies load by 27 across three layers. Retry at one layer, with backoff, jitter and budgets.
- Trusting wall-clock time for ordering or expiry. Clocks drift and jump. Use logical clocks, sequence numbers, or a single ordering point, and back leases with fencing.
- Two-node clusters. With two nodes, neither can form a majority alone, so a partition stops everything, or, if configured to continue, causes split brain. Use 3 or 5 nodes.
- Replicas in the same failure domain. Three replicas on one rack share one switch and one power feed.
- Health checks that test nothing. A
/healthendpoint that returns 200 while the disk is full hides gray failures. - Assuming the network is a clean partition or nothing. Test asymmetric partitions, packet loss and high latency, not just "unplug the cable".
Real-World Examples#
- Amazon Dynamo ("Dynamo: Amazon's Highly Available Key-value Store", Giuseppe DeCandia and colleagues, SOSP 2007) chose availability during partitions for the shopping cart, accepting writes on both sides and merging divergent carts using vector clocks, because rejecting "add to cart" was worse for the business than occasionally resurrecting a deleted item.
- Google Spanner ("Spanner: Google's Globally-Distributed Database", James Corbett and colleagues, OSDI 2012) chose consistency, using Paxos groups for replication and TrueTime, GPS- and atomic-clock-backed time with explicit uncertainty bounds, to provide externally consistent transactions across the world.
- GitHub published a post-incident analysis of an October 2018 outage. A loss of connectivity of less than a minute between its East Coast network hub and its primary East Coast data centre triggered an automated database failover to its West Coast data centre. Writes had been accepted in both locations, and restoring a consistent state took about a day of degraded service.
- Amazon S3 had a major outage in the US-East-1 region on 28 February 2017, when a command meant to remove a small number of servers for debugging removed far more, including servers for subsystems that other parts of S3 depended on. Restarting them took hours, showing how correlated, operator-triggered failures dominate real availability.
- Netflix built Chaos Monkey, which randomly terminates production instances, to force its services to be designed for partial failure, and later expanded it into a broader set of chaos engineering tools.
- Typical scenario: a checkout service calls a payment provider with a 2-second timeout and an idempotency key, stores the payment as pending first, and resolves timeouts through webhooks and a nightly reconciliation with the provider's settlement file.
In the Interview#
Deep Dive: One write, every failureShow
Take a simple replicated write: a client asks a leader to set x = 5, the leader replicates to two followers, waits for a majority (itself plus one follower), and replies. Walk through what can fail at each step, and what a correct design does.
1. The request is lost before it reaches the leader. The client times out. Nothing happened. A retry with the same idempotency key performs the write once. Safe.
2. The leader crashes before writing to its log. Same as case 1 from the client's view. A new leader is elected by the followers. The retry goes to the new leader.
3. The leader writes to its own log, then crashes before replicating. The entry exists only on the crashed node, and was never acknowledged. The new leader does not have it. When the old leader recovers, it discovers a higher term and discards its uncommitted entry. The client's retry writes it again through the new leader. Safe, because the write was never reported as successful.
4. The leader replicates to one follower, then crashes before replying. The entry is on a majority (leader plus one follower), so it is committed, even though the client never heard. Raft's election rule only allows a candidate with an up-to-date log to win, so the follower holding the entry, or another with it, becomes leader, and the entry survives. The client times out and retries. Without deduplication, x = 5 is applied twice, which happens to be harmless because setting a value is idempotent. An increment would not be, and that is exactly why the idempotency key matters.
5. The leader commits and replies, and the reply is lost. The client sees a timeout, and the outcome is unknown. Retrying with the key returns the stored result.
6. The network partitions the leader from both followers. The old leader can no longer reach a majority, so it cannot commit new writes, and clients writing to it time out. The two followers elect a new leader in a higher term and continue. If the old leader still believes it is leader and serves reads from its local state, those reads may be stale. Systems that promise linearizable reads prevent this, either by confirming leadership with a majority before answering (a read index), or by relying on a leader lease that is shorter than the election timeout, which is safe only if clocks drift less than assumed.
7. The old leader pauses for 20 seconds, then resumes. Same as case 6, from everyone else's view. When it resumes, any message it sends carries the old term, and every node that has seen the new term rejects it. If it writes directly to external storage, that storage must check a fencing token, or the stale leader's write may land.
8. A follower's disk silently loses an acknowledged entry. For example, the disk cache lied about fsync. The follower can now vote for a candidate missing a committed entry, and the entry can be lost. Crash-recovery protocols cannot defend against this. It is the reason for durable storage settings, checksums and careful hardware choices.
Every distributed protocol you meet, in databases, queues or lock services, makes the same choices for the same cases. Reading a system's documentation through this list, asking for each case what happens, is the fastest way to understand what it actually guarantees.
Deep Dive: The end-to-end argument and where guarantees belongShow
Jerome Saltzer, David Reed and David Clark argued in "End-to-End Arguments in System Design" (ACM Transactions on Computer Systems, 1984) that a function such as reliable delivery can be implemented completely and correctly only with the knowledge of the application at the endpoints. Lower layers can help with performance, but cannot replace the end-to-end check.
Their example was file transfer. Even if every network link checks and retransmits packets, the file can still be corrupted in a buffer, by a disk, or by a bug in the transfer program. Only an end-to-end checksum, computed by the sender over the original file and verified by the receiver over the stored file, proves the transfer worked. Since that check is needed anyway, per-link reliability is an optimisation, not a guarantee.
Applied to modern systems:
- TCP does not make your request reliable. TCP guarantees ordered delivery of bytes within one connection. If the connection breaks after the server processed the request but before the response arrived, TCP cannot tell you. The application must handle that with idempotency keys and retries.
- Exactly-once messaging is an end-to-end property. A broker can deduplicate producer retries, and a stream processor can make its internal state exactly-once, but the effect on the outside world, such as a row in a database or an email sent, is exactly-once only if the final consumer deduplicates or writes idempotently. See Delivery Semantics.
- Locks do not protect data; the data store does. A lock service can tell a client it holds a lock, but it cannot stop a paused client from writing after the lock expired. Only the storage layer, by checking a fencing token or a version number, can enforce the invariant at the point where it matters.
- Replication does not equal backup. Replicas faithfully copy a bad delete or a corrupting bug. End-to-end protection against data loss needs point-in-time backups and restore tests. See Disaster Recovery.
- Payments need reconciliation. Every layer of a payment flow can be reliable and the books can still disagree with the bank. The end-to-end check is comparing your ledger with the settlement report.
The design rule. For each invariant that matters, such as "never charge twice", "never sell a seat twice" or "never lose an acknowledged order", ask where it is finally enforced. If the answer is "in a cache", "in a lock service" or "in the network", it is not enforced. It should be enforced where the data is stored, with a constraint, a conditional write, an idempotency record or a fencing check. Lower layers then make the common case fast, and the end-to-end check makes the rare case correct.
Deep Dive: Testing distributed systems for the failures they will meetShow
Why ordinary tests miss distributed bugs. Unit and integration tests run with a perfect network, fast and synchronised machines, and no crashes. Distributed bugs appear only under specific interleavings: a pause at exactly the wrong moment, a message delayed past a timeout, a partition during a leader change. They are rare per operation, but a system doing a million operations a second meets rare interleavings every day.
Fault injection. Introduce the failures deliberately:
- Network faults: drop, delay, duplicate and reorder packets, and create clean, partial and asymmetric partitions, using tools such as
tc netemandiptableson Linux, or a service mesh's fault injection. - Process faults: kill processes, pause them with
SIGSTOPto simulate long garbage-collection pauses, and restart them. - Clock faults: skew and jump clocks forward and backward on individual nodes.
- Disk faults: fill disks, slow them down, and return I/O errors.
History checking. Record each client operation with its start time, end time and result, including timeouts as "unknown". Afterwards, a checker searches for a sequential order of operations, consistent with real-time order and the system's claimed consistency model, that explains every result. If none exists, the system violated its guarantee. This is the approach of Jepsen. Its analyses of many well-known databases and queues found lost writes, stale reads and split brain under faults the systems claimed to handle.
Deterministic simulation. Some teams run the entire system, with all its nodes, inside a single-threaded simulator that controls the network, the clocks and the disks, and is driven by a random seed. The simulator can run thousands of randomised fault scenarios per hour, and any failure is reproducible exactly from its seed. FoundationDB's engineering team is well known for building its database this way from the start.
Chaos engineering in production. Staging never fully matches production. Netflix's Chaos Monkey randomly terminates instances, so that every team designs for instance loss, and larger experiments simulate the loss of a whole zone or region. The practice requires care: define the steady state you expect, limit the blast radius, run during working hours with people watching, and stop immediately when the steady state breaks.
Formal specification. For a new protocol, or any design where a bug would be catastrophic, write a specification in TLA+ or a similar language. State the safety invariants, such as "at most one leader per term", and let the model checker explore every interleaving for small cluster sizes. Bugs found this way would often take years to appear in production.
What to measure. For each fault scenario, measure safety (did any invariant break?) and liveness (how long until the system made progress again?). A good result reads like "under a leader partition, writes resumed after 4.2 seconds, no acknowledged writes were lost, and no stale reads were observed".
Key Takeaways#
- Distribute for scale, fault tolerance and latency, but only when needed. Every network hop adds failure modes and multiplies the ways a request can fail.
- The fallacies of distributed computing (the network is reliable, latency is zero, bandwidth is infinite, and so on) are false, and every design must assume so.
- Failure is partial and ambiguous: nodes crash, pause, slow down or half work, and the rest of the system often cannot tell which.
- A partition makes unreachable nodes look dead. Majority quorums prevent split brain, at the cost of the minority side's availability.
- Failure models range from crash-stop to Byzantine. Most systems assume crash-recovery and need 2f + 1 nodes. Byzantine tolerance needs 3f + 1.
- A timeout means "no answer yet", not "it failed". Unknown outcomes require idempotent retries, durable intent records and reconciliation.
- Safety means nothing bad ever happens, and liveness means something good eventually happens. Under bad networks, give up liveness temporarily, never safety.
- Enforce important invariants end to end, where the data lives, with constraints, conditional writes, idempotency records and fencing tokens.