Engineering note · Production firefighting

FastAPI event loop blocking: why health checks time out

Diagnose FastAPI event loop blocking caused by synchronous calls, large JSON responses, and logging. Learn why health checks fail and how to choose a fix.

An API becomes unresponsive. Health checks time out. Kubernetes restarts the container. The service returns, but the next expensive request can trigger the same failure again.

One possible cause is FastAPI event loop blocking: synchronous work inside an async request handler prevents that loop from serving other requests. Database calls, large JSON responses, and payload logging can all contribute.

Recurring incidents interrupt workflows and consume engineering time. The symptoms can look like an infrastructure failure even when the cause is application code.

Why async def can still block the event loop

This handler looks asynchronous:

@app.get("/some_endpoint")
async def work():
    do_blocking_work()  # For example, a synchronous database call
    return {"success": True}

But async def does not make the code inside it non-blocking. While this call runs on the event-loop thread, other tasks on that loop cannot progress. A health-check request handled by the same loop must wait too.

FastAPI runs ordinary def handlers in a thread pool. A synchronous helper called directly inside an async def handler does not get that treatment automatically. See the FastAPI concurrency documentation.

If a liveness probe fails enough consecutive times, Kubernetes can restart the container. A readiness failure instead marks the Pod unready, removing it from normal Service traffic. These signals have different purposes; neither identifies the root cause. See the Kubernetes probe documentation.

With several workers, the exact symptoms depend on which worker receives each request and how work is distributed. A blocked loop does not necessarily freeze every process, but it can still cause timeouts and failed probes.

From recent firefighting: large responses and JSON serialization

The investigation behind this note highlighted work that happens after the query: constructing and serializing the response can occupy the event loop too.

Consider this application-specific conversion helper:

items = [m.SomeDto.from_orm_model(r) for r in result]

Now consider a result with tens of thousands of records and roughly a hundred attributes per record. Even when the database has finished, the application still has to construct all those objects. This synchronous loop does not yield control just because its enclosing handler is asynchronous.

There is another step after object construction. An explicit serialization call also runs synchronously:

response.model_dump_json()

Called directly on the event-loop thread, large serialization work can delay other requests. If the framework generates the response, the execution path depends on the FastAPI version, response type, and configuration. Measure that path too; query duration alone does not explain total request latency.

Measure response construction and serialization as well as the database call. A completed query does not mean the request has finished its expensive work.

How payload logging can delay other requests

Logging an entire request or response can involve formatting a large object and writing it through a synchronous handler. A POST request with megabytes of JSON can turn a useful diagnostic log into substantial work on the request path.

Prefer request identifiers, payload sizes, record counts, durations, and selected fields. Check both formatting cost and the behavior of the logging destination. A queue can move log delivery elsewhere, but expensive formatting before enqueueing still happens in the caller.

How to diagnose FastAPI health-check timeouts

For a service with these symptoms, I would check four things:

  1. Connect failures to requests. Compare probe failures and restarts with request duration, payload size, record count, worker CPU, and event-loop lag.
  2. Time each stage. Separate database access, object conversion, response validation, serialization, and logging. Include work performed after the handler returns.
  3. Reproduce the actual volume. Test a representative large response while sending ordinary requests and health checks concurrently. Use a controlled environment.
  4. Change one cause and repeat. Check tail latency and probe behavior as well as the expensive request itself.

Increasing probe timeouts may reduce restarts during an investigation, but it does not restore the loop’s ability to serve requests while blocked.

How to fix event loop blocking for your workload

For blocking I/O, use a suitable asynchronous client or deliberately run synchronous work in a thread pool. A synchronous def handler can be appropriate when the handler relies on synchronous libraries.

Thread pools have finite capacity and can become another queue under load. Starlette documents the shared thread-pool limit. Moving CPU-heavy Python work into threads is also not a general solution for CPU parallelism; isolation in separate processes or workers may be needed.

For large responses, first ask why the consumer needs so much data at once. Pagination, fewer fields, or a separate export job may remove more work than optimizing serialization. Streaming helps only if the implementation produces bounded chunks without first building the entire result.

Then verify the whole response path again. Changing the handler declaration alone does not prove that all expensive work has moved off the event loop.

Get help investigating recurring timeouts

If your team keeps encountering these timeouts, I can review the request path, workload, and available evidence. We agree a focused scope, with a written assessment and prioritized next steps.

Discuss a focused performance review. A short description of the affected workflow, the symptoms, and what you have already tried is enough for the first conversation. You can also see how an audit works.

Start with a conversation

What’s slowing
your team down?

Let’s talk about your data challenges.

Book a free call

Calls and written deliverables are in English.