brandonmtaylor.dev
Subject
Software
Date
Read
10 min

Retries: when they help and when they make it worse

Which errors to retry, why backoff needs jitter, why retries belong in one layer, and the retries AWS already does for you whether you asked or not.

Contents
  1. What’s safe to retry
  2. Back off, with jitter
  3. Cap them: attempts and time
  4. Retry in one layer, not all of them
  5. A kill switch for when you already know
  6. The retries AWS already does for you
  7. When retrying stops
  8. The takeaway
  9. Test yourself
  10. Further reading

Retries are everywhere, and they’re easy to overlook. Most code has them, often several layers of them, and most of the time nobody thinks about them because they work: a request fails, you send it again, and a moment later it gets through.

Done wrong, they can take down your system and the systems downstream of it. A service that’s struggling under load gets every failed request back again, often from every layer above it at once. That’s a retry storm: the retries meant to ride out a small problem become a big one, and they keep the struggling service from recovering.

Getting them right comes down to a few decisions: what to retry, how long to wait, how many times, where, and when to stop calling altogether.

What’s safe to retry

Two questions, and both have to be yes.

Is the error temporary? Retry only what has a real chance of working the second time:

Retry Don’t retry
Timeouts and dropped connections Validation errors (400, ValidationException)
Throttling (429, ThrottlingException) Access denied (403)
Server errors (500, 502, 503, 504) Not found (404)

The rule of thumb: a 4xx status means the request was the problem, so don’t retry it, and a 5xx means the server was, so a retry might work. The exceptions are the ones in the table: 429 Too Many Requests is a 4xx you should retry, after waiting, because the request was fine and you just sent too many. 408 Request Timeout is the same. If the response includes a Retry-After header, wait at least that long; the server is telling you when it expects to have room.

A request with bad input will be just as bad the second time. Retrying it only delays the error and adds load. (There’s one gray area: in an eventually consistent system, a “not found” right after a create can turn into a success a moment later. Retry that on purpose, a few times, not by accident.)

Is the operation safe to repeat? A timeout means you don’t know what happened. The request may have failed, or it may have succeeded and only the response was lost. Retry a payment after a timeout and you may charge the customer twice. Reads are safe to repeat. Writes are safe only if they’re idempotent: built so that doing them twice has the same effect as doing them once.

Back off, with jitter

Retrying immediately is the worst option. If the service failed because it’s overloaded, an instant retry adds load at the exact moment it can least handle it.

Exponential backoff waits longer after each failure: say 100 ms, then 200, then 400. Each retry gives the service more room to recover. Always cap the wait, or the delays grow past the point anyone is still waiting for the answer.

Backoff alone isn’t enough. If a thousand clients fail at the same moment, they all wait 100 ms and retry at the same moment, then all wait 200 ms and retry together again. The service sees waves of traffic instead of a steady flow. Jitter fixes that by randomizing each wait: instead of exactly 200 ms, wait a random time between 0 and 200 ms. The thousand retries spread out.

// Exponential backoff with full jitter.
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

async function withRetry<T>(call: () => Promise<T>, maxAttempts = 3): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await call();
    } catch (err) {
      if (attempt >= maxAttempts || !isRetryable(err)) throw err;
      const cap = Math.min(10_000, 100 * 2 ** attempt); // grows each time, never past 10 s
      await sleep(Math.random() * cap);
    }
  }
}

You rarely need to write this for AWS calls. The AWS SDKs already do it: the default standard retry mode makes 3 attempts in total (the first try plus two retries), with exponential backoff and jitter.

For calls the SDK doesn’t make, like another team’s HTTP API, there are libraries for this in most languages (for example exponential-backoff or cockatiel in TypeScript, and Tenacity in Python). Whichever you pick, check the defaults. exponential-backoff has jitter off unless you set jitter: 'full', cockatiel’s retry() doesn’t wait between attempts unless you give it a backoff, and “retry everything” includes the 4xx errors you shouldn’t.

Cap them: attempts and time

Every retry loop needs a limit, and two limits are better than one:

  • A maximum number of attempts. Three is a common default for a reason. If three tries didn’t work, the problem probably isn’t a blip.
  • A deadline. If a user is waiting on a page, retries that finish after they’ve given up are wasted work. Stop when the answer would be too late to matter.

Retries also need timeouts to be useful. A call with no timeout can hang forever and never fail, so it never retries. Set one on every remote call. Too long and threads pile up waiting; too short and slow-but-healthy calls fail and get retried, which adds load of its own.

Retry in one layer, not all of them

This is the mistake that causes the big outages.

Say a request passes through three services, and each one retries failed calls 3 times. When the database at the bottom starts failing, the bottom service sends 3 requests for every one it gets. The service above it retries that 3 times, and so does the one above that: 3 × 3 × 3 is 27 requests to the database for every request a user made. The database was failing because it was overloaded, and now it’s getting 27 times the traffic.

AWS’s Builders’ Library article on retries uses a five-deep stack with three retries at each layer, and gets a 243× increase in load on the database.

One request through services A, B and C, each trying every call 3 times.

The fix is to retry in one place, usually the layer closest to the failure, and have the layers above it pass the error up. If you can’t control every layer, at least know how many there are.

What the database sees depends on how many layers retry, not on which one calls it:

Who retries Calls to the database
Nobody 1
Only C, closest to the database 3
B and C 9
A, B and C 27

And it only multiplies while the failure lasts. If C’s second try works, nobody above it retries at all. The 27 shows up during an outage, exactly when the database can least handle it.

A second guard is a retry budget: retry freely while failures are rare, and stop retrying when they’re common. The AWS SDK’s standard mode has one built in, a token bucket that each retry draws from and each success refills. When failures are widespread, the bucket empties, and the SDK returns errors right away instead of piling on.

A kill switch for when you already know

Backoff and budgets react to failures as they happen. Sometimes you know before your code does: the other team has declared an outage, or a partner’s API is down for maintenance tonight. Then every call to it is wasted, and every retry is load on a system that’s trying to recover.

I like putting a kill switch on calls to dependencies like that: a flag that, when it’s on, skips the call entirely and fails fast, without retrying. Flip it when the system is down, and flip it back when it’s up.

  • For a call inside your code, keep the flag somewhere you can change without a deploy, like AWS AppConfig or a Parameter Store parameter, and check it before making the call.
  • For a Lambda function reading from SQS, you can pause the whole consumer instead: disable the event source mapping, and messages wait in the queue instead of burning through their retries and landing in the dead-letter queue. Re-enable it when the downstream is back, and the backlog drains on its own. (Messages still expire at the queue’s retention period, 4 days by default, so this is for outages, not for parking work indefinitely.)
  • Decide what “off” means for each call. Return a clear error, serve a cached answer, or save the work to do later. What it shouldn’t do is silently drop the request.

A circuit breaker is the automatic version: after enough failures in a row, it stops calling for a while, then lets a test request through to see if the system is back. It’s useful, but it has to see failures before it trips. A kill switch lets you act on what you already know.

The retries AWS already does for you

Many AWS services retry on their own. That’s useful, but it’s also how you end up with retries in several layers without writing a single loop:

  • AWS SDK: 3 attempts by default in standard mode, as above.
  • Lambda, invoked asynchronously (by S3 or SNS, for example): 2 more attempts after the first failure, then the event goes to an on-failure destination or a dead-letter queue, if you set one.
  • SQS: a message that isn’t deleted becomes visible again after the visibility timeout and is received again, until it hits the queue’s maxReceiveCount and moves to the dead-letter queue.
  • EventBridge: retries delivery to a target for up to 24 hours by default.
  • Step Functions: retries only what you list in a state’s Retry block. The defaults are a 1-second first wait, 3 attempts and a backoff rate of 2.0, with no jitter unless you set JitterStrategy to FULL.

Now stack them. A Lambda function reads from an SQS queue with a maxReceiveCount of 5, and calls another AWS service through the SDK. If that service is throttling, each message can be tried 5 times, and each try makes up to 3 SDK attempts, before it lands in the dead-letter queue. Every message becomes up to 15 calls, and add your own retry loop on top and it multiplies again. That’s often fine. It just shouldn’t be a surprise.

When retrying stops

Retries handle the blips. Some failures aren’t blips, and after the last attempt the work still has to go somewhere:

  • Back to the caller, with a clear error, if someone is waiting.
  • To a dead-letter queue, if it’s background work, with an alarm on the queue and a redrive once the cause is fixed. The event-driven vs batch post covers that in detail.

What it should never do is disappear. A retry loop that gives up and logs a warning, with nobody reading the logs, is data loss with extra steps.

The takeaway

  • Retry only what can work next time: timeouts, throttling and server errors, not bad input.
  • Make writes idempotent before you retry them. A timeout doesn’t mean it failed.
  • Back off, with jitter, and cap both the attempts and the total time.
  • Retry in one layer. Retries multiply across layers, and they multiply hardest against the thing that’s already failing.
  • Have a kill switch for dependencies you know are down, so you stop calling them instead of retrying into them.
  • Count the retries AWS adds, from the SDK, Lambda, SQS, EventBridge and Step Functions.
  • Give exhausted retries somewhere to go: the caller or a dead-letter queue.

Test yourself

1. A call to create an order times out. Is it safe to retry?

Only if the create is idempotent. A timeout means you don’t know whether the order was created. If the request carries an idempotency key that the server checks, a retry returns the original order instead of making a second one. Without that, a retry can create a duplicate.

2. An API returns 400 with "email is required." How many times should you retry?

None. The request is wrong, and it will be just as wrong the second time. Return the error, or fix the input.

3. 500 clients hit a throttling error at the same moment, and each retries after exactly 1 second. What happens?

All 500 retry at the same moment, the service is overloaded again, and most get throttled again. Jitter spreads the retries across the wait window so the service sees a steady trickle instead of a spike.

4. An API Gateway endpoint calls a Lambda function, which calls a second service with your own retry loop of 3 attempts. The second service calls an AWS service through the SDK, with the default 3 attempts. How many attempts can reach that AWS service for one user request?

Up to 9: 3 attempts from your loop, each making up to 3 SDK attempts. Pick one layer to own the retries. Often that means relying on the SDK at the bottom, and passing errors up from your own loop instead of retrying them.

Further reading