Internals

raftdb-spsc, the cross-core message ring

The lock-free single-producer single-consumer ring used to model thread-per-core hand-off, its memory ordering, API and measured speed.

raftdb-spsc hands Copy messages from one producer thread to one consumer thread without locks. It uses only the standard library. The design follows the thread-per-core study.

Design#

  • A ring of 2^k slots stored inline as UnsafeCell<MaybeUninit<T>>.
  • Two positions that only grow (usize, wrapping): tail, written by the producer, and head, written by the consumer. Item p lives in slot p & mask. The ring is empty when head == tail and full when tail - head == capacity.
  • head and tail sit in separate 128-byte aligned cells so the two cores never share a cache line. Each side keeps its own position privately plus a cached copy of the other side's and loads the other side's atomic only when the ring looks full or empty.
  • Memory ordering: the producer writes slots, then stores tail with Release; the consumer loads tail with Acquire, reads slots, then stores head with Release; the producer loads head with Acquire before reusing a slot.

API#

CallBehaviour
channel::<T>(capacity)Returns (Producer, Consumer); capacity is rounded up to a power of two (minimum 2).
Producer::try_push(v)Writes v without publishing; false if full.
Producer::publish()Makes everything written so far visible with one atomic store.
Producer::push(v)try_push then publish.
Consumer::pop_batch(&mut [T])Takes up to len items with at most one atomic load and one store.
Consumer::pop()One item.

Producer and Consumer are not Clone, which enforces one producer and one consumer. T must be Copy + Send, so nothing needs dropping and no ownership moves.

Safety#

unsafe appears in four places (the slot write, the slot read in two methods, and Sync for the shared state); each has a safety comment stating the protocol above.

Measured#

319 M messages per second one way (batches of 16); 171 ns mean round trip; routed point reads 41.6 M/s with 4 clients and 4 shards. The shard benchmark suite uses it to model the thread-per-core design; the server itself uses bounded channels today (raftdb-server).

Open#

loom model checking; thread pinning and NUMA placement.