Code Lab / Challenge 11

Token-Bucket Rate Limiter + Retry with Backoff

MediumToken bucket, exponential backoff with jitter

The problem, as an interviewer would set it

LLM APIs throttle you (HTTP 429). Implement the two client-side primitives
every production caller needs, designed for deterministic testing:

1. TokenBucket(capacity, refill_rate, clock=time.monotonic)
     - starts full; refills continuously at `refill_rate` tokens/second,
       capped at `capacity`
     - try_acquire(tokens=1) -> bool          (non-blocking)
     - time_until_available(tokens=1) -> float seconds
     - both raise ValueError if tokens > capacity: no wait can satisfy it
     - `clock` is injectable so tests can use fake time.

2. RateLimitError(retry_after: float | None = None) - exception carrying the
   server's optional Retry-After hint.

3. retry(max_attempts=5, base_delay=1.0, max_delay=30.0,
         retryable=(RateLimitError,), sleep=time.sleep, rng=random.random)
     - decorator implementing exponential backoff with FULL jitter:
           delay = rng() * min(max_delay, base_delay * 2**attempt)
     - if the caught exception has retry_after set, wait at least that long
     - re-raise the last exception after max_attempts failures
     - `sleep` and `rng` are injectable for tests.
What interviewers look for

Burst vs. sustained rate reasoning, why jitter prevents thundering herd, retry budget caps

A strong solution demonstrates:
- Lazy refill (compute elapsed * rate on access) instead of a background
  thread - simpler, exact, and trivially testable.
- Why FULL jitter: deterministic exponential backoff synchronizes retries of
  many clients into thundering-herd waves; sampling uniformly in [0, cap]
  decorrelates them (the classic AWS Architecture Blog result).
- Honouring Retry-After: the server knows its window, and retrying inside it
  burns attempts on guaranteed 429s, so take max(hint, jittered delay). Real
  headers may carry seconds or an HTTP-date; parse both.
- LLM limits are usually two buckets, requests per minute AND tokens per
  minute. try_acquire(tokens=n) exists so one bucket can be charged the
  request's estimated prompt plus max output tokens, not just 1 per call.
- Dependency injection of clock/sleep/rng - the difference between a test
  suite that runs in milliseconds and one that actually sleeps.
Common mistakes: sleeping before the FIRST attempt; off-by-one so the code
sleeps after the final failure; int token counts that leak fractional refill;
jitter as +/- 10% of a fixed delay (barely decorrelates); no max_delay cap,
so with a 1 s base the 13th retry may wait over an hour (cap 2**12 s);
a request larger than `capacity`, which no amount of waiting can satisfy and
which must fail fast rather than loop on 429s;
retrying non-idempotent side effects (a tool call that already fired) as if
they were reads.
Follow-ups: make the bucket thread-safe; add an async variant; distributed
limiting across processes (Redis + Lua); a retry budget or circuit breaker so
a sustained outage does not multiply load by max_attempts; read the
provider's remaining-requests and remaining-tokens response headers (names
vary by provider) to throttle proactively instead of reactively.

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge