Module 2 · Backend architectureLesson 21 of 887 minIntermediate

Retries and timeouts

Networks fail briefly all the time. Timeouts stop you waiting forever, and careful retries fix most blips without making things worse.

Try it

Compare "No timeout" with "Timeout + retry". Then watch "Retry storm" overwhelm the service, and "Backoff + jitter" let it recover.

Timeouts

Without a timeout, a call to a hung service can wait forever, holding a thread, a connection and a user. With many such calls, your own service grinds to a halt.

Set a timeout on every network call. A good starting point is a bit above the dependency's normal slow case (its p99 latency). Also set an overall deadline for the whole user request, and pass the remaining time along to downstream calls.

Retries

Many failures are brief: a dropped packet, a server restarting, a moment of overload. Trying again often works. But retries have a dark side.

Retry storms: when a service struggles, every client retries, multiplying the load on the service that was already struggling. With several layers each retrying 3 times, one user request can become 27 calls at the bottom.

Retrying safely

  • Limit attempts: two or three, not infinite.
  • Exponential backoff: wait 100 ms, then 200, then 400...
  • Jitter: add randomness to each wait so clients don't retry in sync.
  • Retry budgets: allow retries to add at most, say, 10% extra traffic.
  • Retry only retryable errors: timeouts, 503s and dropped connections, yes. A 400 Bad Request will fail every time; don't retry it.
  • Retry at one layer, usually closest to the user, not at every hop.

Is it safe to repeat?

If a payment request timed out, did the charge happen or not? You can't know. Retrying might charge twice. Only retry operations that are idempotent (doing them twice has the same effect as once), or make them idempotent with a request ID. That's coming up in the distributed systems module.

Quick check

Why add random jitter to retry delays?