Kaspar's Actor Mailbox Design: Ring Buffer + Overflow, Why Not Lock-Free, and 4 Queue Benchmarks
This article details the mailbox design in the Kaspar HFT system, explaining the Ring Buffer with overflow approach (BQueue), why lock-free queues aren't default due to cache contention and spin overhead, and benchmarks four implementations (BQueue, BQueueBatched, ShardedBQueue, LockFreeMPSC) under various loads showing ShardedBQueue excels at fan-in while pinning threads matters more than queue choice for latency.
Reading font

Mailbox Purpose and Handling Full Queues
In Kaspar, every actor has a mailbox: a multi-producer, single-consumer (MPSC) queue. Asynchronous send goes through the mailbox; actors in the same Group share one mailbox; fast_send bypasses the mailbox via direct function call. The design goal is graceful degradation: fast under light load, slowing smoothly under load, never failing abruptly.
When a bounded queue fills, three typical strategies exist, all problematic for trading systems:
Block producers : A slow consumer (e.g., logging, DB writer) fills its mailbox, blocking the market-data thread. Multicast market data does not wait; packets queue in kernel then NIC then drop, forcing gap recovery.
Drop messages : Simple and fast but breaks state. Order books are built from incremental updates; dropping one makes the book wrong silently. Dropping a trade message corrupts positions.
Unbounded queues : No limit, but every push may allocate on the hot path, and resizing happens when the system is busiest. A stuck consumer causes unbounded memory growth until OOM kill.
Blocking and dropping are unacceptable, so the queue must be effectively unbounded. Unbounded queues imply unbounded latency: a lagging consumer makes the queue longer, so tail messages become stale. The actor may process a market-data update describing the order book 400 µs ago without knowing it, because messages don't carry expiration.
Timestamp checking must be done by the strategy, not the queue: a queue that drops by time would drop market data, but market data must not be dropped — the order-book actor must see every message in order regardless of lag. Responsibilities are split:
Queue : Never drops, never blocks, never reorders. All messages eventually delivered.
Order book : Processes every message, including expired ones. Applying stale increments in order still converges to correct state.
Strategy : Decides if data is too stale. Before acting on a signal, compare message timestamp with current time; if gap too large, don't trade.
Only the strategy knows its latency tolerance. A strategy holding positions for minutes ignores 400 µs; a queue-position-dependent strategy loses edge at 400 µs lag.
BQueue: Ring Buffer with Overflow Area
Structure
Kaspar's default mailbox is BQueue:
struct Inner<T> {
ring: VecDeque<T>, // fast path, length ≤ cap, no reallocation
overflow: VecDeque<T>, // overflow area, used only when ring full or overflow non-empty
}
pub struct BQueue<T> {
inner: Mutex<Inner<T>>,
cv: Condvar,
cap: usize,
}Two containers: a pre-allocated RingBuffer (circular array) sized for normal load, plus an overflow area used only when exceeding normal capacity. cv is a condition variable: consumers sleep on it when queue empty; producers call notify_one() per message.
pub fn push(&self, x: T) {
let mut g = self.inner.lock().unwrap();
if !g.overflow.is_empty() || g.ring.len() >= self.cap {
g.overflow.push_back(x);
} else {
g.ring.push_back(x);
}
self.cv.notify_one();
}Common case: RingBuffer has space, push writes once into pre-allocated contiguous memory — no allocation, no resizing, cache-friendly. When RingBuffer fills, messages go to overflow; producers never wait, messages never dropped, market-data thread keeps reading.
Rust's overflow uses VecDeque (reallocates and copies on growth); C++ uses std::deque (segmented array, constant-time push). Overload consequence becomes memory growth — monitorable and manageable — unlike dropped market data or corrupted books which are hard to recover.
Maintaining Order
The condition !g.overflow.is_empty() is critical. Once any message enters overflow, all subsequent messages go to overflow even if RingBuffer empties and has space. Otherwise new messages would enter RingBuffer while old ones remain in overflow, and pop() (which prioritizes RingBuffer) would deliver new messages first, breaking FIFO.
Message reordering in actor systems is a correctness issue: trade confirmations arriving before orders, or a market update applied before its predecessor. The guarantee "messages seen in send order" would break silently, only under high load. The queue accepts slight inefficiency (RingBuffer idle while overflow drains) for strict FIFO.
Last Flag
pub fn pop(&self) -> (T, bool) {
let mut g = self.inner.lock().unwrap();
loop {
if let Some(x) = g.ring.pop_front() {
let last = g.ring.is_empty() && g.overflow.is_empty();
return (x, last);
}
if let Some(x) = g.overflow.pop_front() {
let last = g.ring.is_empty() && g.overflow.is_empty();
return (x, last);
}
g = self.cv.wait(g).unwrap();
}
}pop()returns the message and a boolean indicating whether the queue is empty after this pop. Under backlog, the actor can use this to reduce decisions: process each message updating state only, skip decisions until last == true (backlog cleared), then evaluate and trade. Order book sees every update in order; strategy avoids per-stale-message decisions. last == true only means the mailbox was empty at that instant. If a market packet has ten increments, the consumer might pop the first while nine more are still being enqueued — last would be true. Batch completion relies on protocol end-markers; staleness relies on timestamps.
Why Not Lock-Free by Default
Lock-Free Meaning
Lock-free is a progress guarantee: some thread always completes; one thread stalling doesn't halt the system. It does not guarantee latency or throughput. With low contention, locked versions are often no slower; uncontended lock/unlock are single atomic ops, no retry loops.
Cache-Coherence Contention
Lock-free queues still contend on shared head/tail pointers. All producers/consumers hammer a few atomic variables; cache-coherence serializes atomic updates on the same address one core at a time — same serialization as locks, just at cache-line level. Many cores contending on one cache line cause wait times scaling with contender count. Synchronization overhead comes mainly from cache-coherence traffic, largely independent of locking. Even without contention, an atomic op on a remote socket costs hundreds of cycles.
Spinning When Idle
Lock-free queues lack sleep mechanisms. Empty queue: dequeue returns "no data" immediately; consumer either spins or adds a condition variable. Pure spinning burns a core doing nothing. Common mitigation: PAUSE ( std::hint::spin_loop()) hints spin-wait, reducing power and hyperthread contention, but thread still occupies core, not sleeping.
Spinning consumers worsen cache issues: they repeatedly read shared cache lines, keeping them in their cache; each producer write forces cache-line ping-pong between cores.
Spinning helps only when runnable threads ≤ cores (dedicated core polling NIC). In component-rich systems, threads > cores (oversubscription): spinning threads don't yield until time-slice ends, blocking other ready threads. At high oversubscription, OS-blocking paths outperform spinning; more spinning actors can make the system slower than blocking queues, throughput may even drop with more parallelism.
Thread Pools
Thread pools (workers pulling from shared queue) suit load balancing but retain idle-wait and cache problems. Workers still wait (block or spin). Cache pollution worsens: task submission moves data from submitter's core cache to worker's cold cache via coherence; shared task queue becomes a contended cache line.
Kaspar's Approach
Avoid cross-thread handoff entirely: fast_send executes target actor's handler on caller's thread — no queue, no cross-thread pass, no wakeup. Hot path stays on one core, data stays in that core's cache. "Spin vs block" only exists when messages cross threads; no crossing, no problem. Busy-wait suits dedicated core polling one thing (e.g., NIC) with no other duties.
Market-data-to-order path uses Groups (shared thread + mailbox) and fast_send: same Group messages enqueue/dequeue on one thread, no wakeup; fast_send direct calls, bypass mailbox. Cross-thread wakeup mailboxes used only off hot path.
Scale: many actors (order books, per-contract logic, order management, timers, logging, monitoring). Spinning mailboxes would give each waiting actor a full core — not enough cores. BQueue consumers sleep via condition variable when empty, consuming zero CPU; idle actors don't burn cores, allowing many small actors. BQueue trades one wakeup latency for near-zero idle overhead, no cache pollution when idle, and avoids lock-free memory-reclamation complexity. Memory reclamation is lock-free's unique hard problem: when is a node safe to free while other threads might read it? C++26 added std::hazard_pointer; Rust uses epoch-based reclamation. Mailbox type is per-actor replaceable; an actor needing lock-free can swap without code change.
Batch Message Dequeue
Per-Message Overhead
Rust consumer loop (simplified):
while running {
let (env, _last) = cell.queue.pop(); // (1) lock mailbox
let mut guard = cell.actor.lock(); // (2) lock actor
guard.process_message(env.msg, &mut ctx); // dispatch & execute
}Each message incurs: mailbox lock on pop(); actor lock on dispatch; sender locks mailbox on push() plus notify_one(); one heap allocation and free.
Drain Entire Mailbox Once
C++ has BQueueBatched: consumer locks once, drains RingBuffer then overflow (order preserved), then processes messages one by one. Adapts to load: one message → minimal overhead; 10,000 messages → lock overhead amortized over 10,000.
Early version also locked actor once per batch and notified only on empty→non-empty transition. Current version reverted to per-message actor lock (so fast_send can interleave) and per-push notify.
Latency vs Throughput
Async send round-trip typically microseconds; batch dequeue test shows tens of nanoseconds average per round-trip. They measure different things: former is latency when mailbox empty (message arrives, wakeup, process); latter is throughput under sustained backlog (10,000 in-flight, total time / round-trips). Two queue states:
Empty mailbox (latency) : Messages arrive slowly, actor keeps up, sleeps after each. Each message pays two condition-variable wakeups (~1–3 µs each). Spare capacity, throughput not an issue; no batchable messages.
Backlog (throughput) : Messages arrive faster than processing, mailbox stays full, actor never sleeps, wakeups drop to zero, average ~tens of ns per message, throughput limited by consumer speed.
Batch dequeue improves backlog throughput. Empty-mailbox latency remains microseconds, dominated by thread wakeup; batching doesn't change that.
One Lock Per Actor
Two ways to dispatch work to workers:
Shared task queue : One central queue, one lock. All producers and workers contend on same lock.
Per-actor mailbox (Kaspar): Each actor has own queue and lock. Sending to A locks A's lock; sending to B locks B's lock. Different senders never touch same lock.
N actors = N mailboxes = N locks = lock sharding by destination. Contention depends on threads wanting the same lock. Shared queue concentrates all producers on one point; sharding spreads them. If eight producers target one busy actor (fan-in), they still contend on that actor's lock — same tail latency as shared queue. Sharding works well when load distributed (e.g., per-instrument actors); true fan-in hotspots need other solutions (different mailbox, split actor responsibilities).
Four Mailbox Implementations
BQueue : RingBuffer + mutex + condvar, FIFO, sleeps when idle, default.
BQueueBatched : Same, but consumer drains entire mailbox in one lock.
ShardedBQueue : Mailbox split into N shards (each with lock), push round-robins across shards. Adjacent messages from same sender may land in different shards — no send-order guarantee.
LockFreeMPSC : Bounded lock-free RingBuffer. Producers CAS to claim slot (no lock). Empty queue: consumer sleeps on condvar. Full queue: producer spins briefly then blocks. Variant LockFreeMPSCSpin: consumer never sleeps, polls continuously.
Simplest lock-free enqueue (illustrative):
let slot = head.fetch_add(1, Ordering::Relaxed); // atomic add, claim slot immediately
buf[slot] = x; // write datafetch_addis wait-free (no retry), but not a complete queue. Bounded lock-free MPSC must also verify slot is free (consumer may not have taken previous round's data), requiring a CAS loop. Eight producers on same address: each CAS needs exclusive cache line, cores fight, CAS fails, retries, more coherence traffic. CAS contention produces microsecond tail latencies — spinning instead of kernel sleep.
Currently only C++ provides all four; Rust has only BQueue. Mailbox type chosen per actor at construction, before thread start. C++ uses std::variant of four concrete types (value-held, not base pointers), so hot-path push and dequeue loop have no virtual calls, can inline — mailbox choice adds zero per-message overhead. ShardedBQueue shard count set to expected producer count.
Benchmark Comparison
Methodology
Two machines:
Apple Silicon (macOS): batch dequeue, multi-producer push latency.
AMD EPYC 9374F server: 32 cores, 4 NUMA nodes, 8 CCDs (4 cores per CCD), hyperthreading on (64 hardware threads). Same CCD threads share L3; cross-CCD cache-line transfer via interconnect.
Each test run three times, median taken.
Batch Dequeue Throughput
Ping-pong test: each side bursts 10,000 messages, keeping both mailboxes full, 10M round-trips total. Experimental version (batch actor lock, notify only on empty→non-empty). C++ -O3.
Batch dequeue + memory pool combined: throughput from 5.52M to 13.6M round-trips/sec (2.46×). Rust similar (5.56M → 9.0M).
Batch dequeue alone: 1.63×. Saves two mailbox locks, two actor locks, two notifies per round-trip (~70 ns).
Memory pool alone: 1.50×. Messages allocated in one thread, freed in another; general allocator thread-caches ineffective; thread-local pool avoids global allocator on hot path.
Global-lock memory pool: throughput half of no-pool. Two threads contend on same lock every alloc/free.
Sender-side batching (construct + enqueue 10,000 messages under one lock): slower (13.6M → 11.3M). Sender holds lock entire construction, consumer can't start; pipeline broken.
Multi-Producer Push Latency
8 producers, each 1M push(), mailbox large enough to never block/overflow. Compare per-actor lock vs shared queue:
Both p50 = 42 ns. p99.9 differs ~184× (320 ns vs 59 µs). Shared queue: 1 in 1000 pushes ≥59 µs; per-actor lock: 320 ns. Median hides tail.
8 producers all writing same actor's mailbox, compare three mailboxes:
BQueue : p50 42 ns, p99.9 ~79 µs. 42 ns = uncontended atomic ops. 80 µs from thread sleep: two producers collide, loser spins briefly then syscall (macOS ulock, Linux futex), sleep/wake via kernel. ~1% of pushes lose and sleep.
LockFreeMPSC : p99.9 ~113 µs, worse than BQueue. Likely CAS contention on same cache line, retries.
Reduce to 2 producers:
LockFreeMPSC p99.9 417 ns, BQueue 4.3 µs. CAS rarely conflicts, no retries; producers don't sleep in kernel, tail latency flat. Lock-free advantage (no producer sleep) only holds when contention low enough that CAS rarely retries.
Pinning (taskset) Impact
EPYC server. Ping-pong: one message in flight, measure pure round-trip latency.
Unpinned: same program, same machine, median 1,470 ns; 30 sec later 7,010 ns (4.8×). Four mailboxes, three runs each:
Fastest mailbox varies per run; results split into two clusters (~3,500 ns and ~7,000 ns) randomly.
Pinned with taskset (each pinning three runs):
Same pinning: mailboxes differ 3–7%. Different pinning: same number varies 1,470 → 3,240 → ~7,000 ns. Pinning differences 2.2×; including unpinned slow cluster 4.8×. Thread placement matters far more than mailbox type.
Fastest: both threads on same core. With one message in flight, threads strictly alternate; one always blocked, no parallelism. Second core adds cross-core interrupt wakeup + cache-line transfer. Same-core context switch cheaper.
Cross-CCD and cross-NUMA rows still show two clusters — scheduler may still place both threads on one core or split them.
Pinning changes ranking: ShardedBQueue fastest on single core (1,470 vs BQueue 1,680, all three runs), but slowest on same physical core's two hyperthreads (SMT pair).
"Which mailbox has lowest single-message latency" is unanswerable — result dominated by thread placement. For latency-sensitive request-response, pinning beats mailbox choice.
Same-Thread (Group) Latency
Two actors in same Group: share thread and mailbox, single-threaded access, no contention, consumer never sleeps (always next message ready), no cross-core wakeup:
Same-thread round-trip ~21× faster than best cross-thread pinned (1,470 ns), ~50× faster than typical unpinned. Three runs stable. LockFreeMPSC fastest: single-threaded push / pop use few uncontended atomics, no mutex/condvar. BQueue still locks, unlocks, calls notify_one (wasted when consumer never sleeps). ShardedBQueue slowest: extra round-robin shard selection and atomic counter, no contention to amortize.
Only this test shows large, reproducible mailbox differences — single thread removes scheduler variability.
Lower bound: fast_send (direct call, no queue) averages 56 ns/msg. Cross-thread send ~7,209 ns (129×). Cross-thread varies 2.2× with pinning, so ratio approximate.
Backlog Throughput (16 In-Flight)
In-flight messages 1 → 16, mailbox stays full, consumer never waits for round-trip. One producer, amort = avg ns/msg:
16 messages overlapping: each takes ~8 µs end-to-end, but completes one every ~585 ns avg. Pipeline trades latency for throughput; speedup ≈ in-flight count.
ShardedBQueue 68% slower than BQueueBatched (slowest in all three runs). Sharding targets contention; single producer has none. Consecutive messages spread across 8 shards → consumer touches 8 cache lines instead of 1. BQueue and BQueueBatched indistinguishable (within 4%, trade leads).
Fan-In: 32 Producers → 1 Consumer
32 producers across all 8 CCDs and 4 NUMA nodes, all sending to same actor — the scenario for ShardedBQueue and lock-free. push p50/p99/p99.9 = contention send() (alloc + enqueue) latency; amort = end-to-end throughput:
ShardedBQueue wins every column, all three runs stable. Median ~1/5.5 of BQueue, p99 ~1/10.6, p99.9 ~1/8.6, throughput 3.6× BQueue. 32 shards = 32 locks, 32 threads spread, rarely collide; single mutex: 32 threads always conflict, losers sleep in kernel.
LockFreeMPSC clear second: p99 16 µs vs BQueue 70 µs. But most unstable row: p99.9 varies 30,540 → 55,270 ns (1.8×) across runs. Same in single-thread test: best p50, worst max.
BQueue raw best push 20 ns (uncontended). With 32 producers, that 20 ns becomes minimum; median rises to 12 µs because lock rarely free.
Selection Guide
Choose by producer count:
1 producer: BQueue or LockFreeMPSC — no contention to solve.
Few producers (2–4), jitter-sensitive: LockFreeMPSC — producers don't sleep, 2-producer p99.9 417 ns.
Many producers to one actor (fan-in): ShardedBQueue — reduces threads per sync point, lowest p99. Requires actor not depend on same-sender order, or order guaranteed higher up.
Many producers + jitter-sensitive: consider sharded mailbox with lock-free per shard (few producers per CAS cache line). Kaspar doesn't yet provide this.
Shard first; if a shard still contends, make it lock-free. Single lock-free queue becomes hotspot when producer count rises.
For most actors, mailbox type isn't critical. In three of four load profiles, best-to-worst mailbox gap is smaller than one taskset line or putting two actors in same thread. A timer-driven actor works fine with default.
For actors written by all producers, mailbox type can differ 10×. That actor's p99 matters most because fan-in peaks coincide with market events: open, large trades, price spikes. BQueue under this load: median 12 µs, p99 ~70 µs.
Order books are typical fan-in actors (multiple market-data threads push). But order books must apply increments in order; switching to ShardedBQueue requires upstream per-feed ordering guarantees.
Even best config shows occasional microsecond-to-millisecond spikes (p99.99+). Likely OS scheduler preempting thread mid- push for background tasks. User-space structures can't fix. Further reduction: real-time scheduling SCHED_FIFO, pin threads to dedicated cores, isolate cores via isolcpus kernel param.
Conclusion
Default mailbox is blocking BQueue: sleeps when idle, degrades smoothly under overload, never drops or reorders. Only fan-in hotspot actors warrant ShardedBQueue or lock-free mailboxes.
Project GitHub: https://github.com/vincent212/kaspar-hft
For questions about attribution, corrections or content rights, please contactand we will review it promptly.