Async Python for AI Apps
Read a little, play a little. No scary maths, and no rush.
Waiting is the job
AI apps spend most of their time waiting: for the LLM's tokens, the vector DB's neighbors, the tool API's response. Synchronous code waits the dumb way — ask, stare at the wall, next. Async waits the smart way: fire ten requests, handle each as its stream delivers. Same waiting, 10× the throughput on one thread.
async/await in 60 seconds
Mark a function async and it becomes pausable. await pauses that task and hands the event loop to others until the waited thing finishes:
import asyncio
async def ask(q):
await asyncio.sleep(0.1) # stand-in for: await llm.stream(q)
return f"answer to {q}"
async def main():
# all 10 fly at once; total ≈ 0.1s, not 1.0s
return await asyncio.gather(*[ask(f"q{i}") for i in range(10)])
asyncio.run(main())
asyncio.gather is the workhorse: fan out retrieval + LLM draft + tool calls together instead of sequentially.
A real fan-out
A RAG request needs three things before it can call the model: relevant document chunks (300 ms), the user's profile for personalization (200 ms), and a check of the answer cache (100 ms). None depends on the others.
Done one after another, that is 600 ms of waiting. With asyncio.gather, all three start together and the total is set by the slowest, about 300 ms. Nothing got faster; the waits simply overlap. On a request that users feel, halving the wait is a big win for one line of code.
Limiting how many run at once
Fanning out is easy to overdo. Firing 1,000 API calls at the same instant will trip the provider's rate limit and return a wall of 429 errors. A semaphore caps how many are in flight:
limit = asyncio.Semaphore(10)
async def ask_limited(q):
async with limit: # at most 10 inside at a time
return await ask(q)
All 1,000 tasks are created, but only ten talk to the API at any moment; the rest wait their turn. Treat ten as a starting point and set the real number from your provider's published rate limits.
Where async shines (and where it doesn't)
- Yes: streaming tokens to users, fanning out retrieval, websockets, concurrent API calls.
- No: pure CPU crunching (the event loop can't parallelize math — use threads/processes), or simple scripts where sync reads clearer.
One gotcha for later: never call blocking code (time.sleep, heavy loops) inside async functions — it freezes the whole loop. Reach for asyncio.to_thread when you must.
Timeouts and partial failures
Every awaited network call needs a deadline. asyncio.wait_for(ask(q), timeout=30) raises an error instead of waiting forever. When gathering many calls, asyncio.gather(*tasks, return_exceptions=True) returns errors alongside successes, so one failed request does not throw away the other nine results. Check each result and retry or report the failures.
Async inside a web app
Frameworks such as FastAPI let you write async def endpoints, so one server process can handle many users waiting on slow AI calls at once. The catch is that every library you call inside must be async too: use an async HTTP client (httpx.AsyncClient) and the async version of your AI SDK. A single ordinary blocking call, such as requests.get, inside an async endpoint stalls every other user on that process until it returns.
Remember this
await= "I'll be back when this finishes; serve others meanwhile."- Network waits → async. CPU burns → threads. Don't mix them up.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
End of Python for AI
Take the section checkpoint
A short mixed quiz on all 3 chapters, to check you are ready to move on.
Related chapters
Spotted a mistake or want a topic covered? Report an issue