Chapter 01 / 10 · Distributed Systems

Partial failure

Asha sends ₹500 and the call times out. Did the money move? Across a network, the honest answer is often “not known yet”.

This chapter gives you the habit the rest of the pathway depends on. When a call to another machine does not answer, you treat its outcome as unknown, list the things that might have happened, and design for each of them. That sounds like caution. In practice it decides what your screens say, how your retries work and which bugs you will be explaining to customers.

Our running example is a wallet service for a payments app. It holds a balance for every user and moves money between them. Asha opens the app and sends ₹500 to Ravi. The app calls our API, the API calls the wallet service, and two seconds later the API gives up waiting. The screen has to say something. Did Ravi get the money?

On one machine that question had an answer. Across a network it does not, at least not yet. The next nine chapters are different ways of living with that fact, so it is worth being exact about where it comes from.

What one machine let us assume

The first version of the wallet is a single server running the application and a Postgres database. A transfer is one database transaction:

BEGIN;
UPDATE accounts SET balance = balance - 500
  WHERE id = 'asha' AND balance >= 500;
UPDATE accounts SET balance = balance + 500
  WHERE id = 'ravi';
INSERT INTO transfers (id, src, dst, amount) VALUES (...);
COMMIT;

Two comforts come with this arrangement, and we rarely notice them until they are gone. The first is atomicity. If the server loses power halfway through, the database replays its write-ahead log on restart, keeps every transaction that reached COMMIT and discards the rest. Asha is debited and Ravi credited, or neither happens. The second is shared fate. The code that asked for the transfer and the code that performed it run in the same process. A function call either returns or the whole process is gone, in which case nobody is left waiting for an answer that will never come.

Strictly, the phone was always on the far side of a network, so even version one had the problem we are about to meet. It was easy to ignore while the server was fast and retries were rare. It stops being ignorable the moment the team splits the system: an API service that handles the app, authentication and limits, and a wallet service on a different machine that owns the balances. The API now calls the wallet over the network, and the second comfort disappears.

Three failures that look the same

When the API sends a transfer request and hears nothing for two seconds, at least three different things could have happened.

request lostyouserver✕…crashed mid-workyouserver✕…reply lostyouserver✕…
Fig 1 · Request lost, wallet crashed mid-work, reply lost. The API sees the same silence in all three

The request may have been dropped on the way, perhaps by a switch with a full buffer or a connection that was reset. No money moved. The wallet may have received the request and crashed. If it crashed before COMMIT, no money moved; if it crashed just after, money moved and nobody was told. Or the wallet may have done the work and replied, and the reply was lost or delayed. Money moved.

There is a fourth case that the picture cannot show, and it causes the most trouble. The wallet may simply be slow. It is still working on the request when the API gives up, and it commits the transfer at 2.4 seconds, after the API has already told the app that something went wrong. The timeout fired in the caller. The wallet has no idea the caller left.

So a timeout records how long the caller was willing to wait. It carries no information about what the callee did. The API cannot tell these cases apart by waiting longer, because each of them can look like any other for an arbitrary length of time.

Predict first

The API times out after two seconds and the app shows “Transfer failed, please try again”. Asha taps Send again and this time it succeeds in 300 ms. She started with ₹2,000. List every balance she could see in her account an hour later.

Show the worked answer

₹1,500 is the outcome everyone expects: the first attempt never reached the wallet, or the wallet crashed before committing, and the second attempt moved the money once.

₹1,000 is also possible. The first attempt committed and its reply was lost, or it was still running when the API gave up and committed later. The retry was a new request as far as the wallet could tell, so it moved another ₹500. Ravi received ₹1,000 and Asha was told the first transfer failed.

There is a third reading, which is about what she sees rather than what she ends with. If the first attempt was slow and committed after the retry, she might refresh and see ₹1,500, then later ₹1,000. The app’s message “Transfer failed” was the real bug here. The system stated as fact something it did not know.

Why the API cannot just ask

The obvious fix is a status call: after the timeout, ask the wallet whether the transfer happened. That helps, and we will build it, but it does not remove the ambiguity. The status call is itself a network request that can time out. Worse, if the original request is still sitting in the wallet’s queue, the honest answer to “did transfer X happen?” is “not yet”, and that answer can become false a millisecond after it is sent. A status check is only useful if the original request can no longer commit, which means the wallet must have some rule that stops abandoned work. The next chapter gives it one.

There is a classic thought experiment behind this, usually told as two generals who must agree on a time to attack while every messenger between them might be captured. Each acknowledgement needs its own acknowledgement, and no finite number of messages makes both sides certain. The practical lesson is narrower than the puzzle: we will never get certainty from the network, so we design operations that are safe to repeat and records that let us find out later what happened.

Slow and dead look the same from outside

A machine that has crashed and a machine that is paused are indistinguishable from the outside. Both stop answering. The paused one may be in a long garbage-collection pause, may have been frozen by the hypervisor during a live migration, or may be waiting on a disk that has become very slow. When it resumes, it carries on from exactly where it stopped, with no sense that time has passed. That detail matters a great deal in the coordination chapter, where a paused leader wakes up and keeps acting like a leader.

Because we cannot tell slow from dead, choosing a timeout is choosing which mistake to make more often. Suppose we measure the wallet in normal operation: median latency 40 ms, 99th percentile 180 ms, 99.9th percentile around 600 ms. These are illustrative numbers, but the shape is typical: a long tail caused by pauses, retries inside the database and the occasional slow disk.

A 200 ms timeout would cut off roughly one call in a hundred even on a healthy day. At 200 transfers per second that is two ambiguous transfers every second, each of which needs the recovery machinery. A 10 second timeout makes ambiguity rare when things are healthy, but on a bad day every request holds a connection and a worker for ten seconds. At 200 requests per second that is 2,000 requests in flight. If the API has a pool of 200 workers, it runs out within a second and stops serving everything, including balance reads that never needed the slow path.

TimeoutWhen it is too shortWhen it is too long
The costHealthy-but-slow calls become ambiguous; retries add loadCallers hold threads, connections and memory while waiting
Who noticesUsers see spurious failures; duplicates appear if retries are unsafeUsers see a frozen screen; the caller fails too, and so does its caller
A reasonable startSomewhat above the measured p99.9 for the call, inside the caller’s own deadline, revisited when the latency distribution moves

No timeout value is correct in general. What we can do is pick it from measured latency rather than from a round number, and make sure that when it fires, the system does something safe.

Naming what can go wrong

Engineers describe the failures a design must survive as a failure model. The model you choose decides how much machinery you need, so it is worth saying out loud.

ModelWhat the wallet machine may doWhat the design must handle
Crash-stopHalt and never returnAnother copy of the data, and a way to start serving from it
Crash-recoveryHalt, then restart with its disk intact and its memory goneDurable logs, and in-flight requests, locks and caches that vanish on restart
OmissionKeep running while messages to or from it are lostPartitions: the wallet is healthy and unreachable, which looks like a crash
TimingRespond, but far later than usualPauses and slow disks, which look like crashes and then stop looking like them
ByzantineSend wrong or malicious answersSignatures, voting among many replicas; far more expensive

Most backend systems, including our wallet, are designed for crash-recovery with omission and timing failures. We assume our own servers are buggy and unreliable but not lying. The Byzantine model still shows up, just at a different boundary. Asha’s phone runs code we do not control, and a modified app can send any request it likes. So the wallet trusts the API’s authenticated identity, checks that the amount is positive and that the balance covers it, and never trusts a balance the client claims to have. Byzantine thinking applies to clients, while the servers inside our data centre are treated as merely unreliable.

One more category deserves a name because it causes so many long incidents: gray failure. The wallet answers its health check, so the load balancer keeps sending it traffic, but writes time out because its disk is degraded. It is neither up nor down. Clean crashes are the easy case. A partly working machine keeps attracting work it cannot finish.

A bad afternoon, step by step

Here is how these pieces combine into an incident. The wallet runs on a virtual machine with network-attached storage.

At 14:02, another tenant on the same storage starts a heavy batch job. The time for each fsync rises from about 1 ms to about 50 ms. A transfer commit waits for an fsync, and commits queue behind each other, so the wallet’s latency climbs from 40 ms to well over a second within a minute.

By 14:04, requests are spending more than two seconds in the wallet’s queue. The API times out and the app shows “Transfer failed”. The wallet, which does not know anyone gave up, keeps working through its queue and commits those transfers at two to four seconds.

Users tap Send again. The app also retries once automatically. The wallet now receives roughly twice the requests at a moment when it can process about a third of its usual rate, so the queue grows faster. Its health check, which only returns a static 200, keeps passing.

At 14:30 the batch job finishes and latency returns to normal. Over the next day, support receives hundreds of tickets from users charged twice. Every one of them had a first attempt that committed late and a retry that committed too.

No single component did anything unusual. The storage got slower, the timeout fired as designed, the retry ran as designed. The failure was in the assumptions joining them: that a timeout means failure, and that a retry is harmless.

The fixes each address one assumption, and each has a cost. Making the transfer safe to repeat with an idempotency key means a retry finds the first attempt’s result instead of moving money twice; the cost is a stored key per transfer and a lookup on every write. Sending the caller’s deadline with the request lets the wallet drop work nobody is waiting for; the cost is plumbing and a few requests rejected that might have finished in time. A health check that exercises a real write would have pulled the slow wallet out of rotation, at the cost of being more dangerous when a shared dependency fails and every instance fails its check at once. And the app should have said “We are confirming your transfer” and then checked the status, which costs a new screen state and a status endpoint. The next chapter builds the first two.

Designing the screen for an unknown outcome

The most visible fix is in the app, and it is worth designing properly because it is where the ambiguity meets a person. A transfer on Asha’s phone should have at least four states, not two: sending, sent, failed and confirming. The first three are the obvious ones. The fourth is the honest answer to a timeout: the app does not know yet, and it says so.

For the confirming state to work, the app needs something it can ask about later. That means the transfer must have an identity before it is sent. When Asha taps Send, the app generates an id for this transfer, stores it on the phone together with the amount and recipient, and only then makes the request. If the request times out, the app shows “Confirming your transfer” and asks the API about that id at intervals. If the phone loses signal, or Asha closes the app, the stored id survives, and the app resumes asking when it next starts. Without the stored id, a crash of the app itself would turn an unknown outcome into a forgotten one.

The confirming state also changes what the Send button does. While a transfer is confirming, tapping Send again for the same recipient and amount should not create a second transfer silently. The app can ask “A transfer of ₹500 to Ravi is still being confirmed. Send another?”, which turns an accidental retry into a deliberate choice. If Asha does want to pay twice, the second transfer gets its own id and is treated as a separate intention.

There is a limit to how long confirming can last. Once the wallet guarantees that a request whose deadline has passed will never start, which the next chapter sets up, the app can wait for that deadline plus a margin, ask once more, and turn “not found” into a definite “failed, no money moved”. Until then, the only truthful answer after a timeout is “we do not know yet”.

None of this is specific to payments. Any operation with effects that accumulate, such as sending a message, placing an order or booking a seat, has the same four states, whether or not the interface admits it. Interfaces that show only success and failure are reporting a guess in the unknown case.

Why distribute at all, and when not to

If one machine gives us atomicity and shared fate, why give them up? Performance is rarely the honest answer for a wallet. A well-run Postgres server can commit thousands of small transactions per second, and a payments app with ten million users might peak at a few hundred transfers per second. One machine can carry that load for a long time.

The real reasons are about independent failure. Disks die, kernels need patching, and every reboot of a single wallet server is an outage for payments. Data centres lose power and fibre. A regulator or a finance team may require that no acknowledged transfer is ever lost and that service resumes within minutes. Meeting those requirements means keeping copies on machines that do not fail together, and that means a network between them. Independence is both the problem and the resource: the same property that makes the outcome of a call unknown is what lets one machine keep serving while another is down.

That also tells us when to stay on one machine. If an outage of a few minutes during a planned failover is acceptable, and point-in-time recovery from continuously shipped backups gives an acceptable loss window, a single primary with a standby is simpler, cheaper and has fewer ways to fail than anything in the rest of this pathway. Revisit the decision when the business tightens its recovery targets, when maintenance windows stop being acceptable, or when the load genuinely outgrows one machine. Each additional machine buys tolerance for one kind of failure and introduces new partial failures of its own.

In the next chapter, Talking between machines, we make Asha’s retry safe. That means idempotency keys stored in the same transaction as the transfer, deadlines that travel with the request, error codes that tell the caller what it may do next, and message formats that survive a rolling deploy.