Implement an async client that sends N prompts to an LLM API with at most C requests in flight, a tokens-per-minute limit, exponential backoff with jitter and per-request timeouts, returning results in input order.
Theme reported publicly: ElevenLabs, PolyAI, Anthropic, OpenAI
Answer
Model answer, written in a candidate's voice
In short
- Semaphore(C) bounds in-flight requests; token bucket refilled by elapsed time gates sends; estimate prompt+output tokens before sending and reserve/refund.
- Classify retryable vs non-retryable errors; exponential backoff with jitter and cap; honour Retry-After; max attempts.
- Index every prompt; collect results by index and return in input order; per-request timeout and cancellation; isolate exceptions per request.
- Return structured per-item results instead of raising the first failure; caller cancellation still propagates.
- Test with a fake server injecting 429s, latency, 5xx, malformed responses and slow bodies; assert concurrency, pacing, retries, timeouts, cancellation and order.
In full
I would make the scheduler the only place that talks to the network: each prompt gets an index, an estimated token cost (prompt tokens plus reserved output), and a future, and a worker acquires a semaphore slot for at most C in flight plus a token-bucket permit refilled by elapsed time before sending. Before the request is sent I reserve estimated tokens; on success I reconcile against usage if returned, and on failure I refund or keep the reservation according to whether the request may have been processed. Errors are classified: 429, 5xx, timeouts and connection resets are retryable, while 400/401/403/404/422 are not; retries use exponential backoff with full jitter, a cap, a max attempt count, and honour Retry-After when present. Each request runs under its own timeout and cancellation scope, and exceptions are caught per request so one failure returns a structured error for that index without cancelling the others; the caller can still cancel the whole batch. Results are collected into an indexed list and returned in input order, with per-item status/value/error rather than a single exception. I would test against a fake server that injects 429s with and without Retry-After, latency, 5xx, malformed bodies and slow responses, asserting at most C in flight, token-bucket pacing, retry/backoff behaviour, timeouts, cancellation and exact input-order output.
What a strong answer covers
- Semaphore for concurrency plus a token bucket refilled over time; estimates tokens before sending
- Retryable vs non-retryable errors; backoff with jitter and caps; honours retry-after
- Order preserved via indices; cancellation and timeouts; exceptions isolated per request
- Tests with a fake server that injects 429s, latency and failures
Common mistakes
- Blocking
time.sleepin async code - uncapped retry loops