Skip to content

I/O load shedding: rebalance sticky I/O across executors - #581

Merged
lalinsky merged 4 commits into
mainfrom
wake-spill
Jul 15, 2026
Merged

lalinsky merged 4 commits into
mainfrom
wake-spill

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 15, 2026 •

Copy link
Copy Markdown
Owner

Found while building the driver-based TCP benchmarks (separate C load generator, driver and server pinned to disjoint cores, so the runtime under test is only ever the server side).

I/O is sticky: a task's ops live on the ring of the executor it runs on — by preference on io_uring, by force on epoll/kqueue. Work stealing cannot rebalance I/O-bound tasks, because their wakes are always local and the wake-to-pop window is sub-microsecond: an idle executor gets searcher-woken tens of thousands of times a second and never catches anything. A multi-threaded TCP server ended up doing all of its work on one core (second executor at 0.0% CPU), byte-for-byte identical to single-threaded on the streaming benchmark.

Go avoids this problem structurally — one shared netpoller means readiness is global and balance is free (at the price of a central funnel, which is why zio beats go on 1000-connection echo). With per-executor rings we need an explicit balancer:

  • Round-robin homes for new tasks (reverts spawn-onto-current-executor): initial spread is the only placement decision that exists on epoll/kqueue backends, and spawning everything onto the acceptor's executor concentrated whole servers onto one core.
  • Decentralized load shedding: once per tick (~100us) each executor compares its in-flight I/O count (== tasks parked on its ring) against the runtime average; if above, it sheds the excess by routing up to 4 wakes to the global queue. Less loaded executors pull from it, and a shed task's I/O re-homes wherever it runs next, so one shed rebalances a connection permanently. No central coordinator, no idle-mask races; the cap keeps the global queue a rebalancing channel rather than a scheduling path.

Benchmarks

Driver/server split, i7-6700 (2 driver cores, 2 server cores), 8 connections, 64KB chunks, ReleaseFast:

server workload before after go tokio
stream write, 8 conns 3.5 GB/s 7.3 GB/s 7.1 7.4
stream write, 1 conn 2.7 GB/s 3.3 GB/s 3.8 3.6
stream read, 8 conns 5.0 GB/s 7.7 GB/s 7.5 7.7
echo 1000 conns 146k msgs/s 166k msgs/s 108k 150k
echo 1 conn 4KB 25.1k msgs/s 25.7k msgs/s 23.4k 24.7k

In-process benchmarks (channel ping-pong, worker pool fan-out/fan-in, spawn) unchanged within noise — non-I/O workloads keep inflight counts below the shedding threshold, so the balancer never engages there.

Follow-up commit: the first wake pushed onto an empty ring from scheduler context no longer arms a searcher — the executor is in its run loop and pops it immediately, so the announcement only caused an idle executor to occasionally win the race and drag the connection to another ring. That fixed single-connection streaming on mt (2.7 -> 3.3 GB/s, now matching st) and, as a bonus, removed enough wakeup churn to lift 1000-connection echo from 147k to 166k msgs/s.

A task woken by an I/O completion always landed on the executor that
owns the ring its op completed on, and long-lived connection tasks
never leave: the steal window between the wake and the local pop is
sub-microsecond, so an idle executor gets searcher-woken tens of
thousands of times a second and finds nothing every time. A
multi-threaded TCP server ends up doing all its work on one core (with
the other executors burning cycles on futile steal attempts).

Now a wake that arrives while the executor already has queued work and
another executor sits idle goes to the global queue instead of the
local ring. One spill rebalances a connection permanently, because its
next ops are submitted from wherever it runs.

Measured with the new driver-based TCP benchmarks (2 driver cores, 2
server cores, 8 connections, 64KB chunks): server write throughput
3.5 -> 7.8 GB/s (was identical to single-threaded before, now ~2x and
ahead of go's 7.4), server read 5.1 -> 7.1 GB/s. Ping-pong, worker
pool and echo benchmarks unchanged — the spill only triggers on a
non-empty ring, which a latency chain never has.
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Executors atomically track cross-thread I/O load, compute bounded per-tick shedding quotas, and route selected wakes through overflow queues. Spawn notifications refill local rings, while new tasks use deterministic executor selection and completion callbacks can be explicitly deferred.

Changes

Load-aware scheduling

Layer / File(s) Summary
Atomic I/O load tracking
src/ev/loop.zig
inflight_io updates and reads use monotonic atomic operations in single-threaded paths, with documentation covering cross-thread scheduler reads.
Queue signaling and refill contracts
src/utils/local_run_queue.zig
LocalRunQueue.push returns whether the ring was previously empty, refillFrom drains a specified overflow queue, and tests discard unused return values.
Per-tick shedding and queue routing
src/runtime.zig
Executors recompute bounded shedding quotas, route selected wakes to overflow, refill pending work, conditionally arm the searcher, and discard stolen-node push results.
Spawn notification and migration routing
src/runtime.zig, src/task.zig
Spawned tasks notify an async drain path that refills local work; migration routing distinguishes new tasks from already-running tasks, and spawnTask selects a deterministic home executor.
Completion callback deferral
src/ev/completion.zig, src/ev/loop.zig
Completions can request deferred callbacks, and finalization honors either completion-specific or loop-wide deferral.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

Poem

Loads are counted, quotas spun,
Overflow carries work to run.
Spawned tasks choose their proper lane,
Async bells refill the ring again,
Deferred callbacks wait their turn.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches the main change: rebalance sticky I/O across executors via load shedding.
Description check ✅ Passed The description directly describes the scheduler and load-shedding changes in the PR.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch wake-spill

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/runtime.zig (1)

743-754: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Lift the common searcher arming out of the branches.

The spillover condition safely handles the backlog without risking starvation. Since both paths conclude by calling armSearcher(), you can drop the early return and use a standard if/else block to remove the duplicated call.

♻️ Proposed refactor
-        if (!self.run_queue.isEmpty() and self.runtime.stealingActive() and self.runtime.idle_mask.load(.monotonic) != 0) {
-            self.run_queue.overflow.push(&task.awaitable.wait_node);
-            self.runtime.armSearcher();
-            return;
-        }
-
-        self.run_queue.push(&task.awaitable.wait_node);
-        self.runtime.armSearcher();
+        if (!self.run_queue.isEmpty() and self.runtime.stealingActive() and self.runtime.idle_mask.load(.monotonic) != 0) {
+            self.run_queue.overflow.push(&task.awaitable.wait_node);
+        } else {
+            self.run_queue.push(&task.awaitable.wait_node);
+        }
+        self.runtime.armSearcher();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime.zig` around lines 743 - 754, Refactor the spillover branch in the
task wake/enqueue flow to remove its early return and shared armSearcher() call.
Keep the spill condition and overflow push unchanged, use an if/else structure
for the spill versus normal enqueue paths, then call self.runtime.armSearcher()
once after both branches.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/runtime.zig`:
- Around line 743-754: Refactor the spillover branch in the task wake/enqueue
flow to remove its early return and shared armSearcher() call. Keep the spill
condition and overflow push unchanged, use an if/else structure for the spill
versus normal enqueue paths, then call self.runtime.armSearcher() once after
both branches.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d4e8ae80-8a2e-4b98-80d1-527e8d6d8b94

📥 Commits

Reviewing files that changed from the base of the PR and between af1943b and 5569fa4.

📒 Files selected for processing (1)
  • src/runtime.zig

lalinsky added 2 commits July 15, 2026 19:08
Reverts the spawn-onto-current-executor placement. Initial spread
matters more than the saved global-queue push: on epoll and kqueue
backends a socket is pinned to the loop that registers it, so the
executor a task starts on decides where its I/O lives, permanently.
Spawning everything onto the acceptor's executor concentrated whole
servers onto one core.
The first version spilled a wake whenever the ring was non-empty and
someone was idle — correct on the benchmark, but a wake burst under
light load would route everything through the global queue.

Now it's an actual load balancer, decentralized: once per tick each
executor compares its in-flight I/O count (== tasks parked on its ring)
against the runtime average, and if it is above, sheds the excess by
routing up to four wakes to the global queue. Less loaded executors
pull from it, the shed task's I/O re-homes wherever it runs next, and
the metric converges in a few ticks. Work stealing cannot do this job:
I/O wakes are always local and the wake-to-pop window is far too small
for a thief, which is why a multi-threaded server used to sit on one
core no matter how many executors it had.

The per-loop inflight counter is now read cross-thread (monotonic
atomics; the owner remains the only writer).
@lalinsky lalinsky changed the title Spill I/O wakes to the global queue when the executor is backlogged I/O load shedding: rebalance sticky I/O across executors Jul 15, 2026
When an I/O completion wakes a task onto an empty ring, this executor
is inside its run loop and pops the task right after completion
processing — no thief can beat that. Announcing it just wakes an idle
executor for nothing, and when the thief does win the race it drags
the task (and with it the connection's I/O home) to another ring for
no benefit; a lone streaming connection lost ~20% of its throughput to
that bouncing. Wakes from a running task still announce, since the
waker may keep the executor busy for a while.

push() now reports whether the ring was empty instead of the caller
peeking beforehand.

Single-connection streaming on the multi-threaded runtime now matches
single-threaded (3.3 GB/s, was 2.7), and 1000-connection echo improves
147k -> 166k msgs/s from the removed wakeup churn alone.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/utils/local_run_queue.zig (1)

297-297: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assert the was_empty return value in tests.

Since push now returns a boolean indicating whether the queue was empty, it's worth actually testing this behavior in the basic test instead of just discarding it.

♻️ Proposed refactor
     for (&nodes, 0..) |*n, i| {
         n.* = .{ .id = i };
-        _ = q.push(n);
+        const was_empty = q.push(n);
+        try testing.expectEqual(i == 0, was_empty);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/local_run_queue.zig` at line 297, Update the basic queue test
around q.push(n) to capture and assert the returned was_empty boolean, verifying
the expected value for the queue’s initial state instead of discarding it.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/utils/local_run_queue.zig`:
- Line 297: Update the basic queue test around q.push(n) to capture and assert
the returned was_empty boolean, verifying the expected value for the queue’s
initial state instead of discarding it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 96771383-9782-4ec4-8edd-a1a34f9d1a27

📥 Commits

Reviewing files that changed from the base of the PR and between f4b05c5 and 55ccd91.

📒 Files selected for processing (2)
  • src/runtime.zig
  • src/utils/local_run_queue.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/runtime.zig

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/utils/local_run_queue.zig`:
- Around line 251-266: Update OverflowQueue.refillFrom to size its local pointer
buffer to capacity instead of the hardcoded 64 entries, allowing the existing
want calculation to honor max up to the queue capacity and drain the requested
batch in one call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 34b264ed-5d1f-483d-ab02-c963d189c746

📥 Commits

Reviewing files that changed from the base of the PR and between 55ccd91 and 4b482d2.

📒 Files selected for processing (3)
  • src/runtime.zig
  • src/task.zig
  • src/utils/local_run_queue.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/task.zig

Comment thread src/utils/local_run_queue.zig Outdated
Comment on lines 251 to 266
pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize {
const t = self.ownTail();
const h = self.loadHead();
const space: usize = capacity - (t -% h);
var buf: [64]*T = undefined;
const want = @min(space, @min(max, buf.len));
if (want == 0) return;
const got = self.overflow.popBatch(buf[0..want]);
if (want == 0) return 0;
const got = source.popBatch(buf[0..want]);
var tt = t;
for (buf[0..got]) |node| {
self.buffer[tt & mask] = node;
tt +%= 1;
}
if (got > 0) self.storeTail(tt);
return got;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix the arbitrary batch size limit to honor max.

Notice how buf is hardcoded to 64 pointers? spawnDrainCallback passes capacity (256) as the max argument, but this hardcoded array size forces the queue to only pull 64 tasks at a time. The rest get left in the overflow queue, triggering spawn_async.notify() and forcing an entirely new event loop tick just to pick up the next batch of 64.

You can fix this by just bumping the buffer size to capacity. Since T is a pointer, [capacity]*T is only 2KB. This easily fits on the executor's OS thread stack, avoids wasting event loop ticks, and completes the pull with a single lock acquisition.

🚀 Proposed fix to allocate a capacity-sized buffer
         pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize {
             const t = self.ownTail();
             const h = self.loadHead();
             const space: usize = capacity - (t -% h);
-            var buf: [64]*T = undefined;
-            const want = `@min`(space, `@min`(max, buf.len));
+            var buf: [capacity]*T = undefined;
+            const want = `@min`(space, max);
             if (want == 0) return 0;
-            const got = source.popBatch(buf[0..want]);
+            const got = source.popBatch(buf[0..want]);
             var tt = t;
             for (buf[0..got]) |node| {
                 self.buffer[tt & mask] = node;

(Alternatively, if you're feeling exceptionally strict about keeping the stack frame tiny, wrap the existing 64-item popBatch in a while (total_got < limit) loop until you hit max.)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize {
const t = self.ownTail();
const h = self.loadHead();
const space: usize = capacity - (t -% h);
var buf: [64]*T = undefined;
const want = @min(space, @min(max, buf.len));
if (want == 0) return;
const got = self.overflow.popBatch(buf[0..want]);
if (want == 0) return 0;
const got = source.popBatch(buf[0..want]);
var tt = t;
for (buf[0..got]) |node| {
self.buffer[tt & mask] = node;
tt +%= 1;
}
if (got > 0) self.storeTail(tt);
return got;
}
pub fn refillFrom(self: *Self, source: *OverflowQueue(T), max: usize) usize {
const t = self.ownTail();
const h = self.loadHead();
const space: usize = capacity - (t -% h);
var buf: [capacity]*T = undefined;
const want = `@min`(space, max);
if (want == 0) return 0;
const got = source.popBatch(buf[0..want]);
var tt = t;
for (buf[0..got]) |node| {
self.buffer[tt & mask] = node;
tt +%= 1;
}
if (got > 0) self.storeTail(tt);
return got;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/local_run_queue.zig` around lines 251 - 266, Update
OverflowQueue.refillFrom to size its local pointer buffer to capacity instead of
the hardcoded 64 entries, allowing the existing want calculation to honor max up
to the queue capacity and drain the requested batch in one call.

@lalinsky

Copy link
Copy Markdown
Owner Author

Reverted the per-executor spawn queue commits (4b482d2, 6a1228b) from this PR — CI still hangs on 2-core runners despite the deferral fixes, and it shouldn't block the load-shedding work. The spawn queue idea and everything learned (callback re-add recursion, defer_callback design, the two stranding bugs) moved to #582; WIP preserved on spawn-queue-wip.

@lalinsky
lalinsky merged commit f525fef into main Jul 15, 2026
53 checks passed
@lalinsky
lalinsky deleted the wake-spill branch July 15, 2026 19:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant