11 November 2026

The fix was correct, but the root-cause analysis was wrong

What an async Python incident investigation taught me about blocking SDKs, plausible explanations, and separating a real defect from the defect that caused production to fail.

One of the more uncomfortable outcomes in incident response is finding a real bug, fixing it correctly, and then discovering that it did not cause the incident.

That happened while investigating repeated liveness timeouts in a FastAPI service.

The full incident investigation follows the Kubernetes evidence. Here I want to look closely at the code fix we made along the way and why it did not explain the repeated pod replacements.

The API used a single Uvicorn worker. Two asynchronous request paths called synchronous third-party SDKs directly:

  • A synchronous embedding request during every retrieval-augmented generation query.
  • Synchronous Stripe requests during checkout and billing flows.

Those calls could block the event-loop thread. While blocked, the worker could delay other requests, including a dependency-free liveness endpoint.

That was a real production risk. It was also a persuasive explanation for the alert we were investigating.

We fixed it.

The alerts continued.

Why synchronous I/O blocks an async server

An asynchronous Python server depends on cooperative scheduling. A coroutine releases control when it reaches an operation that can be awaited. While one request waits for network I/O, the event loop can advance other requests.

Conceptually:

async def handler():
    result = await async_http_call()
    return result

The await does not make the external service faster. It allows the worker to do other useful work while waiting.

A synchronous SDK call behaves differently:

async def handler():
    result = synchronous_sdk_call()
    return result

If that SDK spends five seconds waiting for a remote API, the event-loop thread spends five seconds inside the function. Other coroutines assigned to the same worker cannot make progress during that time.

With one Uvicorn worker, other requests may have to wait:

request A enters synchronous SDK call
  -> event loop cannot advance request B
  -> /health/live may wait too
  -> a monitor may report a timeout

The embedding path

The RAG chain rewrote a user’s question and then requested an embedding:

query_embedding = self.embedder.embed_text(
    rewritten.rewritten_query,
)

The method looked like ordinary application code, but the implementation used a synchronous client to make an HTTPS request to the embedding provider.

The containing function was asynchronous. That did not make the SDK call asynchronous.

The fix moved the blocking function into a worker thread:

query_embedding = await asyncio.to_thread(
    self.embedder.embed_text,
    rewritten.rewritten_query,
)

asyncio.to_thread runs the callable outside the event-loop thread and returns an awaitable. The coroutine pauses while the SDK call runs, but the loop remains available to serve other work.

The change was required in both the streaming and non-streaming RAG paths.

The Stripe path

The billing service had the same structural problem across several operations:

  • Create customer.
  • Create tax rate.
  • Create checkout session.
  • Create customer portal session.

For example:

checkout_session = gateway.create_checkout_session(
    params=params,
    idempotency_key=checkout_idem_key,
)

became:

checkout_session = await asyncio.to_thread(
    gateway.create_checkout_session,
    params=params,
    idempotency_key=checkout_idem_key,
)

One checkout could involve several remote calls. A slow Stripe response or retry could delay other requests handled by the worker.

Why the explanation initially looked right

The production symptom was a timeout on:

/api/health/live

That endpoint did not query a database or external API. A timeout meant the process could not respond at all at that moment.

The service had one worker, and blocking calls existed on production request paths. Staging received little traffic. It was therefore reasonable to predict:

production traffic
  -> slow synchronous SDK call
  -> blocked event loop
  -> liveness timeout

This is where a code review can become dangerous during an incident. Once we found a defect that explained the symptom, the investigation began to feel complete.

The explanation had mechanism, environment specificity, and a concrete patch. It was not vague speculation.

It was still wrong about the repeated pod births.

The evidence that falsified it

The production log archive showed 192 boot markers over more than 21 hours, with a new boot approximately every six minutes, day and night.

There were no chat requests or billing requests during long sections of the timeline. The loop continued at the same cadence when the service was idle.

That created a contradiction:

Hypothesis:
  user traffic triggers a blocking SDK call

Observation:
  the same failure occurs for hours with no relevant traffic

A hypothesis that requires traffic cannot explain a traffic-independent metronome.

The later Kubernetes investigation found that the process was not crashing at all. KEDA scaled the deployment to zero after an idle cooldown, and ArgoCD self-heal restored the Helm replica count of one. Every cycle created a new pod with a restart count of zero.

The async defect could freeze a worker under load. It could not explain an idle controller loop.

Do not revert a correct fix because the RCA changed

Once the root cause changed, there was a temptation to treat the async patch as wasted work.

That would have been another mistake.

The code still had a concurrency defect with an understandable failure mode. The fix:

  • Kept synchronous network waits off the event-loop thread.
  • Allowed the event loop to keep handling other requests during those waits.
  • Preserved the existing synchronous SDKs without requiring a larger client migration.

The correct conclusion was:

This patch fixes a real defect.
This defect did not create the six-minute pod replacement loop.

Engineering reviews and incident reports need enough precision to hold both statements at once.

What asyncio.to_thread does not solve

Moving work into a thread prevents the event loop from being blocked. It does not make the underlying operation free or infinitely scalable.

Thread-pool saturation

Every offloaded call occupies a worker thread until the synchronous function returns. Under sustained load, slow embedding, Stripe, and authentication calls can exhaust the available thread capacity. New work then waits for a thread.

The server can still schedule coroutines, though requests may slow down if too many calls are waiting for threads.

Useful follow-up metrics include:

  • In-flight offloaded operations.
  • Time waiting for thread capacity.
  • Per-provider call duration.
  • Request latency and timeout rate.

Cancellation does not stop the function

Cancelling the awaiting coroutine does not necessarily terminate a synchronous function already running in a thread. The remote request may continue until its own timeout expires.

Third-party client timeouts therefore still matter.

The GIL still matters for CPU-bound work

asyncio.to_thread is a good fit for blocking I/O. It is not a general solution for CPU-heavy Python work. A CPU-bound model initialization or transformation may still contend for the Global Interpreter Lock, consume substantial memory, or belong in a process pool or separate service.

Database transactions can remain open

One Stripe customer call occurred while the service held a SELECT ... FOR UPDATE lock and an open database transaction.

Moving Stripe into a thread stopped it from blocking the event loop, but the transaction still held:

  • A row lock.
  • A pooled database connection.

If Stripe slowed down, concurrent operations for that user could remain serialized and enough checkouts could pressure the connection pool.

The stronger design is:

  1. Make the idempotent Stripe call outside the transaction.
  2. Open a short transaction.
  3. Re-read the customer ID.
  4. Write it only if another request has not already done so.

Lazy initialization can block the first request

The RAG chain was created lazily on the first chat request. Most provider constructors were lightweight, but one configuration could load a local sentence-transformers model.

That initialization belongs in application startup, where the service can fail fast and readiness can remain false until initialization completes. It should not surprise the first user request.

A better incident workflow

This investigation changed how I want to handle plausible defects found during an outage.

Label the claim

Keep these separate in notes and pull requests:

  • Confirmed observation.
  • Working hypothesis.
  • Verified contributing factor.
  • Root cause.
  • Corrective change.

Calling the async defect “the root cause” before correlating it with traffic made later notes harder to unwind.

Write the falsifier before the fix

For the traffic-driven hypothesis, a falsifier could have been:

If the same failures occur on a fixed cadence during periods with no chat or billing traffic, these blocking calls do not explain the loop.

Writing that sentence early would have directed the log query sooner.

Correlate across layers

Application code established that blocking was possible. Request logs established whether the relevant paths ran. Kubernetes established whether containers restarted or pods were replaced.

No single layer contained the full answer.

Verify the incident outcome separately

Tests proved that the patch preserved billing and RAG behavior. They did not prove that production stopped creating pods every six minutes.

Code verification and incident verification are different checklists.

Correctness is not causality

Finding a bug during an incident creates pressure to turn it into the story. The patch gives everyone something concrete to review and deploy. A complete explanation is emotionally satisfying.

But a bug’s ability to produce a symptom is not evidence that it produced this instance of the symptom.

The async patch was correct because synchronous network calls did not belong on the event-loop thread. The original RCA was wrong because the observed failure continued without those request paths ever running.

That is not a contradiction. It is the difference between code correctness and causal evidence.

Comments