Async I/O and Concurrency
LLM apps spend most of their time waiting on the network; async code lets you run many model calls at once without threads everywhere.
Beginner · about 8 hours · difficulty 3/5
Learn first: HTTP, REST APIs and JSON
A single model call may take 2 to 30 seconds. If you process 1,000 documents one at a time, you wait hours; with controlled concurrency you wait minutes. Async I/O is how you do that efficiently.
How it works
In Python, asyncio runs an event loop: when a coroutine awaits a network call, the loop switches to another coroutine. In JavaScript this model is built in. Most model SDKs ship async clients (for example AsyncAnthropic or AsyncOpenAI in Python).
Patterns you need
- Gather with a limit:
asyncio.gatherruns tasks concurrently; wrap calls in anasyncio.Semaphoreso you do not blow through rate limits. - Timeouts:
asyncio.wait_foror SDK-level timeouts so one slow call does not hang a batch. - Streaming: async iterators let you forward tokens to a user while they are generated.
- Background work: long jobs (ingesting documents, running evals) belong in a task queue or background worker, not inside a web request.
Pitfalls
- Calling a blocking function (like a synchronous HTTP client or heavy CPU work) inside async code freezes the whole loop.
- Unbounded concurrency triggers 429 errors; always cap it.
- Forgetting to
awaitproduces coroutine objects instead of results.
Good enough to move on
You can take a list of 200 prompts, run them concurrently with a limit of 10 in flight, with timeouts and retries, and collect results in order.
Key concepts
- Event loop and coroutines
- asyncio.gather and semaphores: Bounded concurrency
- Timeouts and cancellation
- Async iterators for streaming
- Background jobs and task queues
- Promise.all and p-limit in JS
Mini project
Write a script that fetches 200 URLs (or calls a mock slow API) concurrently with at most 10 requests in flight, a per-request timeout, and a progress counter, then compare its runtime with a sequential version.
Check yourself
Why can adding more concurrency make a batch job slower or fail entirely when calling a hosted model API?
Free resources
- asyncio documentation (python.org)
- HTTPX async support (HTTPX)
- MDN: Using promises (MDN)