Concurrency · mid
How asyncio works, and a blocked event loop
An async def call returns a coroutine, and the event loop runs tasks on one thread, switching at each await. One blocking call in a coroutine stops every request in that process.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Calling an async def function returns a coroutine object. Nothing runs until it is awaited or wrapped in a task. A coroutine that is never awaited gives RuntimeWarning.
- The event loop runs tasks on one thread. At an await on I/O, the task pauses and the loop runs another. The operating system says when sockets are ready.
- It is cooperative: a task that never awaits (CPU work, a blocking call) stops everyone.
- await a(); await b() runs one after the other. create_task or a TaskGroup runs them at the same time.
- asyncio.run() makes and closes the loop. Since 3.14, asyncio.get_event_loop() raises RuntimeError when no loop is running.
- Symptom of a blocked loop: every endpoint is slow, even the health check, and CPU is low. Proof: asyncio debug mode (PYTHONASYNCIODEBUG=1) logs slow callbacks; py-spy dump shows the main thread inside a socket read.
- Fixes: an async HTTP client with timeouts, or await asyncio.to_thread(func) for a sync SDK, plus a timeout and circuit breaker. CPU-heavy work goes to a process pool; to_thread does not make it parallel.
- Other blockers: a sync database driver, time.sleep, parsing huge JSON, PDF or image work, sync logging over the network. Ruff has lint rules for blocking calls in async def.
The red pen
Common traps: mistake → fix
Mistake: Async code runs in parallel threads
Fix: it runs on one thread and switches at await.
Mistake: time.sleep is fine in a coroutine
Fix: it blocks the whole loop; use await asyncio.sleep.
Mistake: Add more pods when all endpoints stall
Fix: find the blocking call first.
Mistake: to_thread makes CPU work parallel
Fix: the GIL still applies.
Easy to hard
Questions interviewers ask, easy to hard
- What happens when you call an async def function and await it?
- How can one thread serve thousands of requests?
- What is the difference between await a(); await b() and creating two tasks?
- p99 went from 40 ms to 3 seconds on every endpoint with low CPU after a release. What do you do?
- How do you stop it happening again?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.