Retries, Timeouts, Backoff, and Circuit Breakers

Set API deadlines, bounded retries, exponential backoff, and circuit breakers so transient failures recover without multiplying load or hiding outages.

published: reading time: 12 min read author: Geek Workbench updated: November 5, 2026
Quick Summary

The examples fit two downstream calls inside one deadline, retry a safe read with jitter, and protect an uncertain payment replay with idempotency. A circuit breaker can stop calls while a dependency is unhealthy.

Retries, Timeouts, Backoff, and Circuit Breakers

Introduction

Suppose a client makes three attempts and gives each one a fresh 500 ms timeout. A slow dependency can keep the caller waiting for 1.5 seconds, plus backoff, while concurrent retries add more load to the same service. An overall deadline keeps every attempt and wait inside one request budget.

// Per-attempt timeouts can exceed the caller's total budget.
for (let attempt = 0; attempt < 3; attempt++) {
  await fetch(url, { signal: AbortSignal.timeout(500) });
}

Pick one layer to own retries. Set a deadline for the whole request, then classify which failures may be retried. A circuit breaker handles a longer outage by refusing new calls for a while.

One request inside a 2.5-second deadline

This example has one caller-visible budget of 2,500 ms and two downstream calls. Each call may be attempted at most twice, so the request has a hard cap of four attempts. Each attempt has a 400 ms timeout cap. Times below are illustrative; production budgets should come from the route’s latency objective and dependency behavior.

The first call is a safe inventory read. It returns a temporary 503 with Retry-After: 1:

HTTP/1.1 503 Service Unavailable
Retry-After: 1

Retry-After may be an HTTP date or a non-negative integer number of seconds. RFC 9110 says a server may use it with 503; RFC 6585 allows it with 429. The client treats the server delay as a minimum, adds a small jitter, and retries only if that wait plus another attempt fits the remaining deadline. See RFC 9110 §10.2.3, RFC 9110 §15.6.4, and RFC 6585 §4.

Elapsed time Operation Result and budget decision
0–250 ms GET /inventory/sku-7, attempt 1 503 with Retry-After: 1.
250–1,300 ms Wait Wait 1,000 ms as requested, then add 50 ms jitter.
1,300–1,600 ms GET /inventory/sku-7, attempt 2 200; the read completes.
1,600–2,000 ms POST /payments, attempt 1 The 400 ms attempt times out. The server may have committed even though the response did not arrive.
2,000–2,075 ms Wait Add 75 ms of jitter.
2,075–2,380 ms POST /payments, attempt 2 Retry with the same idempotency key and unchanged payload; the API performs the operation once and returns its result.
2,380–2,500 ms Reserve Return the result with 120 ms left for response handling.

The payment write is safe to replay only because that API contract deduplicates the same key and payload. The key header is application-defined. Without that protection, do not retry the POST after an ambiguous timeout. RFC 9110 defines GET as safe in §9.2.1 and advises against automatic retries of non-idempotent requests in §9.2.2 unless the client knows the operation is idempotent or the original was not applied. The idempotency guide covers the write-side protection.

Before starting a retry, require wait + 400 ms <= remaining budget; otherwise return the latest response or error and stop. In the table, the read retry needs 1,450 ms (1,050 wait + 400 attempt cap) from its 2,250 ms remainder. The payment retry needs 475 ms (75 + 400) from its 500 ms remainder. Assume separate inventory and payment breakers, both closed at the start. If the inventory breaker opens, stop inventory retries; that does not block the independent payment call. The payment breaker gates its own attempts.

If the payment retry is still running when the 2,500 ms deadline expires, abort the client’s in-flight request or sleep, return a deadline error, and start no further attempts. An abort stops the client from waiting; it does not prove the remote server rolled back work that may already have committed.

The payment request uses the same application-defined key and body both times:

POST /payments
Idempotency-Key: pay-ord-91
Content-Type: application/json

{"orderId":"ord_91","amountCents":4250}

Backoff and breaker behavior

Exponential backoff increases the delay after each failed attempt, often with jitter to avoid many clients retrying together. A practical policy caps both the number of attempts and maximum delay. Honor a valid Retry-After response only when its delay plus one full attempt fits within the caller’s deadline. Never use unbounded retries in a request handler: they consume threads, connections, and the user’s time.

A circuit breaker counts failures over a window. In the open state, it rejects requests quickly instead of sending them to a failing dependency. After a cooldown, it permits a small number of probes in a half-open state. A breaker is not a retry mechanism; it limits pressure and gives the dependency room to recover.

The flow below combines the caller’s deadline and retry budget with the breaker lifecycle. Every retry returns through the breaker check, so a breaker that opens during an attempt can stop the next call.

flowchart TD
    A[Incoming call] --> B[Set overall deadline and retry budget]
    B --> C{Breaker state?}
    C -->|Closed| E[Check remaining deadline]
    C -->|Open| N[Return fast failure]
    C -->|Half-open| F{Probe slot available?}
    F -->|Yes| E
    F -->|No| N
    E --> T{Time remains?}
    T -->|No| N
    T -->|Yes| G[Call dependency with timeout capped by remaining budget]
    G --> H{Attempt succeeds?}
    H -->|Yes| I[Record success; close breaker after successful probe]
    I --> J[Return response]
    H -->|No| K[Classify failure and record breaker result]
    K --> L{Threshold reached or probe failed?}
    L -->|Yes| M[Open breaker until cooldown]
    M --> N[Return terminal failure]
    M -->|Cooldown expires| F
    L -->|No| O{Retryable and attempts remain?}
    O -->|No| N
    O -->|Yes| P[Choose capped exponential backoff with jitter]
    P --> Q{Wait fits deadline and retry budget?}
    Q -->|No| N
    Q -->|Yes| R[Consume retry budget and wait]
    R --> S{Breaker still closed?}
    S -->|Yes| E
    S -->|No| C

Retry policy trade-offs

Policy choice Operational effect Latency and load trade-off
Fixed backoff Waits the same interval after each retry; easy to predict and tune for a brief, known interruption. Keeps recovery timing simple, but clients failing together can retry together and create a traffic spike.
Exponential backoff with jitter Grows the wait after each failure and randomizes it; cap the delay and attempt count. Spreads retry traffic and reduces pressure, while later attempts can add more tail latency.
Shared retry budget Limits total retries across requests or over a time window, alongside the per-request attempt cap. Prevents retries from consuming most of the dependency capacity, but some requests fail sooner when the budget runs out.
Per-call timeout plus circuit breaker The timeout bounds one attempt; the breaker rejects calls quickly after sustained failures and allows limited probes after cooldown. Short timeouts and sensitive breaker thresholds shed load sooner, but can cut off slow or recovering calls; loose limits increase waiting and pressure.

A deadline-aware read loop

This TypeScript sketch is for a safe GET. Set the shared deadline once, at request ingress, from a monotonic clock such as performance.now(). Pass that same deadline to both downstream calls. The policy-specific helpers accept valid Retry-After values, classify retryable transport failures, and reject a sleep when its signal aborts.

async function getWithRetry(
  url: string,
  deadlineAt: number,
  callerSignal: AbortSignal,
): Promise<Response> {
  const initialRemaining = deadlineAt - performance.now();
  if (initialRemaining <= 0) throw new Error("request deadline exceeded");

  const overallSignal = AbortSignal.any([
    callerSignal,
    AbortSignal.timeout(initialRemaining),
  ]);
  const maxAttempts = 2;
  const maxAttemptMs = 400;

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const remaining = deadlineAt - performance.now();
    if (remaining <= 0 || overallSignal.aborted)
      throw new Error("request cancelled or deadline exceeded");

    const attemptSignal = AbortSignal.any([
      overallSignal,
      AbortSignal.timeout(Math.min(maxAttemptMs, remaining)),
    ]);
    let response: Response;
    try {
      response = await fetch(url, { method: "GET", signal: attemptSignal });
    } catch (error) {
      if (
        overallSignal.aborted ||
        !isRetryableTransportError(error) ||
        attempt + 1 === maxAttempts
      )
        throw error;
      const delay = Math.random() * 100;
      if (delay + maxAttemptMs > deadlineAt - performance.now()) throw error;
      await abortableSleep(delay, overallSignal);
      continue;
    }

    if (![429, 502, 503, 504].includes(response.status)) return response;
    if (attempt + 1 === maxAttempts) return response;

    const serverDelay =
      parseRetryAfter(response.headers.get("Retry-After")) ?? 0;
    const backoff = Math.min(100 * 2 ** attempt, 500);
    const delay = Math.max(serverDelay, backoff) + Math.random() * 100;
    const remainingAfterResponse = deadlineAt - performance.now();
    if (delay + maxAttemptMs > remainingAfterResponse) return response;

    await response.body?.cancel();
    await abortableSleep(delay, overallSignal);
  }
  throw new Error("unreachable");
}

The 400 ms cap is also part of the budget check: after a proposed wait, the loop starts another attempt only if that full cap still fits. Use an equivalent cancellation API if the runtime does not support AbortSignal.any or AbortSignal.timeout.

When retries help

Retry transient errors only when the operation is safe to repeat and another attempt can finish within the request budget. A circuit breaker can stop calls when a dependency stays unhealthy. Permanent client errors need a request change; writes need idempotency protection before replay. Set timeouts from the service’s observed latency and the caller’s full request budget.

Production failure scenarios and mitigations

  • After a fleet restart, clients reconnect and retry together. Add jitter and a retry budget to spread the extra traffic.
  • A payment commits, but its response times out. The client cannot tell whether the charge happened; require an idempotency key and return the saved result on a duplicate.
  • A breaker opens during a few slow responses. Tune latency and error thresholds separately, then inspect per-operation metrics before changing the policy.
  • Several service layers each retry the same call. Their attempts multiply; assign retry ownership to one layer and propagate the original deadline.

Observability checklist

  • Measure attempt count, final outcome, and time spent waiting between attempts.
  • Track timeout rates and latency percentiles by dependency and operation.
  • Export breaker state transitions and rejected-call counts.
  • Alert on sustained retry volume as well as final request failures.
  • Include trace and correlation IDs while avoiding secrets in logs.

Security notes and pitfalls

Retries can amplify a denial-of-service condition, so apply concurrency limits and bounded queues. Treat remote error bodies as untrusted input, cap their size, and avoid copying sensitive payloads into logs. Do not interpret a client-side timeout as a cancellation guarantee. Keep breaker state local to the dependency boundary; a single global breaker can let one failing route block unrelated work.

Quick recap checklist

  • Set a request deadline and fit all attempts within it.
  • Retry only transient failures, with an attempt cap and randomized backoff.
  • Make writes idempotent or otherwise safe to repeat.
  • Use a circuit breaker to limit calls during sustained dependency failures.

Interview questions

1. Why add jitter to exponential backoff?
Without jitter, clients that fail together may retry together, creating synchronized traffic spikes. Randomized delays spread that traffic over time.
2. Does a timeout cancel server-side work?
Usually not by itself. It stops the caller from waiting, while the server may still be processing. Cancellation needs an explicit protocol and still may arrive after a side effect has committed.
3. How is a circuit breaker different from retry?
A retry repeats an individual operation after a selected failure. A breaker tracks a pattern of failures and temporarily blocks calls to reduce pressure on a dependency.
4. Why should retries usually be owned by one layer in a service call chain?
If multiple layers retry independently, their attempt counts multiply and can produce far more downstream calls than intended. One layer should own retry policy while the shared deadline limits the whole operation.
5. How should a client choose an attempt timeout when it has an overall deadline?
Use the remaining end-to-end budget as the upper bound for each attempt, leaving time for any permitted backoff and later attempts. A fresh full timeout per attempt can exceed the caller's deadline.
6. What does a half-open circuit breaker state allow?
It allows a small number of probe calls after the cooldown. Success suggests the dependency recovered and the breaker can close; failure reopens it to limit further pressure.
7. Why should a circuit breaker be scoped to a dependency or operation?
A broad breaker can let one failing route block unrelated healthy work. Narrow scopes isolate the failure while still protecting the affected dependency.
8. Which failures are usually poor candidates for automatic retries?
Validation and authorization errors generally require a request or permission change, so repeating them will not help. Non-idempotent writes are also unsafe to retry unless protected by a stable idempotency key.
9. How should a client use Retry-After when it also has a deadline?
Honor a valid Retry-After delay only if it fits within the remaining deadline and retry budget. If waiting would exceed either, return the failure instead of retrying after the caller no longer needs the result.

Further reading

Conclusion

Give retries one job: recover from brief faults. Stop when the request deadline runs out, and let the breaker reject calls while a dependency stays unhealthy. For writes, require idempotency before replaying.

Category

Related Posts

Idempotency, Deduplication, and Safe Replays

Design idempotent API operations and deduplication records so clients can retry after timeouts without creating duplicate payments, jobs, or updates.

#api-design #idempotency #retries

GraphQL Federation: Subgraphs, Routing, and Trade-offs

Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.

#graphql #federation #microservices

Network Latency, Timeouts, and Failure

Learn how latency, bandwidth, and jitter shape backend requests, then set useful timeouts, bounded retries, and failure handling without amplifying outages.

#networking #backend #reliability