Skip to main content
20

Timeouts, retries with backoff and circuit breakers

MediumResilienceRetriesCircuit breaker

How do you make calls to other services resilient? Explain timeouts, retries with backoff and circuit breakers.

TL;DR

Every network call can be slow or fail, so protect each one in layers. Timeouts bound how long you wait, so a slow dependency doesn't tie up all your threads and connections. Retries handle brief failures, but only for idempotent operations, only on retryable errors (timeouts, 503, 429), with exponential backoff and jitter and a small cap. A circuit breaker stops calling a dependency that keeps failing: after a failure threshold it opens and fails fast, then after a cool-down lets a few half-open test calls through before closing again. Together they prevent cascading failures.

Key points

  • Always set timeouts. Many HTTP clients default to none or to minutes.
  • Pass a deadline down the call chain so downstream services don't keep working after the caller gave up.
  • Jitter spreads retries out so clients don't retry in sync and hammer a recovering service (a "retry storm").
  • Retry at one layer only. Retries at every layer multiply: 3 × 3 × 3 = 27 calls.
  • Use a retry budget, such as retrying at most 10% of requests.
  • Bulkheads: separate connection pools per dependency, so one slow dependency can't exhaust everything.
  • Fallbacks: cached or default data, or a degraded feature, instead of an error.

Example

ts
async function callWithRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
  for (let i = 0; ; i++) {
    try {
      return await fn()
    } catch (err) {
      if (i >= attempts - 1 || !isRetryable(err)) throw err
      const backoff = Math.min(1000, 100 * 2 ** i)
      await sleep(Math.random() * backoff) // full jitter
    }
  }
}

await callWithRetry(() => fetch(url, { signal: AbortSignal.timeout(2000) }))

Common follow-ups

  • Why must retried operations be idempotent? A timeout doesn't mean the request failed; it may have succeeded. Retrying a non-idempotent POST without an idempotency key can duplicate it.
  • Where do these patterns live? In client libraries (resilience4j, Polly), or in a service mesh (Envoy, Istio) for every service.

What interviewers look for

Tip

Timeouts first, retries only for idempotent calls with backoff and jitter, circuit breaker states, and the idea of stopping cascading failures.

  • Red flag: unlimited immediate retries with no timeout.

Was this helpful?