Skip to content
Goal: Deep understanding✓ Sources verified 2026-11-24asyncioTaskGroupGILfree-threading

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 ​

ApproachGood forNotes
asyncio (coroutines)Lots of concurrent I/O (LLM calls, HTTP, databases)A single-threaded event loop that switches at each await
MultithreadingCalling blocking I/O librariesTraditional CPython has the GIL: only one thread executes Python bytecode at a time
MultiprocessingCPU-bound work (parsing, OCR, vector math)Sidesteps the GIL, but inter-process communication is costly
Free-threaded PythonTruly parallel execution of Python code across threadsIntroduced 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 is awaited 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 no await stalls the entire loop.
  • Structured concurrency (3.11+): asyncio.TaskGroup manages a group of child tasks. If any fails, the rest are cancelled and an ExceptionGroup is raised. asyncio.timeout() provides scoped timeouts.
  • Cancellation: task.cancel() raises CancelledError at the task's next await. 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 pool

Common pitfalls ​

  1. Forgetting await: the coroutine never runs; you just get RuntimeWarning: coroutine was never awaited.
  2. Not keeping a reference after create_task: the task may be garbage collected. The official docs specifically warn you to keep a reference.
  3. Swallowing CancelledError: breaks timeout and shutdown logic.
  4. Unbounded concurrency: hundreds of requests hit the LLM API at once and you get 429s immediately. Control it with a Semaphore.

Common interview questions ​

  1. Which scenarios suit coroutines, threads and processes? How does the GIL affect each?
  2. How does the event loop schedule coroutines? What blocks it?
  3. What's the difference between TaskGroup and gather?
  4. How does task cancellation propagate?
  5. 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 ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section