← Back to Python, page 5

python-0092 · Hard senior

An asyncio service stalls under load because a handler calls a blocking function. Detect it and fix it.

A blocking call such as time.sleep, requests.get or a heavy computation inside a coroutine stops the whole event loop, so every other request waits. Detect it with asyncio debug mode, which logs callbacks slower than slow_callback_duration, or with latency spikes across unrelated endpoints. Fix it by using an async library, or by moving the call off the loop with asyncio.to_thread or a process pool.

Full answer
python
import asyncio, time

async def heartbeat(ticks):
    for _ in range(5):
        ticks.append(time.perf_counter())
        await asyncio.sleep(0.02)

async def blocking_handler():
    time.sleep(0.1)

async def fixed_handler():
    await asyncio.to_thread(time.sleep, 0.1)

async def measure(handler):
    ticks = []
    await asyncio.gather(heartbeat(ticks), handler())
    gaps = [b - a for a, b in zip(ticks, ticks[1:])]
    return max(gaps)

async def main():
    print("blocking: heartbeat gap over 0.08s:", await measure(blocking_handler) > 0.08)
    print("to_thread: heartbeat gap under 0.06s:", await measure(fixed_handler) < 0.06)

asyncio.run(main())

Output:

text
blocking: heartbeat gap over 0.08s: True
to_thread: heartbeat gap under 0.06s: True

The heartbeat task should tick every 20 ms. With the blocking handler, time.sleep(0.1) freezes the loop and the heartbeat misses its slots, producing a long gap. With asyncio.to_thread, the sleep runs in a worker thread and the heartbeat continues on time. The checks use wide margins, so the output is stable across runs. In production, asyncio.run(main(), debug=True) or PYTHONASYNCIODEBUG=1 logs any step slower than 100 ms by default, naming the slow coroutine. CPU-heavy work should go to a ProcessPoolExecutor via loop.run_in_executor, because threads do not help pure-Python CPU work.

python
import asyncio, time

async def heartbeat(ticks):
    for _ in range(5):
        ticks.append(time.perf_counter())
        await asyncio.sleep(0.02)

async def blocking_handler():
    time.sleep(0.1)

async def fixed_handler():
    await asyncio.to_thread(time.sleep, 0.1)

async def measure(handler):
    ticks = []
    await asyncio.gather(heartbeat(ticks), handler())
    gaps = [b - a for a, b in zip(ticks, ticks[1:])]
    return max(gaps)

async def main():
    print("blocking: heartbeat gap over 0.08s:", await measure(blocking_handler) > 0.08)
    print("to_thread: heartbeat gap under 0.06s:", await measure(fixed_handler) < 0.06)

asyncio.run(main())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Blocking calls freeze the event loop
  • Debug mode logs slow callbacks
  • to_thread for blocking I/O
  • Process pools for CPU work
  • Prefer native async libraries

Common mistakes

  • Calling requests or time.sleep inside async def
  • Running CPU work in threads expecting speed-ups

Follow-ups

  • How would you find which library call blocks?
  • What does the default executor size depend on?

Tips

  • Show the heartbeat gap