asyncio and the Python Concurrency Model
A backend spends much of its time waiting on LLM APIs, databases and file storage. All of that is I/O waiting, and asyncio is the foundation of FastAPI.
Core concepts
| Approach | Good for | Notes |
|---|---|---|
| asyncio (coroutines) | Lots of concurrent I/O (LLM calls, HTTP, databases) | A single-threaded event loop that switches at each await |
| Multithreading | Calling blocking I/O libraries | Traditional CPython has the GIL: only one thread executes Python bytecode at a time |
| Multiprocessing | CPU-bound work (parsing, OCR, vector math) | Sidesteps the GIL, but inter-process communication is costly |
| Free-threaded Python | Truly parallel execution of Python code across threads | Introduced experimentally in 3.13; from 3.14 an officially supported optional build (PEP 779, e.g. python3.14t). The default build still has the GIL |
How it works
- Coroutines: defined with
async def. Calling one gives you a coroutine object, which only runs once it isawaited or wrapped in a Task. - Event loop: maintains a queue of ready tasks; a task yields control when it
awaits a Future that isn't done. A long computation with noawaitstalls the entire loop. - Structured concurrency (3.11+):
asyncio.TaskGroupmanages a group of child tasks. If any fails, the rest are cancelled and anExceptionGroupis raised.asyncio.timeout()provides scoped timeouts. - Cancellation:
task.cancel()raisesCancelledErrorat the task's nextawait. If you catch it, clean up and re-raise it; don't swallow it.
In practice
Calling several LLMs concurrently with a concurrency limit
python
import asyncio
sem = asyncio.Semaphore(5) # avoid triggering the provider's rate limit
async def check_rule(rule, doc):
async with sem:
async with asyncio.timeout(30): # 30-second timeout per rule
return await llm.judge(rule, doc)
async def check_all(rules, doc):
async with asyncio.TaskGroup() as tg: # if any fails, the others are cancelled
tasks = [tg.create_task(check_rule(r, doc)) for r in rules]
return [t.result() for t in tasks]When you want to "carry on despite partial failures", use asyncio.gather(..., return_exceptions=True) and check each result.
Running blocking / CPU-bound functions from async code
python
text = await asyncio.to_thread(parse_docx, path) # blocking I/O → thread
loop = asyncio.get_running_loop()
pages = await loop.run_in_executor(process_pool, ocr, path) # CPU-bound → process poolCommon pitfalls
- Forgetting
await: the coroutine never runs; you just getRuntimeWarning: coroutine was never awaited. - Not keeping a reference after
create_task: the task may be garbage collected. The official docs specifically warn you to keep a reference. - Swallowing
CancelledError: breaks timeout and shutdown logic. - Unbounded concurrency: hundreds of requests hit the LLM API at once and you get 429s immediately. Control it with a Semaphore.
Common interview questions
- Which scenarios suit coroutines, threads and processes? How does the GIL affect each?
- How does the event loop schedule coroutines? What blocks it?
- What's the difference between
TaskGroupandgather? - How does task cancellation propagate?
- What is free-threading in Python 3.13/3.14? Is it ready for production?
To be verified / may go stale
- The free-threaded build is at the "officially supported but optional" stage, and compatibility of third-party C extensions varies. Verify each dependency before using it in production.
Sources
- Python Docs: Coroutines and Tasks — TaskGroup, timeout, cancellation, keeping task references
- Python Docs: asyncio.to_thread
- PEP 779: Criteria for supported status for free-threaded Python
- What's New In Python 3.14
- Python Docs: Free-threading HOWTO
