Course contents

08. Distributed Systems Lesson 1 of 10

Distributed System Challenges

Watch partial failures, lost messages, slow-versus-dead timeouts and skewed clocks break the assumptions of a single machine, and see the basic defences.

16 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • In a distributed system some parts fail while others keep running; callers must handle failure on every call.
  • A missing response can mean a lost request, a lost response, a crashed node or a slow one. The caller cannot tell which.
  • Retrying after a timeout may execute an operation twice, so retried operations must be idempotent.
  • Timeouts are guesses: too short and healthy nodes are declared dead, too long and callers wait on dead ones.
  • Clocks drift, jump and pause; ordering events across machines by wall-clock time can silently lose writes.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A distributed system is a set of programs on different machines that cooperate by sending messages over a network. That sounds like an implementation detail, but it removes three guarantees a single process quietly gives you:

  • All-or-nothing failure. One process either runs or has crashed. A distributed system can be half working: some nodes up, some down, some slow.
  • Reliable communication. A function call returns or throws. A message can be lost, delayed for an unbounded time, duplicated or reordered, and the sender often cannot tell which.
  • A shared clock. One machine has one notion of “now”. Different machines have different clocks that drift apart, get corrected in jumps and stop advancing for a process that is paused.

Almost every technique in this module (consensus, quorums, leader election, logical clocks, consistency models) exists to cope with one of these three.

Why it exists

Nobody distributes a system for fun. You do it because one machine is not enough: not enough capacity, not enough availability (one machine is one failure away from an outage), or too far from users on another continent. The moment the work spans machines, the network and independent failures come with it. The well-known “fallacies of distributed computing” (the network is reliable, latency is zero, bandwidth is infinite, the topology doesn’t change, and so on) are a list of assumptions that silently break.

How it works

Partial failure. Each component fails independently: a crashed process, a full disk, a bad network card, a misconfigured firewall rule, a zone losing power. With hundreds of components, something is broken most of the time. The system has to keep serving with that part missing, and every caller has to treat every remote call as something that can fail.

An unreliable network. In the model most distributed algorithms assume (the asynchronous model), messages can be lost or delayed arbitrarily long, and there is no bound on how long a node takes to answer. A caller that hears nothing cannot distinguish:

  • the request was lost (nothing happened),
  • the request arrived and the work was done, but the response was lost,
  • the remote node crashed before or after doing the work,
  • the remote node is just slow (a long garbage-collection pause, a saturated disk, a queue).

So a retry after silence may execute the operation a second time. The standard answer is to make operations idempotent: “set email to x” instead of “append”, or an idempotency key that the receiver stores so it can recognise a duplicate request and return the original result. TCP does not solve this: it retransmits and de-duplicates within one connection, but cannot tell you whether the application on the other side processed your request before the connection broke.

Timeouts as failure detectors. Since there is no reliable signal for “dead”, systems use timeouts: no answer within T, treat the call as failed. A timeout is a trade-off, not a measurement. A short one detects real failures quickly but also declares healthy-but-slow calls dead (wasting their work, and with retries, adding load at the worst moment). A long one avoids false alarms but holds threads, connections and users while a dead node never answers. Health checks, heartbeats and leader leases are all timeouts with thresholds on top.

Unreliable clocks. Quartz clocks drift (tens of parts per million is common, i.e. a few seconds a day uncorrected). NTP keeps machines within milliseconds of each other on a good network, more on a bad one, and corrects them by slewing or by stepping, which can make a clock jump backwards. A virtual machine can be paused and resumed; a process can stall in a stop-the-world GC pause and wake up with stale beliefs (for example, that it still holds a lease). Consequences:

  • Comparing timestamps from different machines can order events wrongly. Last-write-wins conflict resolution then silently discards the genuinely newer write.
  • Measuring durations should use a monotonic clock, never the wall clock.
  • Anything that depends on “I still hold this lease” must account for pauses (fencing tokens).

Some systems bound clock uncertainty explicitly (Google Spanner’s TrueTime waits out the uncertainty interval before committing); most avoid relying on wall time for ordering and use logical clocks, version numbers or a single leader instead.

When to use it

These are not techniques to apply but assumptions to design under. Make them explicit whenever a request crosses a process boundary: microservices, database replicas, caches, message brokers, third-party APIs. A useful habit is to ask of every remote call: what happens if it fails, if it is slow, and if it succeeds but the answer is lost?

When not to

Don’t distribute what one machine can do. A single well-provisioned database server with a hot standby avoids most of this module’s problems and serves a surprising amount of traffic. Many teams adopt microservices or multi-region designs and inherit partial failure, retries and consistency problems they did not need.

Trade-offs

Choice You gain You pay
Short timeout Fast detection, threads freed quickly False alarms on healthy-but-slow calls; wasted work
Long timeout Few false alarms Callers stuck on dead nodes; resources held
Retrying failed calls Hides transient faults Duplicate execution unless idempotent; extra load during overload
Aggressive health checks Faster ejection Flapping, probe load, ejecting nodes that are merely busy
Wall-clock timestamps Simple ordering, human-readable Silent misordering across machines

Alternatives

There is no alternative to the underlying problems, only different ways to contain them:

  • Fewer machines. Scale up before scaling out where it suffices.
  • Avoid synchronous chains. Asynchronous messaging with durable queues turns “the dependency is down” into “the work waits”.
  • Stronger primitives. Consensus systems (etcd, ZooKeeper, Raft-based databases) give you agreement despite failures so each service does not reinvent it.
  • Synchronous networks with bounded delays exist (some industrial and telecom systems), but general-purpose data-centre networks and the internet are not.

Failure modes

  • Retry storms. Every layer retries a failing call three times; a slow dependency receives 27× its normal traffic.
  • Gray failure. A node is slow or fails only some requests; it passes health checks, so nobody routes around it.
  • Double execution. A timed-out payment request was processed; the retry charges again.
  • Split brain. Two nodes each believe the other is dead and both act as leader.
  • Clock-based data loss. Last-write-wins with skewed clocks drops the newer write without any error.
  • Zombie processes. A process paused past its lease expiry wakes up and writes as if it still owned the resource.

In production

Set a timeout on every remote call, derived from measured latency percentiles, and budget them so the caller’s deadline is not exceeded by its callees’ timeouts plus retries (propagate deadlines). Retry only idempotent operations, with exponential backoff and jitter, and cap retries per request. Use health checks plus passive outlier detection so slow instances get ejected too. Make writes idempotent with request ids. Run NTP or PTP and alert on clock offset, but never rely on cross-machine timestamps for correctness. Test failure deliberately (fault injection, chaos experiments) because these paths are rarely exercised otherwise.

Common misconceptions

  • “TCP makes the network reliable.” It makes one connection reliable while it lasts. It cannot tell you whether the far application processed your request before the connection died.
  • “If it timed out, it didn’t happen.” It may have happened completely.
  • “Our clocks are synced by NTP, so timestamps are safe to compare.” NTP narrows the skew; it does not remove it, and it can step a clock backwards.
  • “A node is either up or down.” Slow, overloaded and partially failing nodes are the hard cases.
  • “Exactly-once delivery solves it.” Systems that advertise it achieve exactly-once effects by combining at-least-once delivery with idempotence or transactions.

Interview angle

Interviewers listen for whether you treat remote calls as unreliable without being prompted: timeouts on every call, retries with backoff only for idempotent operations, idempotency keys for payments and orders, and health checks for routing. Be ready to explain why a timeout cannot distinguish slow from dead, the two generals problem in one sentence (no protocol over a lossy channel can guarantee both sides agree they agree), and why you would not use wall-clock timestamps to order writes across nodes.

Model assumptions

The simulated steps use a simplified model, not a benchmark. Orders sends 40 calls per second (Poisson arrivals) through a round-robin load balancer to three Inventory instances, each with 4 workers, a 50 ms mean service time (lognormal, cv 0.5) and room for 20 waiting calls. Network hops take a fixed 2–10 ms; the model never loses packets. “10× slower” multiplies the service time; “crashed” refuses connections immediately. Health checks probe every 250 ms and eject after 2 failures. The lost-message and clock-skew steps are scripted illustrations: the packets and annotations are drawn to explain the idea, not produced by the simulation, which models neither packet loss nor clocks. The “Network” node is scenery. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. A function call becomes a network call

    Inside one process, calling reserveStock() either returns or throws, in microseconds, and if the machine dies the whole program dies with it.

    Here Orders calls Inventory over the network, about 40 times a second, through a load balancer and three instances. A call takes roughly 75 ms: two network hops each way plus 50 ms of work. Orders waits at most 500 ms for an answer (its *timeout*). Right now everything works and the instances are well under half busy.

    Scene: Orders sends 40 calls per second through a load balancer to three Inventory instances. Calls take about 75 ms and all succeed.

    Key idea: A remote call has more outcomes than a local one: it can succeed, fail, or never answer, and the caller cannot always tell which.

  2. 2. Partial failure: some calls fail, most do not

    One second in, Inventory 2 crashes. Orders, the balancer and the other two instances keep running. The balancer does not check health yet, so it still sends every third call to the dead instance, and those calls fail with *connection refused*.

    The result is about one call in three failing, unpredictably, while the rest succeed. That is *partial failure*: in a distributed system some parts break while others carry on, and every caller has to cope with it on every call.

    Scene: Inventory 2 goes offline. About a third of the calls, the ones routed to it, fail with connection refused; the others still succeed.

    Key idea: In a distributed system failure is partial and normal: some components fail while the rest keep running.

  3. 3. Lost request or lost response?

    Traffic is paused for a scripted illustration (the simulation does not model packet loss). Watch three calls.

    Call 1: the request is dropped in the network. Inventory never sees it. Call 2: the request arrives, Inventory reserves the stock, and the *response* is dropped on the way back. From Orders’ side both look identical: silence, until the timeout fires.

    Call 3: Orders retries. The retry succeeds, but Inventory has now reserved the stock twice. A sender can never know whether a lost call was executed. That is why retried operations must be *idempotent*, for example by sending an idempotency key the receiver remembers.

    Scene: Scripted: a request is dropped by the network; a second request is processed but its response is dropped; the retry succeeds and reserves the stock a second time.

    Key idea: Silence does not tell you whether the other side did the work. Retries are only safe for idempotent operations.

  4. 4. Is it slow, or is it dead?

    Traffic is back. One second in, Inventory 2 becomes ten times slower (a long garbage-collection pause, a saturated disk, a noisy neighbour). It is alive and still working.

    Calls routed to it now take about half a second or more, so many of them hit Orders’ 500 ms timeout and are counted as failures, exactly as if the instance were down. Some of those calls will still complete on Inventory 2 after Orders has given up.

    A timeout is the only failure detector you have, and it is a guess: it cannot tell a slow node from a dead one, or a dead node from a lost message.

    Scene: Inventory 2 slows down tenfold. Calls routed to it often exceed the 500 ms timeout and count as failures, although the instance is still running.

    Key idea: A timeout cannot distinguish slow from dead. It is a guess you tune, not a fact you observe.

  5. 5. A tight timeout declares healthy nodes dead

    All three instances are healthy again. To detect trouble faster, the team cuts the timeout to 100 ms.

    Normal calls take about 75 ms on average, but service time varies and the slowest calls take well over 100 ms. About one call in eight now times out although nothing is broken. Each one is work Inventory did for nothing, and with retries it would be done again.

    Too long a timeout and a dead node holds callers for ages; too short and you call healthy nodes dead. Pick it from measured latency (above the P99 of healthy calls), not from a guess.

    Scene: All instances are healthy, but with a 100 ms timeout roughly one call in eight, a normal but slightly slower one, times out and count as failures.

    Key idea: Timeouts trade detection speed against false alarms. Set them from measured latency percentiles.

  6. 6. Detect, route around, retry safely

    The timeout goes back to 500 ms, and two defences are added. The balancer now health-checks each instance every 250 ms and takes it out after 2 failed probes. Orders retries a failed call once; with round robin the retry goes to another instance.

    One second in, Inventory 2 crashes again. Calls that hit it fail fast (connection refused) and are retried elsewhere, and within about half a second the balancer stops sending it traffic. Users see almost no errors.

    The retry is only safe because reserving stock was made idempotent (previous step). Health checks are themselves timeouts with thresholds, so they share the slow-versus-dead problem.

    Scene: Inventory 2 crashes again. Calls that reach it are retried on another instance, and health checks remove it from rotation within about half a second. Almost no call fails.

    Key idea: You cannot prevent partial failure; you detect it (timeouts, health checks), route around it, and retry idempotent work.

  7. 7. Clocks disagree

    Traffic is paused again for a scripted illustration (the simulation has one perfect clock).

    Two instances both store a stock record and reconcile with last write wins: the copy with the newest timestamp wins. Inventory 1’s clock runs 200 ms fast. At real time 10:00:00.050 a write sets stock to 5 on Inventory 1, which stamps it *.250*. At real time .150, a *later* write sets stock to 4 on Inventory 3, stamped *.150*.

    When they exchange copies, the stale write wins because its clock was ahead; the newer write is silently lost. Clocks drift, NTP corrections can jump them, and a paused process does not notice time passing. Don’t order events across machines by wall-clock time; use logical clocks, versions or a single leader.

    Scene: Scripted: Orders writes stock 5 to Inventory 1, whose clock is 200 ms fast, then a later write of stock 4 to Inventory 3. When the two copies are exchanged, last write wins keeps the older value because of its larger timestamp.

    Key idea: Wall clocks on different machines disagree. Ordering events by timestamp across machines can silently lose writes.

  8. 8. The three things you cannot trust

    Building across machines means giving up three comforts of a single process. Failures are partial: any component can fail while the rest run. The network is unreliable: messages are lost, delayed or duplicated, and silence tells you nothing. Clocks are unreliable: they drift, jump and pause.

    Every later lesson in this module answers one of these: CAP and PACELC (what to give up when the network splits or is slow), consistency models (what a read may return), consensus and leader election (agreeing despite failures), and logical clocks (ordering without wall time).

    Scene: All three Inventory instances are healthy, with health checks, a 500 ms timeout and one retry. Orders sends 40 calls per second and they succeed.

    Key idea: Partial failure, unreliable networks and unreliable clocks are the starting assumptions of distributed design, not edge cases.