Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

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.

SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? open the hints under the problem, or 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.

CPython · WebAssembly
Examples and constraints 4 examples
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 []
edge case: no retries → no delays
EXAMPLE 4
Input retries=3, base=10, cap=3
Output [3, 3, 3]
edge case: the cap is below the base, so every delay is clamped
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).
Hints 3 ideas
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.
Approach, complexity & discussion — open after you solve

Start from brute force

The obvious first draft builds each delay from scratch: for attempt i, start at base, double it i times in an inner loop, then clamp with min(cap, …). It is correct, because doubling base i times gives exactly base × 2ⁱ, and it needs O(retries) space for the list. But attempt i costs i multiplications, so the whole schedule costs 0 + 1 + … + (retries − 1), which is O(retries²). It also keeps doubling long after the cap has been reached, so the unclamped value grows without bound: a long integer in Python, and eventually infinity in floating point, all to produce a value that min immediately throws away.

The approach

The delay has a closed form, so no state needs to carry from one attempt to the next: attempt i waits min(cap, base × 2ⁱ). Because 2ⁱ only grows, the schedule never decreases, and once a delay reaches cap every later delay equals cap. That is the invariant the tests check: exactly retries entries, doubling from base, flat at cap.

The reference solution is one list comprehension, [min(cap, base * (2 ** i)) for i in range(retries)]. range(retries) yields i from 0 to retries - 1, so the first delay is base itself and an input of retries = 0 returns [] with no special case. The function is deliberately pure: no sleeping, no retry decision and no randomness. Real clients also randomize these delays so that callers who failed together do not retry together; that randomness, jitter, is the whole subject of the Exponential Backoff with Full Jitter challenge, and leaving it out here keeps the schedule deterministic and easy to test.

delay = min(cap, base × 2^i)12481016cap=10i=0i=1i=2i=3i=4retries fire at t = 1, 3, 7, 15, 25 s
The first example, backoff_delays(5, 1, 10), drawn to scale. Each bar doubles the last until the raw value (dashed 16) crosses the cap and min clamps it. The running sums along the bottom are when the retries actually go out. Had the schedule continued without the clamp, the next three waits would have been 32, 64 and 128 seconds, nearly four minutes between the fifth and eighth retry; with it, each extra retry adds exactly 10 seconds.

Walk through an example

Trace the first example, backoff_delays(5, 1, 10), one list element per value of i.

step2 ** ibase * 2 ** imin(cap, …)list so far
i = 0111[1]
i = 1222[1, 2]
i = 2444[1, 2, 4]
i = 3888[1, 2, 4, 8]
i = 4161610 (capped)[1, 2, 4, 8, 10]

Complexity

Optimal: O(retries) time, one closed-form delay per attempt, and O(retries) space for the list. Strictly, 2 ** i is an i-bit integer in Python, so for enormous retry counts each step costs more; clamping a running delay avoids that. Brute force (doubling from base for every attempt): O(retries²) multiplications, O(retries) space.

Edge cases to test

  • retries = 0 → []. range(0) is empty, so no special case is needed.
  • A cap below the base: backoff_delays(3, 10, 3) → [3, 3, 3]. Every delay is clamped from the first attempt.
  • Reaching the cap exactly: backoff_delays(6, 5, 20) → [5, 10, 20, 20, 20, 20]. Once a delay equals cap, it stays there.
  • Mixed types: backoff_delays(5, 0.5, 3) → [0.5, 1.0, 2.0, 3, 3] in Python, because min returns whichever argument is smaller, here the integer cap. JavaScript has one number type, so the question does not arise there.
  • A zero base: backoff_delays(3, 0, 10) → [0, 0, 0], which means retrying immediately in a tight loop. Validate that base is positive.
  • Huge retry counts: with a float base, Python’s 1.0 * 2**1024 raises OverflowError, while JavaScript’s 2 ** 1024 is Infinity and Math.min clamps it to cap. An integer base never overflows in Python; it just builds very long integers.

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.
  • Starting the exponent at 1 instead of 0: the first example then gives [2, 4, 8, 10, 10] instead of [1, 2, 4, 8, 10].

Follow-ups an interviewer asks next

How would you add jitter to this schedule?
Multiply each capped delay by a random fraction between 0 and 1 (full jitter), so clients that failed together spread across the window instead of retrying on the same tick. That is exactly the Exponential Backoff with Full Jitter challenge, which passes the random fractions in as an argument so the output stays deterministic and testable.
How do you turn the schedule into a retry loop?
Call the operation; on success return, and on a retryable failure sleep for the next delay and try again; after the last delay, raise the final error. Classify errors first: retry timeouts, 429 and 503, but give up at once on 400, 401 or 404. Also check an overall deadline, so the waits cannot outlast what the caller is willing to wait.
How long does a client wait in total?
Before the cap the delays form a geometric series: the first k of them sum to base × (2ᵏ − 1). After the cap, add cap for each remaining attempt. For the first example that is 1 + 2 + 4 + 8 + 10 = 25 seconds. If the total is longer than the caller’s deadline, lower retries or cap.
How do you avoid huge numbers for large retry counts?
Keep a running delay that stops at the cap: start with d = min(cap, base), then for each attempt append d and set d = min(cap, d * 2). The value never exceeds twice the cap, so it cannot overflow or grow into a long integer, and because doubling is exact in binary floating point, the list matches the closed form.
The caller gives you a total budget of D seconds. How many retries fit?
Walk the schedule with a running total and stop before the next delay would exceed D. With base = 1, cap = 30 and D = 60, the delays 1, 2, 4, 8 and 16 sum to 31, and the next delay of 30 would take the total to 61, so 5 retries fit. With base = 0.5, cap = 8 and D = 30, the delays 0.5, 1, 2, 4, 8 and 8 sum to 23.5, so 6 fit. Deriving retries from the deadline, instead of choosing both separately, keeps the two from contradicting each other.

Where this shows up

Retry-with-backoff is the resilience pattern for any flaky remote call. Paired with jitter (randomizing each delay, covered in the Exponential Backoff with Full Jitter challenge) 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.

It is older than HTTP. Classic Ethernet resolved collisions on a shared cable with binary exponential backoff, each station picking a random wait from a window that doubled after every collision, and TCP doubles its retransmission timeout each time a retransmitted segment times out again. The same reasoning applies at every layer: when a shared resource is overloaded, each participant must send less often the longer the trouble lasts, or the retries themselves keep it overloaded.

Retries multiply across layers. If a front end, a service and its database client each make up to 4 attempts, one user request can turn into 4 × 4 × 4 = 64 calls to the database when it is failing, exactly when it can least absorb them. The usual fixes are to retry at one layer only, to pass a deadline down so inner layers stop when the caller has given up, and to cap retries with a budget, for example allowing retries to add at most a small fraction to a client’s request rate, so that a widespread outage does not multiply the load.

Listen to the server. HTTP lets a server send a Retry-After header with 429 and 503 responses, giving either a number of seconds or a date. When it is present it is better information than any client-side schedule, so a well-behaved client waits at least that long, and uses its own backoff only when the header is missing. For agents that call model APIs and tools, this is the difference between riding out a rate limit and burning the remaining quota on retries that were always going to be rejected.

Check yourself

Predict backoff_delays(6, 3, 50).

[3, 6, 12, 24, 48, 50]. The raw values are 3 × 2⁰ through 3 × 2⁵ = 96; only the last exceeds 50, so only it is clamped. A cap that is not a power-of-two multiple of the base produces one “partial” step like this.

How long does backoff_delays(8, 1, 30) make a client wait in total?

121 seconds. The list is [1, 2, 4, 8, 16, 30, 30, 30]: the doubling part sums to 2⁵ − 1 = 31, and the three capped attempts add 90. Once the cap is reached, the total grows linearly, by cap per extra retry.

A refactor writes min(cap, base) * 2 ** i, clamping before doubling. What does it return for retries=3, base=10, cap=3?

[3, 6, 12], where the reference returns [3, 3, 3]. Clamping the input does not clamp the output: the doubling happens after min, so the delays sail past the cap. The clamp has to be the last operation.

With base = 0.1 and cap = 60, at which attempt index does the delay first equal the cap, and how does that index grow with cap / base?

At i = 10: the reference gives …, 25.6, 51.2, 60, because 0.1 × 2¹⁰ = 102.4 is the first raw value above 60. In general it is the smallest i with 2ⁱ ≥ cap / base, so ⌈log₂(cap / base)⌉: the uncapped stretch grows logarithmically in the ratio.

Can a later delay in the list ever be smaller than an earlier one?

No, as long as base is positive. base * 2 ** i grows with i, and taking min with a fixed cap keeps that order, so the list rises and then stays flat at the cap. Jitter is what breaks this order on purpose.

Reference solution

Reference solution — Python
def backoff_delays(retries, base, cap):
    return [min(cap, base * (2 ** i)) for i in range(retries)]


print(backoff_delays(5, 1, 10))   # -> [1, 2, 4, 8, 10]
print(backoff_delays(3, 2, 100))  # -> [2, 4, 8]
Reference solution — TypeScript
function backoffDelays(retries: number, base: number, cap: number): number[] {
  const out: number[] = [];
  for (let i = 0; i < retries; i++) out.push(Math.min(cap, base * 2 ** i));
  return out;
}

console.log(backoffDelays(5, 1, 10));   // -> [1, 2, 4, 8, 10]
console.log(backoffDelays(3, 2, 100));  // -> [2, 4, 8]

Questions about Retry with Exponential Backoff

What is exponential backoff?

Exponential backoff is a retry strategy in which the wait before each new attempt doubles: with a base of 1 second, the waits are 1, 2, 4 and 8 seconds and so on, usually clamped at a maximum so they stop growing. The doubling means a struggling service sees fewer and fewer retries from each client the longer it stays unhealthy, instead of a constant stream. In this challenge the delay for attempt i is base times 2 to the power i, capped at cap, and the function returns the whole schedule as a list, without sleeping or randomness.

Why cap the delay in exponential backoff?

Without a cap the delay grows without bound: with a 1-second base, the tenth delay is already 512 seconds and the twentieth is more than six days. A client that waits that long has usually failed from its user’s point of view, and it will also be slow to notice when the service recovers. The cap keeps the waits in a useful range while keeping the early backing off. In this challenge, once base times 2 to the power i reaches the cap, every remaining delay equals the cap.

Should exponential backoff include jitter?

In production, almost always. Plain exponential backoff spaces out one client’s retries, but every client that failed at the same moment retries on the same schedule, so they arrive together in synchronized waves. Jitter randomizes each delay so the retries spread out. This challenge deliberately leaves randomness out so the schedule is deterministic and easy to test; adding full jitter, where each delay is a random fraction of the capped exponential, is the subject of the separate Exponential Backoff with Full Jitter challenge.

Which errors should be retried with backoff?

Only failures that might succeed if you try again later: timeouts, connection resets, HTTP 429 Too Many Requests, 503 Service Unavailable and similar transient conditions. Errors that describe the request itself, such as 400 Bad Request, 401 Unauthorized or 404 Not Found, will fail the same way every time, so retrying them only wastes time and load. The operation must also be safe to repeat: a retried payment that actually succeeded the first time charges twice, unless the request carries an idempotency key that the server deduplicates on.

Finished this one? 0 / 76 Challenges done
NextParse a Tool Call Next on the “Agents & loop engineering” ladder · rung 3 of 9

Explore the topic

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

More Challenges