How-To Guide

How to Classify Network Errors for Retries

Sort failures by layer, gate retries on idempotency, parse Retry-After, and add full-jitter backoff with a deadline so retries help instead of amplify.

On this page

  1. Introduction
  2. A taxonomy that matters
  3. The idempotency gate
  4. Delays: Retry-After, backoff, and jitter
  5. Bound the budget with a deadline
  6. Retries are load; act accordingly
  7. Test the classifier, not just the loop
  8. Common pitfalls
  9. Conclusion

Introduction

Retrying a failed request sounds like free reliability and is often the opposite: the retry that helps a transient blip is the same mechanism that turns a partial outage into a self-inflicted denial of service. The difference is classification. A connection refused, a 503 with Retry-After, a 429 quota rejection, a 422 validation rejection, and a DNS resolution failure are not the same event, and a retry policy that treats them identically will hammer some, wait pointlessly on others, and retry requests whose failure already had side effects. This tutorial builds a working classifier: a taxonomy of failures by layer, an idempotency gate that decides whether a request may be retried at all, a delay policy that honors Retry-After and adds full jitter, and a deadline that bounds the entire budget so the caller’s timeout governs instead of an arbitrary attempt count. The examples are in TypeScript, but the decision table is the deliverable and ports directly to any language.

A taxonomy that matters

Classify by layer first, because the layer determines what the failure means. Network layer: DNS resolution failures, connection refused, connection reset mid-flight, and timeouts. These say nothing about the server having seen the request, which is precisely why the idempotency gate exists. HTTP layer: the server responded, and the status code carries policy. 408 request timeout and 429 too many requests are explicitly retryable, the latter with the delay the server specifies. 500 may be transient per instance; 502, 503, and 504 from a gateway usually reflect a temporarily unavailable upstream and are reasonable candidates. 401, 403, 404, 409, and 422 are not retryable with the same inputs, ever: the request is wrong or unauthorized, and repeating it wastes the caller’s time and the server’s capacity. Application layer: a 200 whose body reports an application error, which no generic retry layer should even see, because only the caller knows whether an application-level failure is worth repeating. Writing this table down, one row per class with its verdict, is the actual engineering; the code is a lookup.

The idempotency gate

A transport failure leaves the request’s fate unknown: the server may never have received it, or may have completed it and lost the response. Retrying is only safe when executing twice is equivalent to executing once. GET, HEAD, PUT, and DELETE carry that semantics. POST does not, and a blind retry can duplicate a payment, an order, or a message. Two mechanisms make POST retryable. The first is an idempotency key: the client generates a UUID once, sends it as a header, and the server records the key with the outcome, answering duplicates from the record instead of re-executing. The second is scope restriction: within a bounded internal system, a POST may be known idempotent by construction, and the classifier can be told so explicitly. What the gate forbids is the silent default where everything is retried because the failure looked temporary. The classifier should accept the request’s method and an optional idempotency key, and refuse, loudly, to retry otherwise.

export type Verdict =
 | { retry: true; delayMs: number }
 | { retry: false; reason: string };

export function classify(err: unknown, req: { method: string; idempotencyKey?: string }): Verdict {
 if (err instanceof HttpError) {
  const s = err.status;
  const gated = req.method === 'GET' || req.method === 'HEAD' ||
   req.method === 'PUT' || req.method === 'DELETE' || req.idempotencyKey !== undefined;
  if (s === 429 || s === 503) {
   const ra = parseRetryAfter(err.headers.get('retry-after'));
   return { retry: gated, delayMs: ra ?? 1000 };
  }
  if (s === 408 || s === 500 || s === 502 || s === 504) {
   return { retry: gated, delayMs: 0 };
  }
  return { retry: false, reason: 'status ' + s + ' is not retryable' };
 }
 if (err instanceof TypeError || err.name === 'AbortError') {
  return { retry: req.method !== 'POST' || req.idempotencyKey !== undefined, delayMs: 500 };
 }
 return { retry: false, reason: 'unclassified error' };
}

Delays: Retry-After, backoff, and jitter

When the server states its preference, honor it: a Retry-After header on 429 or 503 is the dependency telling you exactly when to come back, in seconds or as an HTTP-date, and overriding it with your own formula is how clients get themselves banned. When no guidance exists, exponential backoff with full jitter is the default with the best evidence. Exponential growth, base times two to the attempt, bounds the sequence; full jitter, sleeping a uniformly random duration between zero and the exponential bound, decorrelates clients that would otherwise retry in synchronized waves. AWS’s published analysis of thundering-herd behavior found full jitter outperforms equal-jitter and no-jitter variants precisely under contention, which is the condition retries exist in. Cap the ceiling, typically thirty to sixty seconds, so a pathological dependency cannot hold callers for minutes per attempt. And reset the sequence on success, or one error amid healthy traffic leaves every client at a permanently elevated delay.

function fullJitterDelay(attempt: number, baseMs = 500, capMs = 30_000) {
 const bound = Math.min(capMs, baseMs * 2 ** attempt);
 return Math.round(Math.random() * bound);
}

Bound the budget with a deadline

Attempt counts are the wrong currency. Three retries at five seconds each holds the caller for fifteen seconds, which is fine for a background job and catastrophic for a request handler with a two-second budget. Express the retry policy as a deadline: the loop may attempt again only if the remaining time admits the expected attempt duration plus delay, and the whole loop aborts when the deadline passes, regardless of attempts remaining. This composes cleanly up the stack: the caller’s timeout becomes the retry loop’s deadline, the retry loop passes a shrinking deadline to each individual attempt, and the innermost fetch gets a per-attempt timeout that is always less than the remaining budget. The result is that retries never exceed the patience of whoever initiated the work, which is the property every layer actually needs. Without it, the failure mode is subtle: metrics show retries succeeding eventually, while p99 latency quietly balloons because eventually means eleven seconds.

export async function retryWithBudget<T>(
 run: (signal: AbortSignal) => Promise<T>,
 opts: { deadlineMs: number; classify: (e: unknown) => Verdict },
): Promise<T> {
 const deadline = Date.now() + opts.deadlineMs;
 for (let attempt = 0; ; attempt++) {
  const remaining = deadline - Date.now();
  if (remaining <= 0) throw new Error('retry budget exhausted');
  try {
   return await run(AbortSignal.timeout(remaining));
  } catch (err) {
   const v = opts.classify(err);
   if (!v.retry || attempt >= 3) throw err;
   const delay = Math.min(v.delayMs || fullJitterDelay(attempt), deadline - Date.now());
   if (delay <= 0) throw err;
   await sleep(delay);
  }
 }
}

Retries are load; act accordingly

Every retry is a request the dependency would not otherwise receive, which means retry policy is capacity policy. At small scale the effect is invisible; at fleet scale, a dependency returning errors receives its normal traffic plus one retry per failure, so a fifty percent error rate roughly doubles offered load at the worst possible moment. Three mechanisms keep retries from becoming amplification. Retry budgets or attempt caps shared across the fleet: no more than a small fraction of requests to a dependency may be retries, enforced with a shared counter, so excess failures route to the circuit breaker instead. Circuit breaking: after a sliding window of sustained failures, stop calling entirely for a cool-off, converting retry load to zero. Single-flight or deduplicated retries where multiple callers await the same logical operation: one retry serves all of them. Telemetry closes the loop: export retry counts and the status that triggered each, because a dependency whose clients retry heavily is telling you something its own error rate understates.

Test the classifier, not just the loop

The classifier is a pure decision function, which makes it the most testable and most undertested part of most systems. Table-test every row: for each status code and each transport error symbol, assert the verdict and the delay source, including the Retry-After parse for both delta-seconds and HTTP-date forms. Test the gate explicitly: POST without a key must not retry on a transport failure; POST with a key must. Test the budget: with a deadline shorter than one attempt, the loop aborts before the second call; with a deadline between delay and attempt, it does not start a doomed attempt. Test jitter statistically: sample delays and assert the distribution stays within bounds and is not degenerate. Then one integration test through a fake server that fails twice and succeeds on the third, verifying the loop actually recovers, because classifiers tested in isolation have a way of never meeting a real socket.

it('honors Retry-After over formula', () => {
 const v = classify(httpError(429, { 'retry-after': '7' }), { method: 'GET' });
 expect(v).toEqual({ retry: true, delayMs: 7000 });
});
it('never retries a keyless POST on reset', () => {
 const v = classify(new TypeError('fetch failed'), { method: 'POST' });
 expect(v.retry).toBe(false);
});

Common pitfalls

  • Retrying every failure. Client errors and validation failures are not transient; retrying them multiplies load for zero benefit.
  • Blind POST retries. The fate of a transport-failed POST is unknown; duplicate payments are the canonical scar.
  • Ignoring Retry-After. The server stated the terms; clients that override them get rate-limited harder.
  • No jitter. Synchronized retries recreate the outage in waves; full jitter decorrelates them.
  • Attempt counts as the only bound. Three five-second retries exceeds most caller budgets; deadlines are the right currency.
  • Invisible retry load. Without retry metrics, the dependency’s clients quietly double its load during its worst hour.

Conclusion

Retries convert transient failures into non-events only when they are governed by classification. Sort failures by layer: transport errors say nothing about server-side effects, HTTP status codes carry explicit retry policy, and application errors belong to the caller. Gate everything on idempotency, by method or by idempotency key, so unknown-outcome failures are never blindly repeated. Honor Retry-After when present, otherwise exponential backoff with full jitter and a capped ceiling. Express the whole policy as a deadline so retries respect the caller’s patience, and instrument retries as the load they are, pairing the loop with a circuit breaker when failures persist. The deliverable is a one-page decision table plus a small loop; systems without the table end up hard-coding the loop instead and learning the taxonomy in production.

Sources: AWS: Exponential backoff and jitter, MDN: AbortController, MDN: Retry-After header.

FAQ

Should I retry on 500 errors?
Sometimes. A 500 from one instance behind a load balancer may succeed elsewhere, so one retry with jitter is reasonable. Sustained 500s mean the service is broken, and the circuit breaker, not the retry loop, should respond.
What makes a request safe to retry?
GET, HEAD, PUT, and DELETE are idempotent by semantics. POST is not, but becomes retryable when the server honors an idempotency key, which is the standard fix for payment-like flows.
How many retries are appropriate?
Two to three within a deadline, with exponential backoff and full jitter. More attempts rarely succeed and instead hold the caller hostage while multiplying load on a struggling dependency.

Related Examples