CODING CHALLENGE · N°14

Retry with Exponential Backoff

Easy AI EngineeringAgentsReliability

Tools time out and APIs rate-limit — a production agent has to retry without hammering. Exponential backoff waits longer after each failure (1s, 2s, 4s, 8s…) up to a cap, so the system backs off instead of piling on. Compute the delay schedule.

The problem

Implement backoff_delays(retries, base, cap). Return the list of wait times before each retry attempt, where the delay for attempt i (0-indexed) is base × 2ⁱ, capped at cap. There are retries attempts in total, so the list has retries entries.

EXAMPLE 1
Input retries=5, base=1, cap=10
Output [1, 2, 4, 8, 10]
doubles each time, then clamps at the cap
EXAMPLE 2
Input retries=3, base=2, cap=100
Output [2, 4, 8]
never reaches the cap
EXAMPLE 3
Input retries=0, base=1, cap=10
Output []
no retries → no delays
CONSTRAINTS
  • Delay for attempt i = min(cap, base × 2ⁱ), with i from 0 to retries − 1.
  • The result always has exactly retries elements.
  • Pure arithmetic — no sleeping, no randomness (that would be jitter, a separate concern).
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement backoff_delays(retries, base, cap) — the exponential-backoff wait schedule, each delay doubling from base and clamped at cap.

HINTS — 3 IDEAS
  1. Loop i from 0 to retries − 1.
  2. The raw delay is base shifted left i times: base × 2**i.
  3. Clamp each delay with min(cap, …) so it never exceeds the cap.
CPython · WebAssembly
Approach, complexity & discussion — open after you solve

The approach

On a failure, retry up to a maximum number of attempts, waiting an exponentially growing delay between tries — base · 2^attempt, capped at a ceiling — and add jitter so many clients do not retry in lockstep. After the cap, stop and surface the error. Crucially, only retry transient failures on idempotent operations.

Complexity

Time O(attempts); the delays dominate wall-clock, not computation.

Common mistakes

  • Retrying a non-idempotent operation, so a “failed” request that actually succeeded runs twice.
  • No cap on attempts or delay — retries stretch into minutes or never stop.
  • Retrying permanent errors (a 400 or 404 will never succeed) — that just wastes time and hammers the service.

Where this shows up

Retry-with-backoff is the resilience pattern for any flaky remote call. Paired with jitter it avoids the thundering herd, and with a circuit breaker it avoids pounding a dependency that is down. Knowing what not to retry — permanent errors and non-idempotent writes — is half the skill.

Finished this one? 0 / 75 Challenges done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges