In this coding round you may use an AI assistant. Implement a rate-limited async client that retries failed model calls with exponential backoff and jitter. Talk through how you use the assistant and how you check its output.
Answer
Model answer, written in a candidate's voice
In short
- Frame the problem first: concurrency cap (semaphore) plus token bucket, retryable vs non-retryable errors, Retry-After, idempotency
- Use the assistant for scaffolding/boilerplate, then read every line and state what I accept, change and reject
- Catch generated-code bugs: retrying non-idempotent or 4xx errors, unbounded retries, missing jitter, time.sleep inside a coroutine, swallowed cancellation
- Reviewed implementation: token bucket + semaphore, full-jitter exponential backoff, Retry-After floor, bounded attempts, cancellation propagates
- Tests with a mocked client and fake clock: success, transient failure, permanent failure, timeouts, non-idempotent, cancellation, rate; run them
- State complexity and limits (per-process bucket); production adds metrics, circuit breaker, per-tenant and shared limits
In full
I would start by pinning down the contract before prompting: a concurrency cap (semaphore) plus a token bucket for request rate, a clear split between retryable errors (timeouts, connection resets, 408, 429 and 5xx) and non-retryable ones (validation 4xx, auth failures), honouring Retry-After when present, and retrying only idempotent calls, or non-idempotent ones that carry an idempotency key.
Then I would use the assistant to draft the skeleton — async client, retry loop, backoff helper and test scaffolding — and read every line. I accept the structure and boilerplate; I change blocking sleeps to asyncio.sleep, add full jitter and a max-attempt bound; I reject any blanket retry on 4xx or non-idempotent requests, any bare except that swallows cancellation, and any unbounded loop. The reviewed version looks like this:
import asyncio, random, time
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
class APIError(Exception):
def __init__(self, status, retry_after=None):
super().__init__(f"HTTP {status}")
self.status, self.retry_after = status, retry_after
class TokenBucket:
def __init__(self, rate_per_s, burst):
self.rate, self.capacity = rate_per_s, burst
self.tokens, self.updated = float(burst), time.monotonic()
self.lock = asyncio.Lock()
async def acquire(self):
async with self.lock:
while True:
now = time.monotonic()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return
await asyncio.sleep((1 - self.tokens) / self.rate) # never time.sleep here
class RateLimitedClient:
def __init__(self, send, max_concurrency=8, rate_per_s=5.0, burst=10,
max_attempts=5, base_s=0.5, cap_s=30.0):
self.send = send # async callable: one request to the model API
self.sem = asyncio.Semaphore(max_concurrency)
self.bucket = TokenBucket(rate_per_s, burst)
self.max_attempts, self.base_s, self.cap_s = max_attempts, base_s, cap_s
async def call(self, payload, idempotent=True):
for attempt in range(self.max_attempts):
await self.bucket.acquire()
try:
async with self.sem:
return await self.send(payload)
except (APIError, TimeoutError, ConnectionError) as e:
status = getattr(e, "status", None) # None: timeout or connection error
retryable = status is None or status in RETRYABLE_STATUS
if not (retryable and idempotent) or attempt == self.max_attempts - 1:
raise
delay = random.uniform(0, min(self.cap_s, self.base_s * 2 ** attempt)) # full jitter
if getattr(e, "retry_after", None):
delay = max(delay, e.retry_after)
await asyncio.sleep(delay) # CancelledError is not caught, so cancellation propagates
I would ask the assistant for tests with a mocked send function (and asyncio.sleep patched or tiny delays, as a fake clock) covering success, a transient failure that succeeds on retry, a permanent 400 that is not retried, timeouts that stop at the attempt limit, a non-idempotent call that is not retried, cancellation during a Retry-After wait, and the bucket’s rate over a burst; then I run them and read any failure rather than trusting green output. Each call keeps O(1) extra state and makes at most max_attempts requests. It is not a full production limiter: the bucket is per process, and its lock serialises waiters (simple, and fair in arrival order). In production I would add metrics, a circuit breaker, per-tenant limits, a shared limiter across replicas and idempotency-key handling, and check the code against the real API’s error semantics instead of assuming the assistant got them right.
What a strong answer covers
- Frames the problem first (concurrency cap, token bucket or semaphore, retryable versus non-retryable errors, Retry-After headers, idempotency) before prompting the assistant
- Uses the assistant for scaffolding or boilerplate but reads every line, explaining what it accepts, changes and rejects
- Catches typical generated-code bugs: retrying on non-idempotent or 4xx errors, unbounded retries, missing jitter, blocking sleeps inside async code, swallowed cancellation
- Writes or asks for tests with a fake clock or mocked client covering success, transient failure, permanent failure, timeouts and cancellation, and runs them
- States complexity and limits, and what would change in production (metrics, circuit breaker, per-tenant limits)
Common mistakes
- Pasting generated code without reading or testing it
- Calling time.sleep inside a coroutine
Follow-ups
- The assistant’s version passes your tests but you suspect a race. How do you find it?