AlgoViz

Retries

medium 30 min

A retry repeats a failed call in the hope that the problem was short.

Video lesson · Chapter 1 of 5

The coffee order with a missing reply

0:00 / 4:08

Retries in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A retry is another attempt at a call that failed. It turns many short failures, such as a lost packet, a restart or a moment of overload, into nothing worse than a small delay.

A retry policy answers six questions: which failures to repeat, how often, how long to wait in between, how much randomness to add, when to stop, and what makes a repeat safe.

Why it exists

Short failures are normal in a network. If 1 call in 100 fails for a reason that is gone a moment later, one retry leaves 1 in 10,000.

A retry is also selfish: the client takes a second share of the server. When the server fails because it is overloaded, retries are more of what hurt it. That is why limits are as much a part of retrying as the retry.

A short history

  1. 1971

    ALOHAnet goes into operation in Hawaii. A station that gets no acknowledgement waits a random time and sends again.

  2. 1989

    RFC 1122 requires internet hosts to back off their TCP retransmissions exponentially.

  3. 1997

    RFC 2068, the first HTTP/1.1, defines idempotent methods and describes when a client may repeat a request.

  4. 2012

    RFC 6585 adds status 429 Too Many Requests, which may carry Retry-After.

  5. 2015

    Marc Brooker compares kinds of jitter on the AWS Architecture Blog. Backoff without jitter is the clear loser.

  6. 2019

    The AWS Builders' Library publishes its article on timeouts, retries and backoff with jitter.

  7. 2021

    Metastable Failures in Distributed Systems, a paper at the HotOS workshop, studies overloads that keep themselves alive. Retries are a typical cause.

Words to know

Transient failure
One that goes away by itself. The only kind worth a retry.
Backoff
Waiting longer before each further attempt.
Jitter
A random part of the wait, so that clients spread out.
Cap
The longest single wait.
Thundering herd
Many clients arriving at the same moment.
Retry budget
A limit on how much load retries may add, for example 10%.
Idempotent
Repeating it has the same effect as doing it once.
Retry amplification
Retries in several layers multiply.
Dead letter queue
Where a job goes when its attempts are used up, for a person to look at.

How it works

Step through the idea, or press Play.

Step 1 of 3

May I?. Temporary failure, safe to repeat, time and budget left

Understand it

Start here

The narrow gate

Imagine four friends who run to a playground. Its gate is so narrow that only one can pass. What they do after bumping into each other decides how long it takes.

Four friends, one gate
PLAYGROUNDcount 0BUMP

The gate never became wider. Only the times of arrival changed.

Decide

Retry or not

Usually worth a retry

  • A timeout or a dropped connection, if a repeat is safe
  • Connection refused, for example during a restart
  • 502, 503 and 504
  • A database deadlock or a serialization failure: run the whole transaction again
  • 429, after the time in Retry-After

Not worth it

  • Most 4xx: the same request is wrong the same way
  • 401 and 403. With an expired token, get a new one once, then repeat
  • Validation errors
  • Business rules, such as not enough money
  • Anything unsafe to repeat without a key

Status codes

AnswerRetry?Note
400, 404, 409, 422No409 may need fresh data first
401, 403NoRenew the token once on 401
408, 429Yes, laterHonour Retry-After
500PerhapsIt may be a bug that fails every time. Once, if safe
501, 505NoIt will not exist in two seconds either
502, 503, 504Yes, with backoff504: the work may have been done
Connection refusedYesThe request was not processed
Read timeout, resetOnly if safeUnknown result. See timeouts
A server can help: say in the error body whether a repeat makes sense. API error handling shows how.

Four questions before a retry

One call with two retries

An example: request, failure, check, wait, retry, success. The waits add up to 1.23 + 2.67 = 3.9 seconds.

Waiting

Four ways to wait

StrategyWaits with base 1 sFormulaFor
Immediate0, 0, 0 s0Once, for a rare glitch or a lost race for a lock. Never against overload
Fixed1, 1, 1 sbaseSimple jobs with few clients
Linear1, 2, 3, 4 sbase x attemptGentle growth
Exponential1, 2, 4, 8, 16 sbase x 2^(attempt - 1)Network and API calls
Exponential with jitterrandom below 1, 2, 4, 8 srandom(0, exponential)Many clients: nearly always
Attempts are counted from 1 here: after attempt 1 the wait is base. Always apply a cap.

How long does that take?

1+2+4+8=15 swith full jitter on average 152=7.5 s1 + 2 + 4 + 8 = 15 \text{ s} \qquad \text{with full jitter on average } \tfrac{15}{2} = 7.5 \text{ s}
Five attempts mean four waits. 15 seconds suit a background job. A person waits perhaps 2 seconds in total, so start at 50 or 100 ms and make two or three attempts.

What retries buy

1−0.75≈0.830.012=0.00011 - 0.7^5 \approx 0.83 \qquad 0.01^2 = 0.0001
If each attempt succeeds 30% of the time and independently, five attempts succeed in 83% of cases. If 1 in 100 fails, two attempts leave 1 in 10,000. In a real outage attempts are not independent, and all of them fail.

Jitter

Why randomness matters more than the wait

Clients that fail together were put in step by the failure. If all of them wait the same time, they stay in step. Jitter breaks the step.

KindWaitCharacter
NonedelayWaves of the same height, further and further apart
Add-on (old code)delay + random(0, delay / 2)Mild. The second wait is 2 to 3 s, so the wave is only smeared
Equaldelay / 2 + random(0, delay / 2)Keeps a minimum wait
Fullrandom(0, delay)Widest spread, little work. A good default
Decorrelatedmin(cap, random(base, previous x 3))Depends on the last wait, not on the attempt number
delay is min(cap, base x 2^(attempt - 1)). The AWS article compares them: full and decorrelated are close, equal is the weakest of the jittered ones, no jitter is the clear loser.

Our own experiment (the code tab)

100 clients, 10 served per time slotCalls in totalFinished after
Immediate55010 slots
Fixed55019 slots
Linear55055 slots
Exponential, no jitter550161 slots
Full jitter36021 slots
Equal jitter39829 slots
Decorrelated jitter27418 slots
The perfect score is 100 calls and 10 slots. Without jitter, waiting longer only makes it slower. Real servers do worse than this one: they slow down when overloaded, so immediate retries would not finish so early.

Safety

Repeating must be harmless

The answer that got lost

The key belongs to the purchase, not to the attempt. Both attempts carry the same one.

Harmless to repeat

  • GET and other reads
  • PUT of a whole resource
  • DELETE by id (the second may answer 404)
  • Set value = X
  • Upsert with a unique key

Not harmless by itself

  • POST that creates something
  • Increment a counter
  • Append to a list
  • Transfer money
  • Send an e-mail or a notification
Text
POST /api/paymentsIdempotency-Key: pay_abc123_1234567890The server stores key -> result.A request with a known key returns the stored result.
How to build this, and what may go wrong, is the subject of idempotency.

HTTP agrees: a client should not repeat a request with a non-idempotent method automatically, unless it knows that the repeat is safe.

Danger

When retries make it worse

Expected attempts per request

E=1−f n1−ff=0.01, n=4: 1.01f=0.7, n=5: 2.77f=1: E=nE = \frac{1 - f^{\,n}}{1 - f} \qquad f = 0.01,\ n = 4:\ 1.01 \qquad f = 0.7,\ n = 5:\ 2.77 \qquad f = 1:\ E = n
With a failure rate f and at most n attempts. In good times retries are nearly free. In a full outage the load is n times as high.

And layers multiply

35=2433^5 = 243
Five layers that each make three attempts: one click can become 243 calls at the bottom. The AWS Builders' Library uses this example. Resilience shows the storm step by step.

How retries keep an overload alive

This is a metastable failure. It ends only when somebody cuts the load.

Limits

Retry in one place, with a budget

One layer retries

Users reach a gateway that does not retry. Orders retries with a budget of 10 percent. It calls stock, which does not retry its database.
Choose the layer that knows whether the repeat is safe and has time left. The others pass the error on.

A retry budget as a token bucket

  1. 1

    Earn

    Every normal call earns a part of a token, for example 0.1.

  2. 2

    Spend

    Every retry costs one token. No token, no retry.

  3. 3

    Keep a few

    A small reserve allows retries at low traffic.

  4. 4

    Effect

    In good times there are always tokens. In an outage retries add about 10%, instead of 300% with four attempts.

The Google SRE book describes both limits together: at most three attempts per request, and a client-wide ratio of retries below 10%. Service meshes offer such budgets too, for example Envoy.

Background work

Retrying without a waiting user

Minutes, not milliseconds

The shop writes a job to a queue. A worker takes jobs and calls the shipping company outside our system. A failed job goes to a delay queue and comes back later. After five attempts it goes to the dead letter queue.
The delay may grow to minutes, the process may restart, and nobody stares at a spinner. See queues.

Here the waits can be 1 minute, 5 minutes, an hour. After the last attempt the job goes to a dead letter queue for a person. Webhooks use the same pattern for delivery.

Best practice

Six rules

  • Set a maximum

    Never retry for ever. Two or three attempts when a person waits, 3 to 5 in a job, more only with long delays.

  • Backoff with jitter

    Exponential, capped, random.

  • Only transient errors

    List what may be repeated. Everything else is not.

  • Make it safe

    Idempotency keys for writes.

  • Cap and deadline

    A cap of 30 to 60 s for jobs. For people the deadline of the request is the cap.

  • Log and count

    Attempts per request, retry ratio, successes after a retry. A rising ratio is an early warning.

Summary

The whole topic in one minute.

Retry only temporary failures of calls that are safe to repeat. Wait a random time below a limit that doubles and has a cap. Stop after a few attempts, at the deadline, or when the budget is empty.

Retry in one layer. Obey Retry-After. A retry that makes an outage longer is worse than the error it wanted to hide.

  • Temporary, safe, time left, budget left: four yeses before a retry.
  • wait = random(0, min(cap, base x 2^(attempt - 1))).
  • Jitter helps more than longer waits.
  • Retry in one layer, at most 10% extra.
  • Same key for every attempt of one write.

Sources