- Zig 100%
poolio #
Worker pools for Zig 0.17 std.Io: bounded queues, Io.Group.concurrent workers, backpressure with put, and best-effort shedding with offer.
const std = @import("std");
const poolio = @import("poolio");
const Io = std.Io;
const Ctx = struct {
fn process(_: *@This(), _: Io, item: u64) Io.Cancelable!void {
std.debug.print("work: {d}\n", .{item});
}
};
pub fn main(init: std.process.Init) !void {
const io = init.io;
var ctx: Ctx = .{};
var pool = try poolio.Pool(u64, Ctx).init(init.gpa, .{
.queue_capacity = 1024,
.workers = 4,
.ctx = &ctx,
.process = Ctx.process,
.shedding = .drop_oldest,
});
defer pool.deinit(io);
try pool.start(io);
try pool.put(io, 1); // backpressure
_ = pool.offer(io, 2); // never waits for queue capacity
try pool.shutdown(io);
}
Local source consumers include typeahead and coral. They currently pin older versions; these API changes have not been rolled out to them.
Context #
poolio is a bounded worker pool, in the same broad family as channel-backed worker patterns in Go and Rust. It is not an actor runtime: it does not provide process identity, routing, supervision, or restart policy. The Zig part is explicit ownership and lifetime: callers choose the allocator, Io, item type, processing callback, and optional drop callback.
Io requirement #
Workers are started with std.Io.Group.concurrent, so start requires an Io implementation that can provide correctness-relevant concurrency and may return error.ConcurrencyUnavailable. Use std.Io.Threaded or another Io implementation that supports concurrent; poolio uses std.Io synchronization primitives and does not spawn std.Threads directly.
put and worker dequeue operations check cancellation even when the queue is ready. offer never waits for capacity, but it can wait for the queue mutex and runs the drop callback synchronously. It is neither lock-free nor a bounded-latency call.
Use the same Io backend instance for all operations and callback I/O. Poolio cannot make blocking foreign calls or CPU-heavy callbacks cooperative; an evented backend does not turn workers into CPU threads.
Lifetime and ownership #
Keep the pool at a stable address once operations begin. The context and Io must outlive all workers and drop callbacks. Lifecycle calls (start, shutdown, cancel, deinit) must be serialized and called outside the pool's own callbacks. Producers and counter readers may overlap shutdown/cancel, but must be joined before deinit or freeing the context. Submission and counter methods support concurrent callers.
- A successful
puttransfers the item to the pool. OnClosedorCanceled, the caller still owns it. offeralways takes ownership, even when it returnsfalse. Rejected, evicted, and abandoned queued items go toon_drop. Resource-owning items require a drop callback.- Once
processis called, it owns that item and must release it on every return path, including cancellation. Poolio never callson_dropfor a started item. processreturnsIo.Cancelable!void. Propagate cancellation withtry; handle application errors inside the callback. A canceled callback exits its worker.- Drop callbacks run outside the queue lock, may run concurrently, and must complete cleanup without failing. They may inspect counters but must not invoke lifecycle methods.
Stopping #
shutdown(io) closes admission, drains with existing workers, and joins them. It propagates parent cancellation after joining workers and dropping queued leftovers. Callers must propagate that error; a canceled shutdown does not promise a complete drain. Before start, shutdown drops prequeued items because there are no workers.
cancel(io) closes admission, prevents further dequeue, requests worker cancellation, joins, and drops queued leftovers. A callback already dequeued may still start; it owns its item and receives pending cancellation at its next cancellation point. Cancellation is cooperative and has no fixed deadline. Even if a callback consumes cancellation, the aborted queue prevents it from taking another item.
deinit(io) performs cancel-and-join before releasing the queue allocation. Prefer defer pool.deinit(io) immediately after initialization; call try pool.shutdown(io) explicitly when graceful draining is wanted. shutdown and cancel are repeatable; deinit is not.
Starting requires at least one worker (NoWorkers). A second start returns AlreadyStarted. A stopped pool cannot restart (Closed). If worker creation fails partway, all started workers are joined, queued items are dropped, and the pool becomes permanently closed. start failure is not transactional: workers may already have processed prequeued items.
Counters #
accepted counts admitted submissions; dropped counts rejected, evicted, or abandoned items; processed counts callbacks that returned successfully; canceled counts callbacks that returned Canceled. A successful callback need not mean business-level success. queued excludes in-flight callbacks. Snapshots taken during concurrent activity are approximate, not a coherent accounting transaction.
Validation and performance #
Run zig build test and zig build bench -Doptimize=ReleaseFast. The benchmark uses two warmups and five measured passes, verifies item accounting, and reports submissions and completions separately. High submission throughput with high shedding is not high work throughput.
Workshop review, 2026-10-08 #
The SYCL workshop principles behind this change are correctness-relevant concurrency (concurrent, never an inline async fallback for resident workers), cancellation propagation, blocking cancellation/join, stable task lifetimes, and backend-compatible synchronization. Poolio already used Io.Mutex and Io.Condition; those remain. A test with async_limit = 0, a capacity-three queue, four producers, and two workers verifies every item is processed exactly once without relying on spare async workers.
Zig 0.17.0 on aarch64 macOS, ReleaseFast, 200,000 tiny jobs per pass:
| Variant | Original submissions/s | Correctness changes, before alignment | Final submissions/s | Final completions/s |
|---|---|---|---|---|
| put, 1 worker | 7.67M | 3.21M | 6.43M | 6.43M |
| put, 4 workers | 6.28M | 5.15M | 6.09M | 6.09M |
| offer, drop newest | 7.43M | 2.71M | 6.23M | 6.21M |
| offer, drop oldest | 6.43M | 2.72M | 6.19M | 6.18M |
These are aggregate rates across five measured passes, after two warmups. Separating producer and worker counters onto cache-line boundaries recovered much of the throughput loss; two earlier aligned runs measured 6.33–6.36M/s for one-worker put and 5.87–5.92M/s for four-worker put. The final implementation remains about 16% slower than the original for one-worker put and 3% slower for four-worker put. Correctness has a cost here; this is not an overall submission-throughput speedup. Alignment increases each pool's memory footprint.
The original offer runs dropped approximately 69% and 56% of submissions, respectively; final runs dropped below 1%. Those submission rates are not equal-work comparisons. The retained benchmark reports actual completions and validates counts and payload sums. Replacing ring-buffer modulo operations with branches did not improve the tested put throughput and was discarded. No batching, ordering changes, or cancellation-check removal was retained.
Threaded tests cover active and pending cancellation, repeated stop calls, callback and queued-item cleanup, start failure, arbitrary ring capacities, and contended producers. The built-in evented backend is blocked in the installed compiler: std.Io.Dispatch.io() references processReplacePath, absent from that version's Io.VTable. ZIO validation is recorded separately below.
ZIO validation, 2026-10-08 #
The alpha's unchanged library source passes a separate integration suite against lalinsky/zio pinned to bba6715195a92a29b4659cea15912fb4ced28485. ZIO is a dependency of the integration project only; Poolio's library package still has no runtime dependencies. The Git URL avoids a nested-root archive-cache failure observed with this installed Zig compiler's tarball fetch path.
From a repository checkout:
zig build test
cd tests/zio
zig build test
zig build test -Doptimize=ReleaseSafe
zig build bench -Doptimize=ReleaseFast
All 22 Threaded unit tests and nine ZIO integration tests pass in Debug and ReleaseSafe. Each integration test runs with one and four executors. Coverage includes four producers draining exactly once through a capacity-three queue, yielding callbacks, active and swallowed cancellation, canceled shutdown, deinit ownership, canceled blocked submissions, close waking a producer, both shedding policies, repeated idle-worker cancellation, and real loopback TCP reads that complete or cancel before socket close. No Poolio runtime changes were needed to pass these tests.
The same benchmark runner and pool allocator are used across Threaded and ZIO. On an Apple M5 Pro (18 logical CPUs), aarch64 macOS, Zig 0.17.0, ReleaseFast, two complete invocations produced these completed-job rates. Each invocation uses two warmups and five measured passes per variant; ranges below span the two aggregate rates, not confidence intervals.
| Workload | Threaded | ZIO, 1 executor | ZIO, 4 executors |
|---|---|---|---|
| put/1w | 6.02–6.04M/s | 66.98–67.63M/s | 66.85–66.98M/s |
| put/4w | 5.74–6.12M/s | 66.14–66.71M/s | 9.22–9.26M/s |
| put/4p4w | 6.35–7.19M/s | 66.62–66.96M/s | 5.12–5.24M/s |
| timer/1w | 6.31–6.41K/s | 6.93–7.02K/s | 7.49–7.54K/s |
| timer/4w | 24.87–25.37K/s | 27.85–28.12K/s | 30.36–30.36K/s |
put/4p4w means four producers and four workers; the other variants have one producer. Tiny-job variants submit 200,000 items with queue capacity 1024. Timer variants submit 512 items, queue capacity 16, and await a 100µs timer in each callback; they test scheduler overlap, not network or disk throughput. These expanded-workload results are not a controlled before/after comparison with the earlier alpha benchmark.
The single-executor tight offer loop drops 99.488% of submissions: with no capacity wait or callback into the scheduler, the producer runs its entire burst before workers drain the last 1024 items. Its approximately 150M submissions/s is mostly rejection/eviction, not processing. On a cooperative backend, callers must use put for backpressure or provide scheduling opportunities in the producer's own I/O/batching policy. Poolio does not insert implicit yields into offer.
One executor avoids cross-thread coordination for these tiny jobs. Four executors improve the timer case, but the contended four-producer/four-worker case is slower than Threaded. More executors are not a universal optimization. CPU-heavy callbacks still need an appropriate execution strategy; a worker count is not a promise of CPU parallelism.
Raw results retain counts, shedding, and per-pass min/median/max. This table describes the tested macOS configuration; Linux validation follows below. It does not establish performance for arbitrary ZIO commits or downstream services. The alpha tag is unchanged; downstream adoption remains a separate step.
Linux ZIO validation #
The same nine integration tests pass in ReleaseSafe on aarch64 Linux (Ubuntu 24.04 container, OrbStack kernel 7.0.14-orbstack-00380-ga7e0a2dc9535), with one and four executors:
| ZIO backend | Container syscall policy | Result |
|---|---|---|
epoll |
Docker default | 9/9 pass |
linux (automatic selection) |
Docker default, io_uring denied | 9/9 pass through epoll fallback |
io_uring |
seccomp restriction lifted for isolated test container | 9/9 pass |
Explicit io_uring initialization returns PermissionDenied under the Docker default policy. The same binary passes when io_uring is permitted. ZIO's automatic Linux backend handles that restriction; it is preferable to requiring explicit io_uring in a restricted deployment. This is an environment requirement, not a Poolio API change.
The test project accepts -Dbackend=linux|epoll|io_uring|kqueue|poll. test-build and bench-build install binaries without executing them, allowing the exact code to run on another host. For example, from tests/zio on the development Mac:
zig build test-build -Dtarget=aarch64-linux-gnu -Doptimize=ReleaseSafe -Dbackend=epoll
docker run --rm --network none -v "$PWD/zig-out/bin:/tests:ro" ubuntu:24.04 timeout 20 /tests/test
For the explicit io_uring test, build with -Dbackend=io_uring and add --read-only --cap-drop ALL --security-opt no-new-privileges --security-opt seccomp=unconfined to that disposable container invocation. These flags describe the test environment, not a recommendation to relax a service's production policy.
Linux benchmarks use ReleaseSafe and the same seven workloads. Their raw results are in linux-results.txt. Timer wakeups in this VM can be far slower than the requested 100µs on both Threaded and ZIO; do not compare those rates directly with native macOS ReleaseFast results or treat them as socket latency. Counts and payload sums are checked on every benchmark pass.
The ZIO validation scope is complete for this pinned version on macOS and aarch64 Linux: pool ownership, cancellation, queue progress, actual TCP readiness, and measured throughput tradeoffs. No runtime changes or new alpha are required. Windows, x86 Linux, and downstream application load tests are outside this pass.
Release compatibility #
0.1.0-alpha.1 is a breaking prerelease for Zig 0.17.0, tagged v0.1.0-alpha.1. The migration from 0.0.1-alpha.2 is described below.
| Change | Migration or semantic impact |
|---|---|
ProcessFn returns Io.Cancelable!void |
Update callback signatures and propagate cancellation; old void function pointers do not coerce. |
shutdown returns Io.Cancelable!void |
Use try or explicitly handle cancellation. |
deinit(io) cancels and joins |
Supply the same live Io; cleanup can block while callbacks finish. |
cancel stops dequeueing |
Pending work is dropped rather than incidentally drained. |
Failed start permanently closes the pool |
Reinitialize rather than retry; queued items are dropped. |
start reports NoWorkers, AlreadyStarted, Closed |
Zero workers may be used before start for queue operations, but cannot start a pool. |
canceled counter; changed processed meaning |
Canceled callbacks are no longer counted as processed; update explicit counter construction. |
Ready put checks cancellation |
It may now return Canceled without waiting for capacity; the caller keeps ownership. |
Downstream source, dependency pins, and deployed services are outside this change.