Skip to content

perf(channels): separate producer and consumer progress in bounded MPMC and SPMC queues - #382

Open
ariesdevil wants to merge 1 commit into
apache:mainfrom
ariesdevil:dev_ariesdevil
Open

ariesdevil wants to merge 1 commit into
apache:mainfrom
ariesdevil:dev_ariesdevil

Conversation

@ariesdevil

@ariesdevil ariesdevil commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Related: #298

Summary

Optimize bounded MPMC and SPMC queues with a ring that keeps producer and consumer progress separate and isolates them on their own cache lines. Exact logical capacity, reservation ordering, cancellation, disconnection, and endpoint traits are preserved. Unbounded queues keep their mutex-based backend. Capacity-one queues and capacities beyond the ring's allocation budget keep lazy storage, so there is no new public capacity limit. These implementations are not lock-free.

Ring-backed queues preallocate up to 64 KiB of message storage, which stays allocated until every handle is dropped; see Memory.

Known limitations (details under Regressions and limits):

  • The immediately-ready capacity-one async round trip is 44.9% slower on Linux.
  • Single-producer bounded MPMC at capacity 64 is 23–37% slower on Linux. On Apple Silicon it is within about 10% of main.

Design Notes

  • Cursors publish completed payload transfers, not outstanding claims. They wrap at twice the capacity, so there are no per-slot stamps, no packed capacity bits, and no reliance on a generation counter wrapping slowly. Each side protects its own cursor and payload move, and caches the peer's progress.
  • MPMC reservations and detached grants belong to producer state, under the producer lock. Waiters use stable IDs rather than pointers into pending futures. A waiting send consumes its grant and publishes in one critical section.
  • A receiver unregisters before consuming, so notification bookkeeping never outlives a taken value. Locks do not nest on the hot path. Wakes and waker destruction happen outside locks. Both rings reuse refactor: share waiter lifecycles and simplify value ownership #431's RetryWaiter.
  • When the last receiver drops, the consumer cursor skips the queued values under one consumer lock (MPMC) or claim (SPMC).
    • The values are then dropped in place as at most two slices, as VecDeque's Drop does, so closing does not allocate.
    • A panicking destructor does not leak the remaining values.
    • SPMC holds its claim while the values drop, so the producer cannot reuse their slots. No remaining operation waits on that claim, and the spmc::bounded docs note this exception.
  • SPMC is a specialized single-producer ring.
    • It implements feat(spmc): add endpoint state queries, bounded reservation, and trait assertions #450's reserve/try_reserve from the producer's cached reclamation cursor. Only the producer consumes capacity, so reserved capacity stays available until Permit::send.
    • Closing the last receiver frees the queued slots, so try_reserve checks for disconnection after reading capacity, as try_send does.
    • A waiting send publishes and notifies under the control lock. Publishing outside the lock and relocking to notify cost 10% on macOS.
  • Both rings use the platform-aware CachePadded helper. Crossbeam provenance is retained in source and in LICENSE.

Benchmarks

The table gives median fixed-work elapsed times, main ae99c15 → PR a1284ba, built with the same harness and rustc 1.99.0. Negative is faster; these are not tail-latency claims.

  • macOS: Apple M5 Pro, 8 rotating runs per implementation.
  • Linux: Xeon 6982P-C KVM guest on kernel 7.0, 6 rotating runs per implementation on CPUs 0,2,...,30. Each revision had its own build directory and hash-verified executables.
Scenario Rounds macOS main → PR (ms) Linux main → PR (ms)
mpmc/bounded/tasks-2p2c-cap64-4w 270 299.5 → 242 (-19.2%) 1826 → 1003.5 (-45.0%)
↳ AsyncbandMpmcReserve 270 343 → 298 (-13.1%) 1935.5 → 1134.5 (-41.4%)
mpmc/bounded/threads-2p2c-cap64 120 275.5 → 182 (-33.9%) 1075.5 → 686.5 (-36.2%)
↳ AsyncbandMpmcReserve 120 318 → 216 (-32.1%) 1256 → 962.5 (-23.4%)
mpmc/bounded/threads-1p8c-cap64 27 368 → 269.5 (-26.8%) 460 → 176 (-61.7%)
mpmc/bounded/threads-2p2c-cap1 4 338.5 → 338.5 (+0.0%) 318 → 316 (-0.6%)
spmc/bounded/tasks-1p4c-cap64-4w 320 278 → 232 (-16.5%) 1072 → 687.5 (-35.9%)
spmc/bounded/tasks-1p4c-cap1024-4w 320 265.5 → 221 (-16.8%) 1538.5 → 801.5 (-47.9%)

The spmc/bounded rows measure the dedicated SPMC queue (AsyncbandSpmc). The AsyncbandMpmc rows of those scenarios are under regressions.

The earlier stamped-slot revision (c766001) was faster on Linux in the 2P2C async and threaded cases, where this PR takes 30% and 155% longer. In threaded 1P8C, this PR takes 61% less time. This PR does not claim that revision's peak throughput.

Regressions and limits

  • Capacity-one send_then_recv (lazy storage, not the ring): on Linux with a fixed single CPU, the median for 24 million round trips went from 755.5 ms to 1095 ms (+44.9%). Main also has a slower mode near 924 ms, and the PR is slower than that too. The cause is unresolved; async backend dispatch and future construction are a follow-up investigation.
  • Single-producer MPMC at capacity 64: these are the AsyncbandMpmc rows of spmc/bounded/tasks-1p1c-cap64-4w, tasks-1p4c-cap64-4w, and tasks-1p4c-cap64-current.
    • Linux: +37%, +23–31%, and +28–30% over three rotations, reproduced after a later rebase.
    • macOS: −1%, −6%, and +10%.
    • Cause: each transfer publishes its cursor with a SeqCst store, which is an xchg on x86-64. Each side therefore does three locked instructions per operation, where main's mutex does two.
    • Dropping the barrier and having waiters synchronize through the peer lock was checked with Miri. It brings these cells near main, but costs 20–40% in Linux async 2P2C and about 2x in threaded 1P8C. It also adds 4–20% on macOS.
    • A Release store followed by fence(SeqCst) is no faster.
    • Avoiding the barrier on both sides would need the waiting flag in the lock word, which means a custom lock and is out of scope.
  • Other cells: other Linux capacity-one microbenchmarks regress by 2–4% (MPMC) and 3.2% (the SPMC task workload). Unbounded results are broadly unchanged.
  • Not measured: P99/P999 latency and oversubscribed scheduling. All Linux results come from one VM.

Memory

Measured with a counting global allocator on a full capacity-4096 queue of [u64; 2], keeping the sender while the last receiver drops:

Linux (rustc 1.99.0) main ae99c15 PR
Retained after receiver drop 200 B 66,384 B (MPMC) / 66,256 B (SPMC)
Close-path allocations 0 0
Close-path extra peak 0 B 0 B

The retained memory is the ring itself. The SPMC producer accesses slots without a lock, so freeing them at receiver close would need extra synchronization on its hot path. On macOS, both close paths show one 64 B allocation, which is std lazily boxing the pthread mutex rather than ring storage.

Validation

  • Rebase: rebased onto 1cadff0 (0.8.1 release preparation). Only the changelog entries moved, to Unreleased.
  • Review fix: SPMC try_reserve used to check for disconnection before reading capacity. If the last receiver dropped between the two reads, a full queue could hand out a permit for the discarded slots.
    • receiver_close_racing_reservation_cannot_reserve_discarded_slots races that drop against try_reserve and reserve.
    • Under Miri at 32 iterations, it failed on 37 of 64 seeds before the fix. All 64 seeds pass after it.
    • The send and receive paths are unchanged.
  • Current head:
    • cargo x test: 787 passed on macOS and on Linux.
    • cargo x lint and cargo x check passed on macOS.
    • cargo x miri with the CI flags (-Zmiri-many-seeds=0..4) passed: 82 library tests (15 of them ring tests), MPMC integration 33 passed/2 ignored, and SPMC integration 33 passed/2 ignored.
  • After the feat(spmc): add endpoint state queries, bounded reservation, and trait assertions #450 rebase (13b13e4), a Linux rotation reproduced the profile:
    • MPMC: 2P2C async −41%, threaded 2P2C −46%, threaded 1P8C −61%, spin −37%.
    • SPMC 1P4C: −43% at capacity 64 and −50% at capacity 1024.
    • Single-producer MPMC: +11–35%.
    • Capacity-one send_then_recv: +37%.
  • Earlier heads (the ring's synchronization has not changed since):
    • Thread-blocking ring tests cover 1P/1C alternation and 2P/2C waiters queued on a capacity-two ring. They passed Miri with -Zmiri-many-seeds=0..640. Removing the cursor/flag StoreLoad ordering makes them report deadlocks.
    • The ring tests passed with 0..128 seeds.
    • The 32-bit powerpc-unknown-linux-gnu MPMC Miri run passed (33 passed, 2 ignored).
    • 30 consecutive Linux release runs passed.
    • The MPMC/SPMC ecosystem smoke checks passed.
  • Post-review simplifications: A/B runs on Linux stayed within ±1.5%, except spin-2p2c-cap64 (+3.4%) and SPMC tasks-1p4c-cap64-4w (+3.2%). Both are attributed to code layout, since a build with instruction-identical hot functions reproduced the shift.
  • Coverage: complete cursor wraps, reservations held across wraps, exactly-once delivery under contention, cancellation before payload destruction, close and wakeup behavior, panicking close-path destructors, reentrant waker destruction, large logical capacities, and legacy endpoint traits.
  • Not run on Linux: nightly lint, the nightly feature matrix, and Miri, because the toolchain was unavailable.

@ariesdevil ariesdevil changed the title perf(mpmc): make bounded queues lock-free perf(mpmc): back bounded queues with a ring buffer Oct 20, 2026
@ariesdevil
ariesdevil force-pushed the dev_ariesdevil branch 4 times, most recently from 94d174b to 4ea81c4 Compare October 21, 2026 08:39
Comment thread licenserc.toml Resolved
Comment thread .asf.yaml Resolved
Comment thread asyncband/src/lib.rs Resolved
Comment thread asyncband/src/lib.rs Resolved
@tisonkun

tisonkun commented Nov 3, 2026

Copy link
Copy Markdown
Member

@ariesdevil You may update the branch to resolve the conflict with the main branch, and I will also adopt the new benchmark best practice that you can leverage. Once this pull request is clean, I will do another review.

Comment thread CHANGELOG.md Resolved
@ariesdevil ariesdevil changed the title perf(mpmc): back bounded queues with a ring buffer perf(channels): optimize bounded MPMC and SPMC queues Nov 18, 2026
@ariesdevil
ariesdevil force-pushed the dev_ariesdevil branch 2 times, most recently from e224174 to 9dafdbb Compare November 19, 2026 06:35
@ariesdevil ariesdevil changed the title perf(channels): optimize bounded MPMC and SPMC queues perf(channels): separate producer and consumer progress in bounded MPMC and SPMC queues Nov 19, 2026
@ariesdevil
ariesdevil force-pushed the dev_ariesdevil branch 2 times, most recently from a7b742b to e62283f Compare November 19, 2026 09:09
Back bounded MPMC and SPMC queues with preallocated rings that track producer and consumer progress
separately and keep each side's hot state on its own cache line. Cursors publish completed payload
transfers and cache peer progress, with no per-slot stamps or packed capacity bits. MPMC
reservations and detached grants belong to producer state under the producer lock, and waiters use
stable IDs instead of pointers into pending futures. Receiver registration is separate from the
consumer cursor, and wake callbacks and waker destruction run outside locks. SPMC keeps a
specialized single-producer ring.

Exact logical capacity, reservation ordering, cancellation, disconnection, and endpoint traits are
unchanged. Unbounded queues keep the mutex backend, which bounded queues also use at capacity one
and beyond the ring allocation budget. Copy CachePadded from crossbeam-utils and record the
incorporated crossbeam portions in LICENSE.

Each transfer publishes its cursor with a SeqCst store, an xchg on x86-64, so single-producer
capacity-64 MPMC workloads are slower than main on Linux; the changelog records this.

The benchmarks gain reserved-send and crossbeam-channel MPMC adapters, fixed-work 1P/8C,
capacity-one, spinning, and SPMC scenarios, and reservation micro-benchmarks.

Co-authored-by: tison <wander4096@gmail.com>

This branch has not been deployed

No deployments
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.

2 participants