Skip to content

Readiness can be blocked by the very stall it reports (Crow io-thread head-of-line blocking) #120

Closed

Description

@jrosskopf

What

flAPI runs a request handler on the Crow io thread that owns its connection. A slow synchronous query therefore blocks every other connection that lands on that same thread, for as long as the query runs.

GET /health is one of those connections. So the readiness probe that exists to report a stall (#116, #119) can itself be blocked by that stall — the orchestrator sees a probe that never answers instead of the documented 503 {"status":"stalled"}.

Measured

With one ~5s query in flight, 40 sequential GET /health requests:

5.111349 200     <- blocked until the slow query finished
0.000386 200
0.000359 503     <- the other 39, correctly reporting the stall
0.000347 503
...

One probe in forty drew the blocked thread on a 32-core machine. The odds are roughly 1/threads, so on a 2–4 core CI runner it is 25–50% per probe, and a probe that draws it is stuck for the rest of the query.

This is what made test_readiness_fails_while_a_request_is_stalled fail on CI while passing locally. The test now works around it (several samplers, short probe timeout, retry on a new connection) and says why in a comment — but the workaround is in the test, not the product.

Why it matters

  • Kubernetes/Cloud Run readiness probes have timeouts. A probe that hangs is usually treated as a failure, so the outcome is often right by accident — but the mechanism is wrong, the response body never arrives, and nothing distinguishes "stalled" from "probe timed out".
  • It is not limited to /health. Any endpoint sharing an io thread with a slow query waits behind it, which is a throughput characteristic worth knowing and is currently undocumented.

Options

  1. Run query execution off the io threads (a handler thread pool, crow::response completed asynchronously). Correct, and the largest change.
  2. Serve /health and /health/live from a dedicated listener or reserved thread, so probes are never behind user traffic. Narrow, and fixes the probe specifically.
  3. Document it and leave it. Cheapest, but leaves the readiness contract only probabilistically true.

Discovered while fixing #116.

Activity

  1. jrosskopf commented on Sep 19, 2026

    @jrosskopf
    ContributorAuthor

    Prototype result: the offload works, and it crashes

    Prototyped async handler offload behind FLAPI_PROTO_OFFLOAD=1 — endpoint handling moved to a pool thread, completion posted back to the connection's own io_service (req.io_service, http_connection.h:146).

    It fixes the symptom completely. 2 server threads, one slow query in flight, 40 concurrent GET /health probes:

    blocked >0.5s answered 503 stalled worst
    offload off 40/40 0/40 5.17s
    offload on 0/40 40/40 7ms

    But it is memory-unsafe. Symbolised backtrace from the core dump:

    #0  Connection<...>::prepare_buffers()
    #1  Connection<...>::complete_request()
    #2  crow::response::end()
    #3  <the posted completion lambda in APIServer::setupRoutes>
    

    The posted completion dereferences a Connection that has already been destroyed.

    Crow keeps a connection alive across an incomplete response only through res.complete_request_handler_ holding shared_from_this — and that self-reference is private. A route handler has no public way to pin the connection across an async boundary in the Crow we pin (version.h says master).

    Ruled out: the 5s deadline timer. It is cancelled in handle_url() (http_connection.h:138), and a ~1.9s query — well inside the timeout — crashes too.

    Also still unsolved

    • RequestContextScope and the OTel active-span stack are both thread-local. Not rebound on the pool thread, so span parenting and audit correlation are wrong under the flag.
    • RequestContextScope::clear() in after_handle clears whichever request the io thread happens to be serving at that moment, not the one completing.

    Those are ordinary work. The lifetime problem is not — it needs a change in Crow itself (an overlay port exposing a connection guard), or a different server strategy.

    Where that leaves it

    The thread floor (#121) stands as the mitigation: 1 thread → 40/40 probes blind, 7 threads → 35/40 correct. Offload remains the right fix and is now known to work; it is blocked on pinning the connection, not on the concept.

    Prototype kept on proto/gh-120-async-offload (commit f3a66dd), not merged.

  2. jrosskopf commented on Sep 19, 2026

    @jrosskopf
    ContributorAuthor

    Correction to the comment above

    I wrote that "a route handler has no public way to pin the connection across an async boundary". That is wrong, and the mechanism is right there in http_connection.h:195-201:

    if (!res.completed_)
    {
        auto self = this->shared_from_this();
        res.complete_request_handler_ = [self] { self->complete_request(); };
        need_to_call_after_handlers_ = true;
        handler_->handle(req_, res, routing_handle_result_);
        ...
    }

    Crow does keep the Connection alive while a response is incomplete — the handler that completes it holds shared_from_this, and that survives the route handler returning. So the crash is not an unpinned connection, and forking Crow to add a guard would have been solving a problem that does not exist.

    What the cause looks like instead

    handle() (http_connection.h:133-146) resets per-request state on the connection, not per request object:

    ctx_ = detail::context<Middlewares...>();
    req_.middleware_context = static_cast<void*>(&ctx_);
    req_.io_service = &adaptor_.get_io_service();

    req_, res and ctx_ are all Connection members reused across requests on a keep-alive connection, and the read loop keeps running after the handler returns. An offloaded job holding &req/&res is therefore racing whatever the connection does next — a second pipelined request, or the read loop reaching EOF — and the posted res.end() lands on a response that has been reset underneath it.

    That is a state-reuse problem, not a lifetime one. It is plausible rather than proven: I have the crash site and the reused members, not yet a demonstration of the interleaving.

    Consequence for the fix

    Offload needs the response to be detached from the connection's reusable slot, not just the connection kept alive — which is a deeper change to Crow's model than adding a guard would have been. Worth knowing before anyone starts.

    Still true from the earlier comment: the measurement. Offload takes 2 server threads from 40/40 probes blind to 40/40 correct. The approach works; the integration with Crow's connection state is the open problem.

  3. jrosskopf commented on Sep 22, 2026

    @jrosskopf
    ContributorAuthor

    Investigation: the offload is viable, and my earlier explanation here was wrong

    I said the crash was Crow reusing req_/res/ctx_ per connection. That is not it, and the code says so explicitly (http_connection.h:517-522):

    else
    {
        // res will be completed later by user
        self->need_to_start_read_after_complete_ = true;
    }

    Crow supports deferred completion. While a response is incomplete it stops reading, precisely so no second request can land on that connection. So the per-request state is stable across an offload — the thing I claimed was the blocker.

    The actual mechanism

    prepare_buffers() (http_connection.h:288-291):

    void prepare_buffers()
    {
        res.complete_request_handler_ = nullptr;   // releases a [self] shared_ptr
        res.is_alive_helper_ = nullptr;            // releases the other one
        if (!adaptor_.is_open())                   // ...then dereferences `this`

    Those two lambdas hold the only strong references to the Connection once the read callback has returned. Nulling them destroys this, and every line after is a use-after-free — which is exactly where the prototype crashed.

    Synchronously this is safe: do_read's lambda still holds self on the stack for the whole handler chain. In an offload the read callback has already returned, so the posted completion is the last owner — and it owns nothing.

    So Crow supports deferred completion from a context that still holds a reference, and offers no public way to obtain one.

    Demonstrated

    I added three lines to the vendored Crow — a public std::shared_ptr<void> connection_keepalive on crow::response, set next to the existing complete_request_handler_ — and had the offloaded completion capture it. Same experiment that crashed reliably before:

    probes=40  blocked>0.5s=0  got-503-stalled=40   server still ALIVE
    

    40/40 probes answered, none blocked, all correctly reporting 503 stalled, no crash. Without offload the same setup gives 40/40 blocked and 0/40 correct.

    (Local experiment only — reverted. No production code changed.)

    What this means for the fix

    The blocker is not Crow's connection-state model. It is one missing public handle, which is a ~3-line addition carried in a vcpkg overlay port — the same mechanism already used for opentelemetry-cpp — not a fork of Crow's design.

    Still required before this could ship, and none of it is speculative:

    1. Rebind RequestContext (request_context.cpp:12 thread-local) and the OTel active-span stack on the pool thread, or inner-span parenting and audit correlation break.
    2. RequestContextScope::clear() in after_handle currently clears whichever request the io thread is serving at that moment.
    3. Backpressure and shutdown ordering for the pool (the prototype has neither).
    4. Upstreaming the Crow change, or accepting a patched dependency.

    That is a real piece of work, but it is ordinary work — which is a different answer from the one I gave before.

  4. added a commit that references this issue on Sep 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions