← Back to Pull requests

Give tokio a turn while the KJ loop stays busy #8594

Closed
unknown closed this pull request without merging on Nov 30, 2026 17:07 UTC
View on GitHub
unknown unknown commented on Nov 18, 2026 06:11 UTC
Author

This PR makes sure tokio gets a turn even while KJ's event loop stays
busy. Today, a busy KJ queue can stop every Rust socket, timer, and
future on that thread. In cluster mode, that can stall the lease loop
long enough for a node to fence itself and leave the cluster.

Background

An event loop runs many small pieces of work on one thread, one at a
time. Event loops generally do not promise fair scheduling, but they
try not to let one always-ready source starve everything else. For
example, a fast TCP stream may always have more data when the previous
chunk finishes, repeatedly jumping ahead of other sockets and timers.

tokio gives each task a cooperative budget per scheduler tick: 128
operations according to the [introductory blog post][tokio-blog].
Operations on tokio resources such as sockets, timers, and channels
decrement that budget. When it runs out, those resources return
Pending even when ready, forcing the task back to the scheduler.
The details are in the [tokio coop documentation][tokio-coop].

libuv uses per-resource limits instead. It reads a ready stream at
most 32 times in one go, to "prevent loop starvation when the data
comes in as fast as (or faster than) we can read it"
([source][libuv-read]). Writes have the [same limit][libuv-write].

KJ, the Cap'n Proto event loop used by workerd isolates, has no
automatic budget. Promise::then() continuations are scheduled
depth-first, immediately after the current event and ahead of the rest
of the queue. KJ's [documentation][kj-scheduling] warns that this can
cause starvation and says long-running tasks must occasionally yield
with armBreadthFirst(); evalLater() and yield() are breadth-first.

A KJ socket read [tries read() right away][kj-read] and
[waits on the event port][kj-read-wait] only if it would block. KJ
checks that port for new I/O readiness, and in workerd for the tokio
runtime, only when its queue becomes empty. A WaitScope can call
[setBusyPollInterval(n)][kj-busy-poll] to poll every n turns
inside Promise::wait() ([loop][kj-busy-poll-loop]), but the
[default][kj-busy-poll-default] is kj::maxValue, meaning never, and
workerd on main does not change it.

The problem in workerd

On a KJ loop thread, workerd also runs a tokio runtime for Rust I/O:
kj-hyper HTTP, Rust sockets and timers, and the cluster lease loop.
The loops share the thread through KJ's event port, the kj-rs-tokio
TokioEventPort. tokio runs only when KJ calls the port, in its
wait() after the KJ queue becomes empty.

As long as KJ has queued work, tokio therefore gets no time at all.
This is total starvation of the second loop, not merely less-fair
scheduling. Every tokio socket, timer, and Rust future on that thread
waits through the entire busy stretch.

One concrete case is a cluster node opening many Durable Objects at
once. On a loaded machine this keeps KJ busy for seconds, while the
lease loop running on tokio stalls past the lease. The node then fences
itself and leaves the cluster. On main, the cluster 64-DO test lost its
lease in 53 of 500 runs.

setBusyPollInterval(n) limits the gap in turns, not elapsed time, and
individual turns can be long. A Durable Object start takes about 16 ms
in a fastbuild on a loaded executor, so 32 such turns can leave tokio
idle for over half a second. Even with n=32, the 64-DO test still
lost its lease in 2 to 4 of 100 runs.

What this PR does

Inside promise.wait(), KJ polls the port after every turn using
setBusyPollInterval(0). The port runs tokio from such a poll at most
every 20 ms, measured with the coarse monotonic clock. A busy turn
costs 94 ns instead of 74 ns. waitScope.poll() and promise.poll()
take no busy polls: they run tokio only once KJ's queue is empty, as
before.
After the turn that empties the queue, tokio gets a single yield
instead of a full pump before the following wait() parks it. A
return to idle therefore costs about 22 us of CPU instead of 19 us
in an opt build.
Every busy poll reports the cross-thread wake latch, so
kj::Executor work and cross-thread fulfillers reach the loop within
a turn.
A busy poll does not advance the KJ timer. A due timer fires once the
queue drains, as before, so a zero timer still runs after work queued
ahead of it. Events that tokio arms in a busy poll do run ahead of
the backlog, as with KJ's own busy polling of I/O.
The wait_timeout_ns(0) behavior for an already-due KJ timer is
unchanged.
New kj-rs-tokio tests verify that a tokio task sleeping during a busy
chain completes meanwhile, a cross-thread fulfill arrives within a
few turns, and a poll() on an empty queue runs tokio fully unless
turns were left queued, in which case it yields once.
This changes the event loop for every worker, not only cluster mode.
This is a time-based budget for the KJ side: every 20 ms, tokio gets
a turn. It is the same idea as tokio's coop budget and libuv's
32-read limit, applied between two loops rather than within one. It
does not make KJ itself fair among its own events; that is out of
scope.

Stacking

This PR is stacked on #8592 and #8593, which fix two bugs exposed while
testing this change: a kj-hyper body cut short by a failed pump could
be framed as complete, and bootstrapping a cluster peer session after
a failure aborted the node. Review only the last two commits here.

The first of those two commits fixes a third bug exposed by this
change. A dropped dynamic worker unlinked itself in a task on the next
turn. If the server was dropped first, it cleared that task without
running it, leaking both the worker and the factory. ASan caught this
in worker-loader-rab-test once tokio could drop the server between
busy turns.

The factory now retains a dropped stub's worker until it is unlinked,
and dropping the server unlinks any workers left. A new server-test
case fails 40 of 40 runs without the fix.

Results

The 64-DO test lost its lease in 53/500 runs without either change
(this PR and #8564), 1/500 with this change alone, and 0/500 with
both.
All cluster, kj-hyper, and kj-rs-tokio targets pass 40 runs on
bazelflare. The whole //src/workerd/api/... tree passed 1542/1542
tests in 10 runs each on main and here, and 1533/1533 in 5 runs
under ASan.

  • Under TSan, net-nodejs-test (testNetConnectionReset, reporting

  • "Network connection lost" instead of ECONNRESET) failed once in
    two of four API-tree runs on branches with this change and never on
    main. It failed 0 of 600 runs when run alone here and on main. It is
    unclear whether this change makes the failure more likely under
    load.

    | Kind | Lines | Where |
    | -------------- | ----: | --------------------------------------- |
    | Implementation | 118 | kj-rs-tokio event port |
    | Implementation | 31 | worker unlink fix: config.rs, loader.rs |
    | Tests | 144 | kj-rs-tokio Rust and C++ tests |
    | Tests | 57 | server-test |
    | Documentation | 2 | server AGENTS.md |

    [tokio-coop]: https://docs.rs/tokio/latest/tokio/task/coop/index.html
    [tokio-blog]: https://tokio.rs/blog/2020-04-preemption
    [libuv-read]: https://github.com/libuv/libuv/blob/v1.53.0/src/unix/stream.c#L1042-L1050
    [libuv-write]: https://github.com/libuv/libuv/blob/v1.53.0/src/unix/stream.c#L849-L853
    [kj-scheduling]: https://github.com/capnproto/capnproto/blob/be8fbe7bc7ad6c5cc8106385a1919df7222b1e5e/c++/src/kj/async.h#L1309-L1322
    [kj-read]: https://github.com/capnproto/capnproto/blob/be8fbe7bc7ad6c5cc8106385a1919df7222b1e5e/c++/src/kj/async-io-unix.c++#L564
    [kj-read-wait]: https://github.com/capnproto/capnproto/blob/be8fbe7bc7ad6c5cc8106385a1919df7222b1e5e/c++/src/kj/async-io-unix.c++#L711-L715
    [kj-busy-poll]: https://github.com/capnproto/capnproto/blob/be8fbe7bc7ad6c5cc8106385a1919df7222b1e5e/c++/src/kj/async.h#L1620-L1623
    [kj-busy-poll-default]: https://github.com/capnproto/capnproto/blob/be8fbe7bc7ad6c5cc8106385a1919df7222b1e5e/c++/src/kj/async.h#L1657
    [kj-busy-poll-loop]: https://github.com/capnproto/capnproto/blob/be8fbe7bc7ad6c5cc8106385a1919df7222b1e5e/c++/src/kj/async.c++#L2105-L2113

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: piscisaureus Review duration: 17935m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #8594"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%