Skip to content

Interview question · Build-an-Agent Coding Rounds

Implement retries with backoff, jitter and a retry budget for an agent's tools.

Retry only what can succeed on retry, wait longer each time with randomness, stop when a shared budget says the service is struggling, and hand the model a clear result when retries are over.

mediumNewUpdated Nov 2026

TL;DR: Classify errors first: retry transient ones (timeouts, 429, 503), never validation or permission errors. Wait with exponential backoff and full jitter, respecting a server's Retry-After. Draw retries from a shared budget proportional to recent successes so a failing dependency stops receiving retries. Make every wait and random choice injectable for tests. When retries end, return a structured, non-retryable observation instead of raising into the agent loop.

How to approach it

Define the error classes and the result shape, write the retry function with injectable sleep and randomness, add the budget, and test each path deterministically.

A strong answer

import random

class Transient(Exception):
    def __init__(self, retry_after=None):
        self.retry_after = retry_after

class Permanent(Exception):
    pass

class RetryBudget:
    def __init__(self, ratio=0.1, floor=3):
        self.ratio, self.floor, self.successes, self.retries = ratio, floor, 0, 0
    def record_success(self):
        self.successes += 1
    def take(self):
        if self.retries < max(self.floor, self.ratio * self.successes):
            self.retries += 1
            return True
        return False

def call_with_retries(fn, budget, attempts=4, base=0.2, cap=5.0,
                      sleep=lambda s: None, rng=random.Random(0)):
    waits = []
    for attempt in range(attempts):
        try:
            out = fn()
            budget.record_success()
            return {"ok": out, "attempts": attempt + 1, "waits": waits}
        except Permanent as e:
            return {"error": "permanent", "message": str(e), "retryable": False}
        except Transient as e:
            if attempt == attempts - 1 or not budget.take():
                return {"error": "unavailable", "retryable": False,
                        "message": "service failing; do not retry this call now"}
            wait = e.retry_after or rng.uniform(0, min(cap, base * 2 ** attempt))
            waits.append(round(wait, 3))
            sleep(wait)

def flaky(failures):
    state = {"n": 0}
    def fn():
        state["n"] += 1
        if state["n"] <= failures:
            raise Transient()
        return "ok"
    return fn

b = RetryBudget()
r1 = call_with_retries(flaky(2), b)
print(r1["ok"], r1["attempts"], len(r1["waits"]))  # => ok 3 2
def bad_id():
    raise Permanent("bad id")

r2 = call_with_retries(bad_id, b)
print(r2["error"])  # => permanent
empty = RetryBudget(floor=0)
r3 = call_with_retries(flaky(5), empty)
print(r3["error"])  # => unavailable

Transient failures are retried with growing, randomised waits; a permanent error returns immediately; with the budget exhausted, the call returns a clear "unavailable" observation at once rather than adding load to a failing service.

What to say.

  • "Sleep and randomness are injected so tests are instant and deterministic."
  • "Retry-After overrides the computed wait when the server provides it."
  • "Only idempotent calls are retried automatically; writes need an idempotency key first."
  • "The budget would be shared across the fleet in production, in a fast shared store."

What interviewers probe next

"Why full jitter rather than fixed exponential delays?" Clients that failed together would otherwise retry together; random waits spread them out.

"How does the model see this?" Only the final result: success, or an observation that the service is unavailable and retrying will not help now.

"What about a total time limit?" Add a deadline parameter and stop when the next wait would pass it.

How it's scored

Weak: A loop with time.sleep(1) around every exception.

Hire: Exponential backoff with jitter on transient errors only, with tests.

Strong Hire: Error classification, Retry-After support, full jitter with a cap, a success-proportional budget, injectable sleep and randomness for deterministic tests, a structured final observation, and notes on idempotency, fleet-wide budgets and deadlines.

Common mistakes

  • Retrying permanent errors.
  • Fixed delays that synchronise clients.
  • Real sleeps in tests.
  • Raising the last exception into the agent loop.
You just read a free answer. Every topic opens its first 5 answers to anyone. Sign in and the count per topic goes to 6, and the site remembers where you stopped in each one.Google sign-in · free · no payment details
HOW DID IT GO?
0
READING SIGNED OUT

Signing in raises your free answers from 5 to 6 per topic, adds an applied lesson in every topic and easy practice tests, and the site starts remembering you: mastery per topic, bookmarks, and a next-focus recommendation. Free, no card.

Sign in free
UP NEXT ON YOUR JOURNEY
DISCUSSION · 0

Nobody has commented. Post a correction or another way to answer.