Async Rust in a query engine: lessons learned
Why Krishiv runs compute on Tokio, the experiment that decided it, and the rules that keep a CPU-bound engine from stalling its own async runtime.
- Krishiv 0.2
- Tokio
- Cooperative yielding
- // Features
- // Query engine
- # Krishiv
// contents
Summary. A query engine is mostly CPU work, which is the opposite of what async runtimes are built for. I still run Krishiv's compute on Tokio, because an experiment I wrote the pass rule for in advance did not justify a dedicated thread pool. The price is discipline: every operator loop yields after each batch, CPU work that cannot yield goes to a bounded blocking pool, object-store I/O lives on its own runtime, and a stall detector plus a few clippy bans turn "do not block a worker" from advice into a failing build. This post is the decision, the numbers, and the rules, including the ones I learned the hard way.
Key facts
| Item | Value |
|---|---|
| Decision | Tokio multi-thread runtime for compute, cooperative yielding in operators (ADR 0006 update, experiment E01) |
| Rejected option | A dedicated work-stealing compute pool with Tokio only for I/O |
| Pass rule (written before the runs) | Choose the pool only if short-query p99 improves by more than 20% and heavy throughput stays within 5% |
| Result | p99 improved 3.7% and throughput 2.0%, so the simpler option won |
| Stall threshold | 10 ms by default: a poll longer than that without yielding is counted, and fails tests and CI |
| Status | The decision is marked provisional, with a tripwire to re-check on a quiet machine with 16 or more cores |
Why use an async runtime for CPU-bound work at all?
The textbook answer is that you should not. A hash join does not wait on anything; it burns a core. A dedicated pool of threads pulling morsels off a work-stealing queue is the shape DuckDB and HyPer use, and my first proposal in the design was exactly that, with Tokio only for I/O.
What pulled me the other way was everything around the CPU work. A scan awaits object-store reads. Cancellation, spill requests and memory-pressure signals need to reach a running pipeline. Query results flow through bounded channels with backpressure. All of that is naturally expressed as futures, and a second scheduler next to Tokio means two ways to wait, two ways to cancel and two sets of bugs at the seam. So I wrote the question down as an experiment instead of deciding by taste.
How did I decide, and what did the experiment show?
Experiment E01 compared option A, Tokio for everything, with option B, a dedicated pool plus Tokio for I/O. The workload was one heavy TPC-H-derived query (scale factor 10, q9) running alongside an open-loop stream of short q6 queries at scale factor 1, with 6 threads, mimalloc and 4,096-row batches. The rule was fixed before the runs: pick B only if short-query p99 improves by more than 20% with heavy throughput within 5%.
The interleaved result: heavy throughput was 808.7 queries per hour for A and 824.6 for B, so B was 2.0% higher. Short-query p99 was 660 ms for A and 636 ms for B, a 3.7% improvement. Median short-query latency was actually worse for B, 342 ms against 297 ms. The throughput criterion was met and the p99 criterion was not by a wide margin, so A won, the simpler option.
The part I am most glad I wrote down is how nearly I got the opposite answer. My first protocol ran each option as its own process, one after the other. Pooled over those runs, B looked 27% better on both p99 and throughput, which would have chosen the pool. But the per-round baselines flipped direction between runs: one pair read A 4.05 s against B 3.41 s, the next A 2.65 s against B 3.40 s. That tracked load and thermal state on a shared laptop, not the scheduler. Switching to in-process interleaving, with the options alternating inside one run, made the effect vanish. I come back to that protocol in the post on benchmarking.
The review recorded the caveats. It was a shared, throttling laptop with six physical cores, round-to-round p99 varied by about 10%, and B ran without priorities. So the decision is provisional, with a tripwire: re-run on a quiet host with 16 or more cores, with several heavy queries and object-store I/O, and switch only if the pool clears the original rule. I do not have a quiet 16-core result to quote, so this post does not claim one.
What is the rule that makes Tokio safe here?
Tokio schedules cooperatively. A future that never returns to the runtime holds its worker thread, and every other task on that thread waits. In a query engine that is easy to do by accident: a loop over a large batch is just a loop.
The rules from the decision, as the code now stands:
- Every pipeline driver yields after each batch. The driver processes a batch, pushes it downstream and calls
tokio::task::yield_now()before the next one. With 4,096-row batches that is a yield roughly every millisecond or less. - CPU work over about a millisecond that cannot yield goes to the blocking pool. The
Executortrait documentsspawn_blockingas the only place for it, and operators reach it throughTaskContext::run_blocking. The pool is bounded by a semaphore, not left at Tokio's default. - Never block a worker. No
block_on, nothread::sleep, no synchronous file I/O on a compute thread. - Object-store and network I/O runs on a separate, small I/O runtime. A scan awaits its reads there.
Rule 3 is the one people break, so it is enforced by the toolchain. The crate that holds the operators denies Handle::block_on, Runtime::block_on, std::thread::sleep and the synchronous std::fs calls through clippy.toml, and a source-guard task scans for the same names textually. The error message tells you where to go instead: await on the I/O runtime, or use run_blocking.
How do I find the stall I did not know I wrote?
By measuring every poll. Each driver is wrapped in a future that times each call to poll. A poll longer than the stall threshold, 10 ms by default, increments a counter that is visible in query metrics and the query profile. In tests and CI there is a fail-on-stall mode that turns the same event into a query error saying how long the driver ran without yielding.
Making that detector trustworthy was a lesson of its own. Counting plain wall time failed queries on loaded machines, because a thread that was runnable but kept off a core looked like a stall. The fail-on-stall mode now subtracts the time a thread waited on a run queue and the time its cgroup was throttled by a CPU quota, both read from the kernel. It also excuses a bounded amount per major page fault, since a thread blocked paging code in from disk is the disk's time, not the driver's. A sleep or blocking read inside a poll still counts in full, which is the point. The detector is a tool for finding my bugs, so it has to tell my bugs from the machine's.
What did the I/O runtime and the blocking pool teach me?
Two things, both from memory rather than speed.
First, an unbounded blocking pool is a resource leak with a delay. A local file store reads each range on a blocking thread, and the buffer lives in that thread's allocator heap. Tokio's default pool grows to 512 threads. In one TPC-H q21 run at scale factor 10 under a 2 GiB memory limit, the process ran up to about 200 threads and held roughly 690 MiB more resident memory than the live heap, because freed pages stayed resident in the idle reading threads. Both runtimes now have explicit bounds, and requests beyond the bound queue.
Second, a blocking closure keeps its pool slot until it returns, even if the future waiting on it is dropped by cancellation. So a long closure has to check its query's cancellation itself between chunks, each chunk at most about 10 ms. Async cancellation does not reach into a running thread.
Can I test async code deterministically?
Mostly, yes, and it was worth the effort. The executor has a deterministic mode where every task, blocking closures included, runs on the caller's current-thread runtime with a paused clock. With a seeded config, interleavings, morsel order and the timing of spill and cancel events replay exactly, and a paused clock never advances inside a poll, so no slice counts as a stall. The point is that a scheduling-dependent failure can be replayed from a seed instead of waiting for it to recur in CI.
What is not settled yet?
- The 16-core tripwire. The decision stands on a six-core shared laptop, and I would not generalise it to a large server.
- Priorities. Option B's motivating feature, workload classes, was not exercised, and the executor accepts a workload class that does nothing yet.
- Async I/O starvation. The experiment did not stress object-store reads together with a heavy compute load.
- The yield discipline is a convention held up by a detector. A kernel that runs long without touching a batch boundary is caught in tests that reach it, not by the type system.
What should I read next?
The experiment above is also the reason I trust my benchmark protocol, so the next Krishiv post is about benchmarking honestly: noise floors and paired A/B runs. For the shape of the engine around the executor, see the anatomy of a query engine.
Series: 5. When one machine beats a cluster · 7. This post.
New deep dives by email
One email per post, no spam, unsubscribe any time.