Retry the wrong error and you get a retry storm or a double charge. Here is a simple guide to which errors to retry, which to fail fast on, and how to retry without making an outage worse.
Every backend engineer writes a retry loop at some point. It usually starts with a good reason: "the network blipped once, let's just try again." Five minutes later there's a for loop, a maxAttempts = 5, and a warm feeling of having made the system more reliable.
Sometimes you did. Sometimes you just built a machine that hits a struggling service five times harder at the exact moment it asked you to stop.
The short answer: retry an error only if all three of these are true:
- It's temporary. Trying again later could give a different answer. A
503 might. A 400 never will.
- It's safe to repeat. Doing the operation twice won't charge someone twice or send two emails.
- Retrying won't make things worse. You wait between tries, you stop at some point, and you don't flood a service that's already down.
Everything else should fail fast, with a clear error.
This post goes through each question with real code from three broken systems: an email worker that blocked itself, a checkout that charged people twice, and a search API that stayed down long after the database came back.
Question 1: Is the error temporary?
Some errors are like a busy phone line. Call back in a minute and you'll get through. Others are like calling a number that doesn't exist. You can call it a thousand times and it will still not exist.
Here's a cheat sheet for HTTP and network errors:
| Error | What it means | Retry? | |---|---|---| | Connection refused / reset | The other side wasn't reachable for a moment | Yes, with backoff | | 502, 503, 504 | A server or proxy in the middle is struggling | Yes, with backoff | | 429 Too Many Requests | You're sending too fast | Yes, but wait as long as Retry-After says | | Timeout | You don't know what happened | Only if the operation is safe to repeat (see question 2) | | 500 Internal Server Error | Could be a blip, could be a bug | Maybe a couple of times, then stop | | 400, 422 | Your request is wrong | No. Fix the request | | 401, 403 | You're not allowed | No (unless you refresh a token first, once) | | 404 | It isn't there | No | | 409 Conflict | The state changed under you | Re-read the state, then decide |
Retrying a 400 is like sending the same text with a typo to someone over and over, hoping it fixes itself. It won't. The request is wrong, and every retry is just extra work for both of you.
The same goes for database errors. A dropped connection or a deadlock victim (Postgres error 40P01) is worth another try. A unique constraint violation or a syntax error is not. The query will fail the same way every time, forever.
The 500 is the tricky one. Sometimes it's a pod restarting, and a retry works. Sometimes it's a null pointer on line 42, and you can retry until the heat death of the universe. Retry it a couple of times at most, and make sure it shows up in your logs as an error, not a warning.
Question 2: Is it safe to repeat?
This is the one people forget. A timeout doesn't mean the request failed. It means you don't know if it failed.
Maybe the server never got your request. Maybe it got it, charged the card, and the response got lost on the way back. From your side, those two look exactly the same: a spinner, then a timeout.
If the operation is a read (GET /products/42), no problem. Read it again. If the operation moves money, sends an email, or creates an order, a blind retry can do it twice.
Here's a real example. This checkout service already did half the work right. Every checkout must carry an Idempotency-Key header, and the mobile app retries with the same key when a checkout looks slow. Good! Here's the worker that records the charge:
func (c *Checkout) charge(ctx context.Context, payment Payment) error {
_, err := c.db.Exec(ctx, `
INSERT INTO payments (idempotency_key, order_id, amount)
VALUES ($1, $2, $3)`, payment.IdempotencyKey, payment.OrderID, payment.Amount)
return err
}
See the problem? The key is stored, but nothing checks it. The client sends the same key twice, and the worker happily inserts two charges. HTTP looks perfect, every request returns 202 Accepted. The bug only shows up where it hurts most, in the money:
idempotency_key | count | sum
------------------------------+-------+--------
order-4-1842-1760278805123 | 2 | 50.00
order-7-1843-1760278805391 | 2 | 168.00
order-2-1844-1760278805602 | 2 | 94.00
An idempotency key that nothing enforces is a seatbelt that isn't clipped in. It looks great in the code review.
The fix is to let the database enforce it, since the database is the one place every worker agrees on:
CREATE UNIQUE INDEX payments_idempotency_key ON payments (idempotency_key);
_, err := c.db.Exec(ctx, `
INSERT INTO payments (idempotency_key, order_id, amount)
VALUES ($1, $2, $3)
ON CONFLICT (idempotency_key) DO NOTHING`,
payment.IdempotencyKey, payment.OrderID, payment.Amount)
Now a retry is harmless. The first charge wins, and every repeat of it does nothing. That's what makes a retry safe: not hoping it won't happen twice, but making "twice" mean the same as "once".
Rule of thumb: before you add a retry to anything that writes, ask "what happens if this runs twice?" If the answer makes you nervous, add an idempotency key and enforce it with a unique constraint first.
Question 3: Will retrying make things worse?
Here's the part where good intentions cause outages.
This is a real notification worker. It sends order confirmation emails through an email provider that allows 100 requests per second. Twenty workers pick up emails and call deliver:
const (
concurrency = 20
maxAttempts = 5
)
func (w *Worker) deliver(ctx context.Context, n Notification) {
for attempt := 1; ; attempt++ {
err := w.send(ctx, n)
if err == nil {
w.finish(ctx, n, "sent", attempt, "")
return
}
if attempt == maxAttempts {
log.Printf("send %s: giving up after %d attempts", n.OrderID, attempt)
w.finish(ctx, n, "failed", attempt, err.Error())
return
}
log.Printf("send %s: %v, retrying (attempt %d)", n.OrderID, err, attempt+1)
}
}
It looks responsible. It retries, it has a limit, it logs. Ship it.
Now look at what's missing between the attempts: nothing. No wait at all. And send turns every status code above 299 into the same plain error, so a 429 ("slow down please") gets exactly the same treatment as a 503 ("I'm down") or a 400 ("your request is broken").
On a normal day, about 40 orders a second come in and the provider accepts them all. Then the provider has a short blip. Every send fails, and each email burns through all 5 attempts in about 150 milliseconds. 40 emails a second × 5 instant attempts = 200 requests a second, against a limit of 100.
The provider does what providers do: it starts answering 429 Too Many Requests with a Retry-After: 1 header. The worker ignores the header and retries immediately. Those retries count against the quota too, so the account stays blocked. The blip is long over, but the worker is now attacking the provider all by itself:
13:05:03 send order-881: 429 Too Many Requests, retrying (attempt 2)
13:05:03 send order-881: 429 Too Many Requests, retrying (attempt 3)
13:05:03 send order-881: 429 Too Many Requests, retrying (attempt 4)
13:05:03 send order-881: 429 Too Many Requests, retrying (attempt 5)
13:05:03 send order-881: giving up after 5 attempts
# curl localhost:9101/stats
{"requests_per_sec":203,"accepted_per_sec":0,"rejected_429_per_sec":203,"quota_per_sec":100,"throttled":true}
203 requests a second. Zero emails sent. Order volume is completely normal. Nothing is wrong except the retry loop.
This is a retry storm. It's like ringing a doorbell, and when nobody answers in 30 milliseconds, ringing it four more times and then leaving forever. Then 39 of your friends do the same thing, every second.
How to retry without starting a storm
Four changes turn this loop from a weapon into a tool.
1. Wait between attempts, and wait longer each time. This is *exponential backoff*: wait 200 ms, then 400 ms, then 800 ms, up to a cap like 5 seconds.
2. Add randomness to the wait. This is *jitter*. Without it, all 20 workers fail at the same moment, wait exactly 200 ms, and come back at the same moment, like a crowd pushing through one door at once. With jitter they spread out.
3. Listen to Retry-After. When a server tells you how long to wait, it's not a suggestion. It's the most useful thing in the whole response.
4. Only retry errors that can get better. Sort the error first. Keep retrying the temporary ones, and fail a permanent one right away.
Here's a sketch of what that looks like in Go:
type sendError struct {
status int // 0 means a network error
retryAfter time.Duration // from the Retry-After header, if any
}
func (e *sendError) temporary() bool {
return e.status == 0 || e.status == 429 || e.status >= 500
}
func (w *Worker) deliver(ctx context.Context, n Notification) {
delay := 200 * time.Millisecond
for attempt := 1; ; attempt++ {
w.limiter.Wait(ctx) // shared by all workers, set under the provider's quota
err := w.send(ctx, n)
if err == nil {
w.finish(ctx, n, "sent", attempt, "")
return
}
var se *sendError
if !errors.As(err, &se) || !se.temporary() {
w.finish(ctx, n, "failed", attempt, err.Error()) // a 400 won't fix itself
return
}
// Wait a random time in the upper half of the delay, and at least
// as long as the server asked for.
wait := delay/2 + rand.N(delay/2)
if se.retryAfter > wait {
wait = se.retryAfter
}
time.Sleep(wait)
delay = min(delay*2, 5*time.Second)
}
}
Notice one more thing: this version doesn't give up after 5 attempts for a temporary error. That's on purpose. An order confirmation should arrive late rather than never. "Retry 5 times instantly, then drop the email" is the worst of both worlds: it hammers the provider *and* loses the email.
The limiter (for example golang.org/x/time/rate) is the part people skip. Backoff makes each worker polite. But 20 polite workers clearing a backlog can still send over 600 requests a second when the provider comes back. A shared rate limiter under the quota means the whole service is polite, not just each worker.
Bonus problem: retries multiply
One retry loop is easy to reason about. Real systems have several, stacked on top of each other.
Say your mobile app retries 3 times. It calls your API, which retries 3 times. Your API calls a database client, which also retries 3 times. One user tap can become 4 × 4 × 4 = 64 database queries when things go wrong. Retries at every layer multiply, they don't add.
Here's a search API that shows how bad this gets. It normally gets 80 searches a second, and the database can handle about 125. Plenty of room. Clients give up after 1 second and retry up to 3 times.
Then Postgres freezes for 10 seconds during a storage failover. Searches pile up in the service's queue. Each one now waits more than a second, so its client has already given up and sent a retry. The service still runs the old query (nobody is waiting for the answer), and the retry joins the back of the queue. 80 searches a second become about 300 requests a second, against a database that does 125.
The database recovers after 10 seconds. The search API doesn't:
21:00:30 db: stall injected for 10s
21:00:40 db: stall cleared
21:05:00 queue_depth=6211 served_rps=124 goodput_rps=2 incoming_rps=301
Five minutes later, the service is working at full speed, 124 answers a second, and only 2 of them reach a client who is still waiting. The database is healthy. The traffic is normal. And the service is down, kept down by its own retries.
The fix here is on the server side:
- Keep the queue small, and say no early. When the queue is full, return
503 with Retry-After: 1 right away. A fast "no" is kinder than a slow "yes" that arrives after the client has left.
- Don't do work nobody will read. If the client's deadline has passed, skip the job. Pass the request's context into the query, so it gets cancelled too.
Rule of thumb: pick one layer to own retries, usually the one closest to the user, and keep the layers below it to one attempt or very few.
A checklist to stick next to your retry loop
Before you merge that for attempt := 1 loop, check:
- [ ] Is the error sorted? Temporary errors retry, permanent errors fail fast.
- [ ] Is the operation safe to repeat? If it writes, it has an idempotency key that the database enforces.
- [ ] Is there backoff with jitter? No instant retries.
- [ ] Does it read
Retry-After?
- [ ] Is there a limit? On attempts, on total time, or on the whole service's rate.
- [ ] Is there only one retrying layer? Or at least, you've done the multiplication.
- [ ] Does a failure show up somewhere? A message that gave up should land in a "failed" table or a dead-letter queue, not just a log line nobody reads.
Common questions
Should I retry a 500 error?
Maybe once or twice, with backoff. A 500 can be a short blip, like a server restarting, or a real bug that fails the same way every time. If it keeps failing, stop and report it, because retrying a bug only hides it.
Should I retry on timeout?
Only if the operation is safe to repeat. A timeout means you don't know if the request worked. Reads are fine to retry. For writes like payments or orders, retry with the same idempotency key, and make sure the server actually enforces that key.
What is exponential backoff with jitter?
Exponential backoff means waiting longer after each failure: 200 ms, 400 ms, 800 ms, and so on, up to a cap. Jitter means picking a random wait around that number, so that many clients that failed at the same moment don't all retry at the same moment too.
How many times should I retry?
There's no magic number, and it depends on the job. A user waiting on a page should get 1 or 2 quick retries, then an error. A background job, like sending an email, can keep retrying temporary errors with backoff for minutes, because late is better than never. Whatever you choose, cap the total time, not just the count.
What's the difference between a retry storm and a DDoS attack?
From the server's side, not much. One comes from strangers on the internet. The other comes from your own code, with your own API key, which is somehow more embarrassing.
Fix one yourself
Reading about a retry storm is one thing. Watching your own worker keep a provider blocked, and then fixing it while orders keep coming in, is how it sticks.
The email-retry-storm stack gives you that exact notification worker: 40 orders a second, an email provider capped at 100 requests a second, and a provider outage in the middle of the load test. You get a terminal, an editor and live logs, in Go, Node.js, Python or Rust. When you think it's fixed, a k6 load test checks that 99% of emails arrive, nothing is sent twice, and the provider never sees more than 110 requests in any second. Shorter retries or fewer workers won't pass.
The double-charge and search examples above are stacks too: double-charge and search-never-recovers.
You can browse stacks without an account. To run labs you sign in with your email or Google account. BustedStack uses your email address to
sign you in, and your name and profile picture to show your account and pre-fill certificates. We never access your Gmail, contacts or Drive,
sell your data or run ad trackers.
This site needs JavaScript to run labs.