One Sync Line Froze the Event Loop for 4 Seconds — A 20-Line Probe Catches It
Event loop blocking is a hidden cause of P99 spikes in async Python services, and this probe turns that mystery into a measurable number. The experiments correct common assumptions about to_thread, default thread pools, and wait_for, giving developers concrete guidance for choosing between threads, processes, and asyncio primitives.
An async endpoint showed almost no QPS improvement after the rewrite: 80 to 95. The signature was perfect, every await in place, yet P99 would occasionally spike from stable to seconds. Logs and tracebacks showed nothing because nothing errored. The missing piece was a probe that measures how long the event loop actually freezes.
A heartbeat task that wakes every 10ms records real intervals between wakes. The gap between two wakes equals the stall time. That probe, about 20 lines of pure asyncio, turned an intermittent mystery into a reproducible number. With it, the author tested common patterns: pure async, sync code inline, and asyncio.to_thread. Inline sync code turned 50 concurrent 80ms tasks into a 4-second serial slog, freezing the loop for 4001ms. to_thread reduced the stall to 667ms but still 60x off the 11ms baseline, because the GIL hands control between threads every 5ms and the default pool has only 14 workers on a 10-core machine.
Further experiments show to_thread gives near-linear speedup for I/O (7.87x on 8 tasks) but makes CPU-bound work slower (0.92x vs serial). The default thread pool fills up with slow I/O calls, delaying short tasks by nearly a second. wait_for cannot cancel blocking code inside a coroutine, nor cancel a thread already running; the side effect still executes. CPU-bound work needs ProcessPoolExecutor, where 8 processes gave 5.11x speedup, not 8x. Unbounded create_task and asyncio.Queue eat memory, while maxsize enforces backpressure. The article closes with a safe_call wrapper that routes coroutines, blocking I/O, and CPU work to the right executor, plus a self-check checklist.
The probe turns a vague 'sometimes slow' complaint into a concrete metric, which is far more useful for debugging than any logging or tracing tool.
to_thread is often treated as a universal 'make sync code async' hammer; the data shows it's only for I/O, and even then it's vulnerable to pool saturation.
The GIL penalty on threads makes thread pools scale worse than expected; it's not just about the number of threads but how often the loop gets preempted.
wait_for gives false confidence: it's a safety net only for truly async code, and its interaction with threads and blocking code is a trap for the unwary.
The memory numbers for unbounded queues and create_task show that async code is not free; backpressure must be designed in, not hoped for.
ProcessPoolExecutor's 5.11x on 8 cores reminds that speedup is not linear; overhead costs real throughput, and the bottleneck often shifts to serialization.