Skip to main content
03

Resilient LLM client

Mediumretriesexponential backoffjitterrate limitingtoken bucket

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

LLM APIs fail all the time in production: rate limits at peak hours, overloaded servers, requests that time out. Build the two pieces that keep an app working through it: a retry loop with exponential backoff, and a token-bucket rate limiter that keeps you under the provider's limits in the first place.

The API

python
client.chat(messages).content   # the reply's text, or raises one of these:

RateLimitError     # 429: too many requests; error.retry_after is seconds to wait, or None
ServerError        # 5xx: the provider failed or is overloaded; error.status is 500, 502, 503 or 529
APITimeoutError    # the request took too long
BadRequestError    # 400: the request itself is wrong
AuthenticationError  # 401: the API key is invalid

All of them subclass APIError and are already defined. Time and randomness are passed in, so tests run instantly and give the same result every time:

  • sleep(seconds) waits on a fake clock, and clock.now() reads it, in seconds.
  • rand() returns a number in [0, 1), like random.random().

Part 1: retry transient errors

Write chat_with_retry(client, messages, sleep, rand, max_retries=3, base_delay=1.0, max_delay=8.0). It returns the reply's text.

  • Retry RateLimitError, ServerError and APITimeoutError, up to max_retries times, so at most max_retries + 1 calls. sleep before each retry.
  • Raise any other error straight away. A bad request or a wrong key fails the same way every time.
  • Out of retries: raise the last error, and don't sleep before raising it.

Part 2: backoff with jitter

How long to sleep before retry number n (0 for the first retry):

  • If the error is a RateLimitError with a retry_after, sleep exactly that.
  • Otherwise use full jitter: rand() * min(max_delay, base_delay * 2 ** n).
text
base_delay=1, max_delay=8, rand() = 0.5  →  sleeps 0.5, 1, 2, 4, 4, ...

The doubling backs off from a struggling server. The cap stops the waits from growing without limit. The jitter keeps a thousand clients that failed at the same moment from all retrying at the same moment too.

Part 3: a token bucket

Write class RateLimiter with __init__(self, rate, capacity, clock, sleep) and acquire(self, tokens=1).

  • The bucket holds up to capacity tokens and starts full. It refills continuously at rate tokens per second, and never past capacity.
  • acquire(tokens) takes that many tokens. If the bucket has fewer, it first sleeps exactly as long as the refill takes, in one sleep call. It returns the seconds it waited, 0 when it didn't wait.
  • Asking for more than capacity can never succeed: raise ValueError.
python
limiter = RateLimiter(rate=2, capacity=2, clock=clock, sleep=sleep)
limiter.acquire()  # 0: the bucket starts full
limiter.acquire()  # 0: now it's empty
limiter.acquire()  # 0.5: one token takes 1/2 second to refill

Providers limit tokens per minute as well as requests, so in real code tokens is often the request's estimated size.

Note

Run plays the scenarios in tests.json, which you can edit. Each one scripts the API's replies and errors, the values rand() returns, and for the limiter, the method calls and how much time passes between them. Submit runs all the hidden scenarios. The Trace tab shows every call, error and sleep on the fake clock.

Follow-up questions interviewers ask

  • Retrying a request that creates something (sends an email, charges a card) can do it twice. How do idempotency keys fix that?
  • Retries multiply load on a service that is already failing. How does a circuit breaker help, and what is a retry budget?
  • The primary model is down for minutes, not seconds. When do you switch to a fallback model or provider, and what changes in the prompt?
  • A response is streaming and the connection drops halfway. Do you retry, and what do you show the user?
  • Ten worker processes share one API key. Where does the rate limiter live now?

The approach

Two separate tools for two separate problems. Retries recover from failures that already happened. The rate limiter prevents the most common failure, a 429, by not sending more than the provider allows. Production clients use both.

Which errors to retry

The question to ask about each error: will the same request work later?

ErrorRetry?Why
429 RateLimitErrorYesCapacity frees up over time
5xx ServerErrorYesOverload and outages are usually brief
APITimeoutErrorYesThe next attempt may be faster
400 BadRequestErrorNoThe request is wrong; it fails every time
401 AuthenticationErrorNoThe key won't fix itself

Retrying a 400 only multiplies the cost and delays the real error. That's why the code catches the RETRYABLE tuple, not APIError or Exception.

The loop

for attempt in range(max_retries + 1) bounds the calls. On a retryable error, the last attempt re-raises with a bare raise, which keeps the original traceback. Every other attempt sleeps and goes round again. Sleeping before giving up would only make the caller wait longer for the same error.

Loading diagram...

Why backoff and jitter

Retrying immediately hits a struggling server again before it can recover. Doubling the delay backs off fast: 1, 2, 4, 8 seconds. The cap keeps a long outage from producing a ten-minute wait.

Without jitter, every client that failed in the same second also retries in the same second, in synchronized waves that keep knocking the server over (the "thundering herd"). Full jitter, rand() * delay, spreads the retries evenly across the window. Applying the cap first, then the jitter, keeps the spread even at the cap.

When a 429 carries retry_after, the server is saying exactly when it will have room, so the code uses that number instead of guessing.

The token bucket

The bucket stores up to capacity tokens and refills at rate per second. A full bucket allows a burst of capacity requests, and after that requests are paced at rate. The refill is computed lazily from the clock on each call, so no background timer is needed:

text
tokens = min(capacity, tokens + (now - last_update) * rate)

If there aren't enough tokens, the exact wait is (needed - tokens) / rate. One sleep for exactly that long beats polling in small steps: it wakes up once, at the right moment. A request bigger than capacity could never be served, so it raises instead of waiting forever.

Complexity

acquire is O(1) time and memory, whatever the traffic. That's why token buckets are the standard: a sliding-window log has to remember every request in the window.

Reference solution

python
# Transient failures: waiting and sending the same request again can succeed.
RETRYABLE = (RateLimitError, ServerError, APITimeoutError)


def chat_with_retry(client, messages, sleep, rand, max_retries=3, base_delay=1.0, max_delay=8.0):
    for attempt in range(max_retries + 1):
        try:
            return client.chat(messages).content
        except RETRYABLE as error:
            if attempt == max_retries:
                raise  # Out of retries: let the caller see the last error.
            sleep(backoff_delay(error, attempt, rand, base_delay, max_delay))
        # Anything else (a bad request, a wrong API key) fails the same way every time: no retry.


def backoff_delay(error, attempt, rand, base_delay, max_delay):
    """Seconds to wait before retry number `attempt` (0 for the first retry)."""
    retry_after = getattr(error, "retry_after", None)
    if retry_after is not None:
        return retry_after  # The server knows when it will have capacity again.
    # Full jitter: anywhere between 0 and the capped exponential delay.
    return rand() * min(max_delay, base_delay * 2 ** attempt)


class RateLimiter:
    """A token bucket: holds up to `capacity` tokens and refills at `rate` tokens per second."""

    def __init__(self, rate, capacity, clock, sleep):
        self.rate = rate
        self.capacity = capacity
        self.clock = clock
        self.sleep = sleep
        self.tokens = capacity  # Starts full, so a burst can go out at once.
        self.updated = clock.now()

    def _refill(self):
        now = self.clock.now()
        self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
        self.updated = now

    def acquire(self, tokens=1):
        if tokens > self.capacity:
            raise ValueError(f"Can't take {tokens} tokens from a bucket that holds {self.capacity}")
        self._refill()
        waited = 0.0
        if self.tokens < tokens:
            waited = (tokens - self.tokens) / self.rate
            self.sleep(waited)
            self._refill()
        self.tokens -= tokens
        return waited