方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Implement async batch processing for LLM calls

Implement Async Batch Processing for LLM Calls

Calling an LLM API once takes 500ms–3s. Processing 50 prompts serially takes 25–150 seconds. Async batch processing with a concurrency limiter can reduce that to 5–30 seconds while staying within provider rate limits.

What to build

Implement a BatchProcessor class that:

  1. Accepts a list of prompts and processes them concurrently with a bounded semaphore.
  2. Respects a max_concurrent limit — never fires more than N simultaneous requests.
  3. Applies per-item timeout — each call that exceeds timeout_s raises asyncio.TimeoutError.
  4. Retries transient failures — retry up to max_retries times with exponential backoff + jitter before marking an item as failed.
  5. Returns a structured result — a BatchResult with successes: list[ItemResult] and failures: list[ItemFailure]. A partial failure should NOT abort the batch.
  6. Records latency per item — each ItemResult includes latency_ms.

Constraints

  • Use asyncio.Semaphore for concurrency limiting.
  • Use asyncio.wait_for for per-call timeouts.
  • Use asyncio.gather(..., return_exceptions=True) so one failure does not cancel other tasks.
  • Type-hint every method.

Python Ai / medium / Step 2 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

Review where the boundary is, what gets validated, and what would be hard to debug later.

Practice

Generate a variation

Generate a new exercise variation to deepen understanding or practice a related concept.

Attempt history

Recent submissions

Before you submit, decide what a strong answer should make obvious to the reviewer.

No attempts yet.