跪拜 Guibai
← All articles
Python · Performance Optimization · Backend

One Sync Line Froze the Event Loop for 4 Seconds — A 20-Line Probe Catches It

By Wellijohn ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

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.

Summary

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.

Takeaways
— A 20-line asyncio heartbeat probe measures event loop stalls by recording real intervals between 10ms sleeps; the max gap equals the freeze duration.
— Writing synchronous code directly inside an async coroutine kills concurrency: 50 tasks of 80ms became 4.00s wall-clock, with the loop frozen for 4001ms.
— asyncio.to_thread reduced that stall to 667ms but not to the 11ms baseline, because the GIL hands off every 5ms and the default thread pool has only 14 workers on a 10-core machine.
— to_thread gives 7.87x speedup for 8 I/O tasks that release the GIL, but makes 8 CPU-bound tasks slower (0.92x vs serial) due to thread overhead and GIL contention.
— The default executor's _max_workers is min(32, cpu_count + 4); on the test machine it was 14. This caps to_thread's true parallelism.
— Mixing slow I/O and short CPU tasks in the default thread pool delays the short tasks by 0.98s; separate pools with different max_workers avoid the queueing.
— asyncio.wait_for cannot interrupt blocking code inside a coroutine because the loop is busy; it also cannot cancel a running thread, so side effects still execute after timeout.
— ProcessPoolExecutor gave 5.11x speedup with 8 processes on 8 tasks, not 8x, due to fork and serialization overhead. More processes than tasks adds no benefit.
— Unbounded create_task for 100k coroutines peaked at 153.7 MB memory; unbounded asyncio.Queue with 200k items peaked at 42.8 MB. Setting maxsize brings near-zero memory.
— Separate pools for I/O and CPU, plus queue.maxsize and a final reconciliation assert, turn these findings into a safety net for async batch code.
— The combination of wait_for timeout and non-idempotent operations is dangerous: a timed-out thread still writes to the database, so side effects need idempotency keys.
Conclusions

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.

Concepts & terms
Event loop probe
A heartbeat task that logs the real time between its 10ms wake-ups, so any delay caused by a blocking synchronous call in the event loop becomes visible as a gap in the timestamps.
GIL (Global Interpreter Lock)
A lock in CPython that allows only one thread to execute Python bytecode at a time. It limits thread-based parallelism for CPU-bound tasks and causes context-switching overhead that makes to_thread ineffective for such work.
asyncio.to_thread
A helper that runs a synchronous function in the default thread pool, allowing the event loop to keep running while blocking I/O waits. It works well for I/O that releases the GIL, but poorly for CPU-bound code.
ProcessPoolExecutor
A concurrent.futures executor that runs callables in separate processes, bypassing the GIL and enabling real parallelism for CPU-heavy tasks. It carries serialization overhead for passing data between processes.
Backpressure
A mechanism to limit how quickly producers can push items into a queue, preventing unbounded memory growth. In asyncio, setting maxsize on an asyncio.Queue makes producers await put() when the queue is full.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗