Skip to content

Explore MPMC queue contention, wakeup, and storage optimizations #298

Open

Description

@tisonkun

Goal

Explore measurable performance improvements to the competing MPMC queues introduced in #265. Preserve their delivery, strict bounded capacity, cancellation, and disconnection contracts. The existing mutex-based implementation is a valid baseline; a lock-free rewrite is not a prerequisite.

Candidates to investigate

  1. Queue and waiter coordination. Shared uses a queue mutex plus separate sender and receiver semaphores, each with its own waiter lock. Profile lock acquisitions, cache contention, and retries after a notified task loses the race. Compare this with keeping queue state and waiter bookkeeping under one mutex before introducing more elaborate synchronization.
  2. Separate bounded and unbounded internals where useful. Both currently share capacity: Option<usize> and both semaphore fields, although unbounded sends never wait for capacity. A smaller unbounded state and a bounded-specific capacity model may simplify hot paths. Public endpoint types can stay unchanged.
  3. Bounded storage allocation. The current VecDeque grows lazily while the queue mutex is held. Compare preallocation or a fixed-capacity buffer with the current approach, including construction cost and large, mostly empty capacities. Preserve the exact requested logical capacity.
  4. Unbounded burst handling and memory retention. Measure allocation frequency and retained memory after a burst drains. Investigate chunked storage, incremental reclamation, or limited internal batching if measurements justify them. MPSC's receiver-private batch relies on a unique receiver; do not copy it into MPMC without preserving message accessibility and correct cancellation/drop behavior for competing receivers.
  5. Waiter allocation and scheduling overhead. Profile repeated registration, redundant waker clones, and wake-to-poll round trips under empty/full transitions. Optimize only measured costs while preserving notification transfer on cancellation and the Waker contract in AGENTS.md.

These are hypotheses to test, not a requirement to implement every candidate. Coordinate capacity-accounting changes with the bounded-reservation work in #297.

Measurement and acceptance

Start with the existing MPMC ecosystem benchmarks, which compare asyncband, async-channel, and Flume across 1P/1C, 1P/8C, 8P/1C, and 8P/8C. Keep producer/consumer behavior and message counts comparable.

  • Cover bounded and unbounded queues, small and larger capacities, steady traffic, bursts, and idle-to-active transitions. Include workloads where receivers stop at different times rather than only consuming equal quotas.
  • Report reproducible before/after results with commit, toolchain, hardware, runtime/thread setup, and benchmark parameters. Measure throughput and latency; include allocations and peak/retained memory for storage changes.
  • Explain which cost each change removes and report regressions across the other topologies. Land independently reviewable improvements rather than one combined backend rewrite.
  • Preserve deterministic cancellation and disconnect regressions, exactly-once delivery, and bounded-capacity checks; use the relevant cargo x workflows and Miri where appropriate.

Follow-up to #211 and #265; part of #206. This issue does not add public APIs.

Activity

  1. added
    enhancement
    help wanted
    on Sep 11, 2026
  2. Kaileshwar16 commented on Oct 11, 2026

    @Kaileshwar16
    Contributor

    Hey @tisonkun, I spent some time benchmarking the MPMC queue against async-channel on current main (44fc2d8). I found a pretty noticeable gap with 1 producer and 8 consumers running on separate OS threads. Asyncband was around 3.4–4.2x slower at 16K messages and 4.9–5.6x slower at 100K. Interestingly, the gap was much smaller with async tasks, and asyncband was actually faster in some paced workloads.
    I also tried a prefilled queue to take wakeups out of the picture, and the diagnostics still showed quite a bit of mutex contention. So I am leaning toward the shared queue lock being the bigger issue here.
    I am still looking into it, but do you think reducing contention in the thread-heavy case is worth pursuing? Or would you rather focus on the async-task workloads?

  3. tisonkun commented on Oct 11, 2026

    @tisonkun
    MemberAuthor

    @Kaileshwar16 Thanks for looking into this!

    I'd poll @ariesdevil here for advice and I may look closer days later. Feel free to ping me if I don't reply the next Sunday.

  4. Kaileshwar16 commented on Oct 11, 2026

    @Kaileshwar16
    Contributor

    Thanks! I will keep looking into the contention side and see if I can find a change that gives a measurable improvement. Would be great to hear ariesdevil's thoughts too.

  5. Kaileshwar16 commented on Oct 11, 2026

    @Kaileshwar16
    Contributor

    A quick update on this: I finished the investigation and tried a few different approaches. The biggest improvement came from using parking_lot::Mutex for the MPMC queue. It reduced execution time by around 23% for async 1P/8C and 33% for 8P/8C in my local benchmarks.

    There are some tradeoffs though. It barely improves the original thread-heavy case, and I found around a 5% regression in bounded 4P/4C. It also adds dependencies.

    The tests, lint checks, and Miri checks passed, but I'm holding off on a PR for now.

    @tisonkun @ariesdevil, do you think the async performance gains are worth the added dependency, or would you prefer keeping the existing mutex?

  6. Kaileshwar16 commented on Oct 11, 2026

    @Kaileshwar16
    Contributor

    One more interesting thing I found: when the queue was already filled with messages, asyncband was actually faster than async-channel. The big slowdown mostly showed up when receivers kept waiting on an empty queue.

    I also tried changing the blocking executor, but the 1P/8C gap was still around 4.4x at 100K messages. The diagnostics showed much more receiver wakeup activity in asyncband, although those counters don't tell us exactly how many wakeups are unnecessary.

    So it looks like the receiver waiting/notification path is worth investigating further. I haven't found a safe optimization for that part yet, but wanted to share what I found.

  7. ariesdevil commented on Oct 14, 2026

    @ariesdevil
    Member

    @tisonkun @Kaileshwar16 thanks for the investigation and the ping.

    A quick note first: #368 only changes the blocking executor, which now yields once before an untimed wait sleeps. That removes most of the thread-heavy 1P/8C gap caused by sleep/wake cycles, but it leaves the queue unchanged.

    For the queue itself, #314 already took the first step from candidate 1: values, endpoint counts, and both waiter queues now share one mutex. I think the next step is a lock-free ring buffer for the bounded data path, along the lines of crossbeam-queue's ArrayQueue (Vyukov's bounded MPMC queue):

    • Producers claim positions with a CAS on a tail cursor and consumers with a CAS on a head cursor, so each cursor is written by only one side.
    • Each slot carries a sequence number (stamp) that hands the slot from the producer that filled it to the consumer that takes it, so values move without a shared lock.
    • The mutex remains only on the slow path, for registering and waking waiters when the ring is full or empty. A sender checks an atomic for waiting receivers before taking that lock, so the uncontended path stays lock-free. This is roughly how async-channel is built on concurrent-queue and event-listener.

    This is also the point where cache padding starts to matter. Today every party writes the same mutex-protected state, which is true sharing that padding cannot fix; when I padded the blocking parker to 128 bytes, the contended benchmarks got slower. Once producers and consumers write separate cursors, the head and tail should live on separate cache lines, as ArrayQueue does with CachePadded. I'd copy CachePadded from crossbeam-utils 0.8.23 into an internal module rather than add a dependency, record its provenance in LICENSE and the source header as we did for parking, Pollster, and futures-lite, and land it together with the ring that uses it.

    The main design question is the existing bounded contract: pending send and reserve operations receive capacity in wait-queue order, and a Permit holds capacity without occupying a value slot. A lock-free fast path must not let a new sender take freed capacity ahead of queued waiters. I'd keep capacity accounting separate from slot claiming and allow the lock-free path only while no sender is queued, handing freed capacity to the first queued waiter as today. Does that match how you want to keep the ordering contract, or would you accept relaxing it on the fast path?

  8. Kaileshwar16 commented on Oct 14, 2026

    @Kaileshwar16
    Contributor

    Thanks for explaining, @ariesdevil I think keeping the existing capacity ordering makes sense, especially with pending sends and permits. Id be happy to help implement the ring buffer, once the design choice is confirmed. Are you planning to work on it, or would it be okay if I take a shot at it?

  9. FalkWoldmann commented on Oct 18, 2026

    @FalkWoldmann
    Contributor

    The 0.7 design in #146 lists rendezvous next to bounded and unbounded, but bounded(0) panics for both mpsc and mpmc in 0.7.3 and I couldn't find an issue about it. Was it dropped on purpose or just postponed? A zero-capacity channel where try_send only succeeds if a receiver is already waiting is quite handy for stuff like a thread pool that spawns a new worker when none is idle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementhelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions