Skip to content

perf(broadcast): replace mutex-backed unbounded backlog with segment buffers - #469

Merged
tisonkun merged 6 commits into
apache:mainfrom
biaoma-ty:perf/broadcast-unbounded-segments
Nov 24, 2026
Merged

tisonkun merged 6 commits into
apache:mainfrom
biaoma-ty:perf/broadcast-unbounded-segments

Conversation

@biaoma-ty

@biaoma-ty biaoma-ty commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

broadcast::mpmc::unbounded previously put its VecDeque<Slot<T>> backlog, Arena<u64> subscriber cursors, and parked receiver wakers behind one channel Mutex, so every publish, receive, empty probe, subscription change, and cancellation serialized on the same lock.

  • Segment-backed backlog and atomic slot retention (broadcast::mpmc::unbounded::{queue, segment}): Replace the mutex-guarded VecDeque and cursor arena with an 8-slot inline segment in Shared<T> plus 252-slot (4,080 B, single 4 KiB page) heap segments, monotonic tail and reclaimed u64 counters (AtomicU64 with a Mutex<u64> fallback on targets without 64-bit atomics), and per-slot receiver counts so steady-state send, try_recv, try_recv_cloned, ready recv / recv_cloned polls, empty probes, and zero-receiver discards proceed without acquiring a channel mutex.
  • 1-word Unpin receive futures and WakerSet-backed waiters (mod, waiters): Replace the outer async fn receive wrappers with 1 * usize (8 B on 64-bit, 4 B on 32-bit) Unpin RecvShared and RecvCloned futures backed by an inline single-waiter slot and internal::wakerset::WakerSet overflow storage, keeping uncontended single-receiver waits allocation-free and detaching woken registrations without relocking on drop.
  • Tests and changelog: Expand unit, integration, Unpin trait, and multi-seed Miri coverage for segment boundaries, retired-predecessor unlinking, half-closed segment reclamation across unwinds and lagging drops, in-flight slot suspension and parking, and concurrent subscription churn, and update CHANGELOG.md.

Closes #402.
Part of #396.

Design Notes

  • Per-slot receiver counts and sole-owner unwrap: When k receivers are subscribed, send claims the next u64 version, writes Arc<T> into the segment slot, and stores slot.state = k. Each receiver advances its own (cursor, seg, slot_ptr, rem_in_seg) cursor: when slot.state == 1, the final eligible reader moves the Arc<T> out directly without an atomic decrement (so try_recv_cloned and recv_cloned still unwrap T without cloning on sole ownership) and increments reclaimed; when slot.state >= 2, readers clone the Arc<T> before fetch_sub(1, AcqRel). When no receivers exist, send discards the value without entering the backlog while advancing both tail and reclaimed.
  • Subscription changes, incremental segment reclamation, and half-closed cleanup: Publishers enter one of four cache-line-separated epoch shards around send (shard0 inline plus three lazily allocated shards once cloned). subscribe and drop_receiver pause new publishers under control only while snapshotting tail and updating live_receivers, while seg_readers tracks subscriptions through unlocked backlog drains so inline_seg0 is only reset once every live and draining reader has released its segment reference. Retired heap segments recycle across 3 publisher epochs, retaining at most one 4,080 B spare segment during active streaming and deallocating excess segments immediately (including during partial drains and upon endpoint closure).
  • In-flight slot handoff: Because tail advances right before send finishes writing slot.msg and slot.state, a receiver can briefly observe tail > cursor while slot.state == 0. Async poll_recv registers its task Waker and returns Poll::Pending rather than spinning on the executor thread, while synchronous try_recv and drop_receiver park on a private Mutex<bool> + Condvar waker so any caller Thread::unpark token stays intact.
  • Tradeoffs: Endpoint handles grow (16 B UnboundedSender plus a lazy shard allocation once cloned, and 56 B UnboundedReceiver on 64-bit targets), each channel uses a larger cache-line-isolated shared Arc allocation (936 B on aarch64-apple-darwin and 912 B on x86_64-unknown-linux-gnu, including 8 inline 16 B message slots) plus 4,080 B 252-slot heap segments (alloc_zeroed) when retained backlog exceeds 8 messages, and dropping a lagging receiver while other subscriptions remain active scans and decrements its unread slots.

Benchmarks

Measured back-to-back on Apple Silicon (aarch64-apple-darwin, optimized Cargo bench profile, median of 5 runs) comparing origin/main (1c5584d) against HEAD (b090ff8):

Benchmark Rounds main (1c5584d) This PR (b090ff8) Change
ecosystem broadcast/no-backpressure/try-roundtrip 9,100,000 230 ms (vs Tokio 103) 148 ms (vs Tokio 103) -35.7% (1.55x)
ecosystem broadcast/no-backpressure/ready-roundtrip 8,000,000 214 ms (vs Tokio 122) 134 ms (vs Tokio 125) -37.4% (1.60x)
ecosystem broadcast/no-backpressure/publish-4p-drain-1r 810 288 ms (vs Tokio 110) 252 ms (vs Tokio 111) -12.5% (1.14x)
ecosystem broadcast/no-backpressure/drain-4r 500 320 ms (vs Tokio 67) 74 ms (vs Tokio 65) -76.9% (4.32x)
primitives send_and_try_recv_shared 6,000,000 185 ms 97 ms -47.6% (1.91x)
primitives send_and_try_recv_string_shared 3,000,000 168 ms 128 ms -23.8% (1.31x)
primitives send_and_try_recv_string_cloned_sole 3,000,000 154 ms 129 ms -16.2% (1.19x)
primitives send_and_try_recv_string_cloned_fanout 3,000,000 208 ms 175 ms -15.9% (1.19x)
primitives deliver_to_waiting_receiver 6,000,000 241 ms 168 ms -30.3% (1.43x)
primitives register_and_deliver_fanout/1 3,000,000 564 ms 538 ms -4.6%
primitives register_and_deliver_fanout/4 750,000 245 ms 258 ms +5.3%
primitives register_and_deliver_fanout/16 187,500 198 ms 181 ms -8.6%
primitives send_without_receivers 12,000,000 211 ms 41 ms -80.6% (5.15x)
primitives try_recv_empty 60,000,000 317 ms 62 ms -80.4% (5.11x)
primitives drain_with_receivers/peak 1 live 1 10,000,000 241 ms 155 ms -35.7% (1.55x)
primitives drain_with_receivers/peak 8 live 8 1,250,000 79 ms 35 ms -55.7% (2.26x)
primitives drain_with_receivers/peak 8 live 1 10,000,000 242 ms 154 ms -36.4% (1.57x)
primitives drain_with_receivers/peak 32 live 32 312,500 63 ms 33 ms -47.6% (1.91x)
primitives drain_with_receivers/peak 32 live 4 2,500,000 102 ms 48 ms -52.9% (2.13x)
primitives drain_with_receivers/peak 32 live 1 10,000,000 241 ms 155 ms -35.7% (1.55x)
primitives drain_with_receivers/peak 256 live 32 312,500 70 ms 33 ms -52.9% (2.12x)
primitives drain_with_receivers/peak 256 live 1 10,000,000 244 ms 153 ms -37.3% (1.59x)
primitives cancel_pending 3,000,000 287 ms 233 ms -18.8% (1.23x)

Validation

  • cargo x lint
  • cargo x check
  • cargo +1.86.0 check --workspace --all-targets --all-features
  • cargo x test
  • cargo +stable semver-checks --baseline-rev origin/main -p asyncband --all-features (196/196 passed)
  • MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package asyncband --lib --features broadcast -- broadcast::mpmc
  • MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-many-seeds=0..4" cargo +nightly miri test --package tests-integration --test broadcast_test --test traits_test
  • cargo x bench -- --test

…buffers

Replace the single-mutex VecDeque backlog and Arena cursor table in broadcast::mpmc::unbounded with reference-counted segment buffers (an 8-slot inline segment plus pooled 256-slot heap segments), atomic per-slot receiver counts, and explicit 16-byte Unpin RecvShared and RecvCloned futures:

- Let steady-state send, try_recv, try_recv_cloned, ready recv / recv_cloned polls, empty probes, and zero-receiver discards execute without acquiring a channel mutex, while keeping a Mutex<u64> fallback on targets without 64-bit atomics.
- Coordinate subscription changes through four cache-line-separated publisher epoch shards, recycle retired heap segments across three epochs with burst hysteresis, and immediately release heap segments when either endpoint side closes and finishes draining.
- Suspend poll_recv without spinning when a claimed slot write is still in flight, and park synchronous try_recv and drop_receiver in-flight waits on a private Mutex + Condvar waker.
…overage

Expand integration, auto-trait, and changelog coverage for unbounded broadcast segment buffers and explicit receive futures:

- Cover poll-after-completion panics, overflow waiter slot reuse and waker replacement, completed future moves after payload drop, multi-segment concurrent subscribe/resubscribe/drop churn, close vs. try_recv linearizability, and concurrent last-receiver drop with resubscription in broadcast_test.
- Assert Unpin on UnboundedReceiver::{recv, recv_cloned} futures over !Unpin payloads in traits_test.
- Record the broadcast::mpmc::unbounded improvements and tradeoffs in CHANGELOG.md.
@biaoma-ty
biaoma-ty force-pushed the perf/broadcast-unbounded-segments branch from 5f094a0 to 83310f3 Compare November 24, 2026 14:23
…ordering races

Fix concurrency, layout, and counter-bound defects in `broadcast::mpmc::unbounded`:

- Distinguish retired segments from segments without an allocated successor by storing a dedicated `unlinked_next` sentinel on `release_seg_ref` and reloading `tail_seg` when a preempted publisher encounters an unlinked predecessor, while guarding `advance_or_get_next_for_pub` against resurrecting a retired segment's zero reference count.
- Compute `Segment::slot_ptr_at` via `mem::offset_of!(InlineSegment<T>, slots)` backed by a compile-time layout equality check with `HeapSegment<T>` instead of a zero-length `[MsgSlot<T>; 0]` tail array, fixing a 4-byte slot misalignment into uninitialized padding on 32-bit targets.
- Use `Ordering::SeqCst` across publisher `tail_seg` loads, `extra_shards` pause barriers, and 3-epoch `Shard::is_epoch_idle` checks so weak-memory Store-Buffering reorderings cannot bypass subscription pauses or segment quiescence, and unify `Shard` to `[AtomicUsize; EPOCHS]` to eliminate the 16-bit per-epoch publisher cap.
- Guard `CounterU64::claim_next` and `advance_or_abort` below `u64::MAX` so concurrent overflow checks saturate cleanly without wrapping `tail` to zero, and replace mutual recursion between `send` and `send_cold` with `try_discard_cold`.

Signed-off-by: tison <[email protected]>
… races

Eliminate the segment-pool hysteresis glue in `broadcast::mpmc::unbounded` while closing half-closed inline-segment reset races and adding a lock-free final-receiver teardown path:

- Replace `SegmentPool`'s multi-segment `free_list`, cycle peak tracking, and `maybe_shrink_pool` hysteresis with a single `spare` heap segment (`HEAP_CAP = 252`, fitting a 4 KiB page on 64-bit targets) so excess retired segments deallocate immediately upon 3-epoch quiescence during streaming and partial drains without per-message cold-path probes.
- Track active segment readers (`seg_readers`) across `drop_receiver`'s unlocked backlog drain so `reclaim_all_heap_when_no_receivers`, `reclaim_when_drained_and_disconnected`, and zero-receiver `subscribe` only reset `inline_seg0` once every live and draining subscription has released its segment reference, unlink any speculative successor attached to `inline_seg0` at the `INLINE_CAP` boundary, and keep publishers paused until pool cleanup completes.
- Release any cached spare segment when the final sender disconnects on an already-drained channel, and bypass locks and atomic RMWs when dropping the sole remaining `seg_readers == 1` receiver on a disconnected channel.

Signed-off-by: tison <[email protected]>
…ontracts

Replace custom overflow waiter arena bookkeeping with `internal::wakerset::WakerSet`, shrink receive futures to one pointer, and tighten observable contract documentation:

- Keep the uncontended inline `slot0` waker in `Waiters` while delegating multi-waiter overflow slots to `WakerSet` and storing registration state on `Subscription<T>`, shrinking `RecvShared` and `RecvCloned` to `size_of::<usize>()` (`8 B` on 64-bit and `4 B` on 32-bit targets).
- Saturate `retained_message_count` and `unread_from` to `usize::MAX` instead of panicking on 32-bit concurrent skew, and document in-flight publication and approximate reclamation observations on `retained_message_count` and `unread_message_count`.
- Update `CHANGELOG.md` with measured cross-platform allocation sizes and final observable contracts.

Signed-off-by: tison <[email protected]>
Run `ptr::drop_in_place` on `HeapSegment<T>` before `alloc::dealloc` so targets without 64-bit atomics drop the `Mutex<u64>` fallback in `Segment::base` instead of leaking any lazily boxed OS mutex state, while compiling to a no-op on 64-bit-atomic targets, and tighten the `reclaim_when_drained_and_disconnected` doc comment to match its sole-reader scope.

Signed-off-by: tison <[email protected]>
@tisonkun
tisonkun enabled auto-merge (squash) November 24, 2026 23:20

@tisonkun tisonkun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks!

I'm afraid that all this code changes increase the cognitive overload, so maybe later we will give an overall code review for all the channels.

@tisonkun
tisonkun merged commit ed4a31e into apache:main Nov 24, 2026
9 checks passed
@biaoma-ty

Copy link
Copy Markdown
Contributor Author

Thanks!

I'm afraid that all this code changes increase the cognitive overload, so maybe later we will give an overall code review for all the channels.

Roger that.

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.

Reduce unbounded MPMC broadcast publish and receive overhead

2 participants