Chapter 02 / 10 · Distributed Systems

Talking between machines

Making the transfer call safe to retry: idempotency keys, deadlines, errors the caller can act on, and messages that survive a rolling deploy.

This chapter turns the transfer call into something a caller can retry without fear. By the end you should be able to design the request and response for a money-moving RPC: what key the caller sends, what the server stores and when, how long everyone waits, and what each error tells the caller to do.

We left the wallet in a bad state. The API calls Transfer(from, to, amount) on the wallet service. When the call times out, the API does not know whether the money moved, and a retry might move it twice. During one slow afternoon that produced hundreds of double charges. We need the second attempt to find the first.

A remote call is not a function call

Most RPC frameworks generate a client stub so that calling the wallet looks like calling a local function: wallet.Transfer(req). That convenience is useful and slightly dishonest. A 1994 paper from Sun, A Note on Distributed Computing, argued that local and remote calls differ in ways no interface can hide, and the argument has held up.

Latency differs by orders of magnitude. A local function call costs nanoseconds; a round trip inside one data centre costs something like half a millisecond, and between two cities tens of milliseconds. A loop that makes a remote call per item is a different program from the same loop with local calls. Memory is not shared, so the wallet cannot receive a pointer to the API’s account object; everything crosses as a copy, and the copy can be stale by the time it arrives. Most of all, a remote call can fail partially, in exactly the ways the last chapter listed. A local call never returns “maybe”.

The practical consequence is that the stub’s signature should not pretend. A transfer method that returns Result or throws hides a third outcome. Our design will make “unknown” a first-class answer the caller has to handle.

The retry needs a name for the operation

A retry is only safe if the server can recognise it as a retry. The wallet sees two requests that both say “move ₹500 from Asha to Ravi”. They could be one intention sent twice, or two genuine payments, perhaps rent split in two halves. The amounts and accounts cannot tell them apart. Something in the request has to.

That something is an idempotency key: a unique identifier for one intention, generated by the client before the first attempt and sent unchanged on every retry. The important word is intention. The key is created when Asha taps Send, not when the API makes a network call. If the app generated a fresh key on each attempt, every retry would look new and the key would do nothing.

On the server side, the key has to be recorded in the same transaction as the money movement. Here is the shape of it:

BEGIN;
INSERT INTO idempotency_keys (key, request_hash, status)
  VALUES ('k7f2...', 'sha256(asha,ravi,500)', 'done');
  -- a unique index on key: a second insert fails here
UPDATE accounts SET balance = balance - 500 WHERE id = 'asha' AND balance >= 500;
UPDATE accounts SET balance = balance + 500 WHERE id = 'ravi';
INSERT INTO transfers (...) VALUES (...);
UPDATE idempotency_keys SET response = '{"transfer":"t-9001"}' WHERE key = 'k7f2...';
COMMIT;

If the insert of the key fails on the unique index, the wallet rolls back, reads the stored row, and returns the stored response. If the request hash differs from the stored one, the client has reused a key for a different operation, which is a client bug, and the wallet returns an error instead of guessing.

APIwallet servicewallet databasePOST /transfers · key k7f2one transaction:insert key + debit + credit✕reply losttimeout · retrysame key k7f2key existsstored result · no second debit
Fig 2 · The reply to the first attempt is lost. The retry carries the same key, finds the stored result, and moves no money

Walk the cases from the last chapter with the key in place. If the first request never arrived, the retry is the first time the wallet sees the key, and it does the transfer. If the first attempt committed and the reply was lost, the retry hits the unique index and gets the stored result. If the first attempt crashed before commit, the key row was rolled back with everything else, so the retry does the transfer. All three converge on exactly one transfer. The slow case needs one more rule, which we will come to.

Predict first

A colleague suggests a simpler version: first SELECT the key; if it is absent, call the existing transfer code, which runs its own transaction; then insert the key. What goes wrong?

Show the worked answer

Two things. First, two attempts can overlap. The slow first attempt and the retry both run the SELECT, both find nothing, and both perform the transfer. The check and the action are separate steps, so nothing stops both from passing the check.

Second, the wallet can crash between the transfer’s commit and the key insert. The money has moved, the key was never recorded, and the next retry moves it again.

Both bugs come from the same place: the record that the work happened and the work itself are not atomic. Putting the key insert inside the transfer’s transaction, guarded by a unique index, closes both. The database does the serialising for us.

Keys cannot be kept forever, and they do not need to be. They need to outlive every retry that might carry them. If the app retries for at most a few minutes and the user might tap again within an hour, a retention window of a day leaves a wide margin. Stripe’s public API, for example, documents that keys can be pruned after 24 hours. Choose the window from the longest plausible retry, then add a margin, and note that a key expiring too early turns a late retry back into a double charge.

Stopping work nobody is waiting for

The idempotency key handles the case where the first attempt finished. It does not handle the slow afternoon well. There, the first attempt was still in the wallet’s queue when the retry arrived. With the key in place, one of them wins the unique index and the other returns the stored result, so we no longer charge twice. But the wallet still spends its scarce capacity on requests whose callers left long ago.

The fix is to send a deadline with every request: an absolute point in time, or a remaining budget, after which the answer is useless. gRPC builds this in, and propagates it to downstream calls. Say the app gives the whole operation 3 seconds. The API spends 200 ms on authentication and limits and calls the wallet with 2.8 seconds left. The wallet’s request sits in a queue for 2.9 seconds. When a worker finally picks it up, the deadline has passed, and the wallet rejects it without touching the database. The work that would have been wasted is never done, and the queue drains faster.

A deadline also lets the status check from the last chapter give a definite answer. Once a request’s deadline has passed, the wallet will not start it. If the transfer is not recorded by then, and the request has not been picked up by a worker, it will never be. The caller can wait until the deadline plus a small margin, then ask, and trust a “not found”. There is a subtlety: the wallet checks the deadline when it starts the work, so a transfer that started just inside the deadline can still commit a little after it. The margin covers the longest time a started transfer can take, which is why the transaction itself also needs a timeout.

Retry when, how often, and at which layer

With keys and deadlines, retries are safe. They can still be harmful. A retry is extra load, and it arrives precisely when the service is struggling. Three rules keep that under control.

First, back off. Wait before retrying, and wait longer each time: 100 ms, then 200, then 400. Second, add randomness to each wait. If ten thousand app instances all time out during the same blip and all retry after exactly 100 ms, they arrive together and recreate the blip. A common form, sometimes called full jitter, picks a uniformly random delay between zero and the current backoff ceiling, which spreads the retries across the whole interval.

Third, retry at one layer only. Suppose the app retries three times, the API retries each call to the wallet three times, and the wallet’s database client retries three times. One tap can become 3 × 3 × 3 = 27 database attempts. During an overload this multiplication is exactly the wrong response. A common policy is to retry only at the layer closest to the user, or to give each client a retry budget, for example allowing retries to add at most 10 percent to its normal request rate and failing fast once the budget is spent.

Retries should also be limited to outcomes that might heal. A timeout might. A “service unavailable” might. “Insufficient funds” will not, and retrying it only adds load.

Errors the caller can act on

That last point argues for designing errors around what the caller should do next. An error that only says “500 Internal Server Error” forces the caller to guess whether retrying is safe. For the transfer RPC, the wallet’s responses should fall into a small number of classes.

ResultMeaningCaller’s action
OKTransfer committed, or this key’s earlier attempt didShow success with the transfer id
RejectedChecked and refused: insufficient funds, account frozenDo not retry; show the reason
Key conflictSame key, different request bodyClient bug; log and alert, do not retry
UnavailableRefused before any work started, such as overload or deadline already passedSafe to retry with backoff and the same key
UnknownTimeout, connection reset, or an error after work may have begunRetry with the same key, or check status after the deadline

The difference between the last two rows is useful. A server that is shedding load can say so before doing any work, which lets the caller know that nothing happened. The unknown row is the honest residue. With idempotency keys in place, the caller handles it the same way as unavailable; without them, it would need a human.

The message will change while both versions are running

A remote call has one more difference from a local one: the two sides are deployed separately. A rolling deploy of the wallet replaces servers a few at a time over twenty minutes. During that window some API calls reach new wallet code and some reach old. The app on Asha’s phone may be months out of date. So every message format must be readable by older and newer code at the same time.

Schema-based formats such as Protocol Buffers make the rules explicit. Each field has a number, and the number is what goes on the wire. Old code skips fields with numbers it does not know. That gives a short list of safe and unsafe changes: adding a new optional field is safe; removing a field is safe if its number is reserved and never reused; changing a field’s type or reusing a number is unsafe, because old readers will decode the new bytes as the old type.

Those rules only protect the bytes. They do not protect meaning, and the wallet shows why. Suppose the team adds international transfers by adding a currency field, with INR as the default when absent. A new API server sends amount=50, currency=USD. If that request reaches an old wallet server, the old server skips the field it does not know and moves ₹50. The schema change was technically compatible, and the transfer is wrong by a factor of about eighty.

The fix is a deploy order and a guard. Roll out the wallet first, with code that understands the field. Only when every wallet server is new does the API start sending non-INR transfers. And because a rollback could bring old code back, the wallet should reject requests that contain fields it does not understand when those fields change the meaning of the operation. Some teams do this with an explicit list of required capabilities in the request. The general rule is that a field that changes what an operation does is a new operation, and needs to be introduced like one.

Finding the wallet, and noticing it has moved

Before the API can call the wallet, it has to find a wallet server, and that list changes constantly. Servers are replaced during deploys, added when traffic grows and removed when it falls. The API asks a service registry, or DNS, for the current addresses and keeps a pool of open connections to them, because opening a fresh connection with a TLS handshake for every call would add one or two extra round trips to each transfer.

The pool and the registry are both caches of the truth, and both go stale. Suppose the wallet scales down from twelve servers to eight. The registry removes four addresses. An API server that cached the old list for sixty seconds keeps sending a third of its transfers to machines that are shutting down. If those machines stop abruptly, the API sees connection resets in the middle of requests, which are unknown outcomes, and retries them. With idempotency keys that is safe, but each one costs a timeout and a retry.

Two habits remove most of this. A wallet server that is about to stop should first leave the registry, then stop accepting new requests while finishing the ones it has, and only then exit. This is usually called draining, and it turns abrupt resets into clean refusals that the caller can retry immediately because no work began. And clients should treat a failed connection as a reason to refresh their view of the registry, rather than waiting for a cache timer.

There is a subtler problem with long-lived connections. HTTP/2 and gRPC send many requests over one connection, so a client that opened its connections when there were four wallet servers keeps using those four after eight more are added. The new servers sit idle while the old ones are overloaded. Load balancing has to happen per request rather than per connection, either in the client library or in a proxy, and connections should be recycled periodically so that new servers receive a share. The general point is that an RPC is not only a request and a reply. It travels over connections and addresses that each have their own lifetime and their own ways of going stale.

When an RPC is the wrong tool

Not everything the wallet does needs a synchronous call. Sending Ravi a notification that money arrived, updating the analytics store and feeding the fraud model do not need to finish before Asha sees “Sent”. Making them RPCs on the transfer path adds their latency and their failures to every transfer. They are better as events the wallet publishes after the transfer commits, which is the subject of the broadcast chapter.

Idempotency keys also have a cost worth stating. Every write path pays an extra indexed insert, and the key table grows with traffic until pruned. For operations that are already idempotent, such as “set Asha’s display name to A. Rao”, a key adds nothing, because applying the same write twice gives the same state. Keys are for operations whose effects accumulate: debits, credits, sending messages, creating records.

So far the wallet runs on one machine and the only question was whether a request happened. Once we keep copies of the wallet on several machines, a harder question appears: when two updates touch the same account on different machines, which one came first? The next chapter, Time and order, explains why the timestamps on those machines cannot settle it, and what can.