Skip to main content

A Lock-Free SPSC Ring Buffer in Rust: Memory Ordering Explained

Updated 5 min readMarkdown

A single-producer, single-consumer (SPSC) queue is the simplest useful lock-free structure. Because exactly one thread writes and exactly one thread reads, you can build it from two atomic counters and no compare-and-swap loops. This post walks through a bounded ring buffer in Rust, and explains why each memory ordering is the one it is.

Design

The buffer has a power-of-two capacity, so an index can be turned into a slot with a bit mask instead of a modulo. Two counters grow monotonically and wrap only at the integer limit:

  • tail is the next slot the producer will write. Only the producer stores to it.

  • head is the next slot the consumer will read. Only the consumer stores to it.

The queue is empty when head == tail and full when tail.wrapping_sub(head) == capacity. Using monotonically growing counters, rather than counters kept below the capacity, removes the classic "one slot always empty" workaround, since full and empty produce different values.

The code

use std::cell::UnsafeCell;
use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicUsize, Ordering::{Acquire, Relaxed, Release}};
use std::sync::Arc;

struct Ring<T> {
    buf: Box<[UnsafeCell<MaybeUninit<T>>]>,
    mask: usize,
    head: AtomicUsize, // written only by the consumer
    tail: AtomicUsize, // written only by the producer
}

unsafe impl<T: Send> Send for Ring<T> {}
unsafe impl<T: Send> Sync for Ring<T> {}

pub struct Producer<T>(Arc<Ring<T>>);
pub struct Consumer<T>(Arc<Ring<T>>);

pub fn channel<T>(capacity: usize) -> (Producer<T>, Consumer<T>) {
    let cap = capacity.max(1).next_power_of_two();
    let buf = (0..cap)
        .map(|_| UnsafeCell::new(MaybeUninit::uninit()))
        .collect();
    let ring = Arc::new(Ring {
        buf,
        mask: cap - 1,
        head: AtomicUsize::new(0),
        tail: AtomicUsize::new(0),
    });
    (Producer(ring.clone()), Consumer(ring))
}

impl<T> Producer<T> {
    pub fn push(&mut self, value: T) -> Result<(), T> {
        let r = &*self.0;
        let tail = r.tail.load(Relaxed);
        let head = r.head.load(Acquire);
        if tail.wrapping_sub(head) == r.buf.len() {
            return Err(value); // full
        }
        unsafe { (*r.buf[tail & r.mask].get()).write(value); }
        r.tail.store(tail.wrapping_add(1), Release);
        Ok(())
    }
}

impl<T> Consumer<T> {
    pub fn pop(&mut self) -> Option<T> {
        let r = &*self.0;
        let head = r.head.load(Relaxed);
        let tail = r.tail.load(Acquire);
        if head == tail {
            return None; // empty
        }
        let value = unsafe { (*r.buf[head & r.mask].get()).assume_init_read() };
        r.head.store(head.wrapping_add(1), Release);
        Some(value)
    }
}

impl<T> Drop for Ring<T> {
    fn drop(&mut self) {
        let (mut h, t) = (*self.head.get_mut(), *self.tail.get_mut());
        while h != t {
            unsafe { (*self.buf[h & self.mask].get()).assume_init_drop(); }
            h = h.wrapping_add(1);
        }
    }
}

Why these orderings

Each side reads its own counter with Relaxed. Nobody else writes it, so the thread always sees its own latest store and needs no synchronization with itself.

The producer writes the slot first and then publishes it with a Release store to tail. The consumer reads tail with Acquire. If the consumer observes the new tail value, the release/acquire pair guarantees it also observes the slot write that happened before the store. Without that pairing, the consumer could see the incremented counter and read stale or uninitialized memory.

The same reasoning runs the other way for head. The consumer moves the value out, then releases head. The producer acquires head before deciding a slot is free, so it cannot overwrite a value the consumer is still reading.

Why the API is shaped this way

The safety argument depends on there being exactly one producer and one consumer. Rust can enforce that in the type system. Producer and Consumer are not Clone, and push and pop take &mut self, so safe code cannot create a second writer or reader. Both handles are Send when T: Send (through the Arc), so you can move each to its own thread.

Things to watch

  • False sharing. head and tail sit next to each other and are written by different cores, so they can share a cache line and bounce between cores. Padding each to its own cache line often helps, and you should measure on your hardware before assuming it does.

  • Cached counters. The producer can keep a local copy of head and reload it only when the queue looks full, which cuts cross-core traffic. The consumer can do the same with tail.

  • Testing. Ordinary tests rarely expose ordering bugs. Run the queue under a model checker such as loom, and under Miri to catch undefined behavior in the unsafe blocks.

  • Element drops. The Drop impl drains items that were pushed but never popped. Leaving that out leaks any owned values still in the queue.

Summary

Two counters, one writer each, and a release/acquire pair around the slot access are enough for a correct bounded SPSC queue. The interesting part is not the code but the argument about who may write what, and the type system can carry most of that argument for you.


About the author: I work on the web platform at eSIMCircle, a travel eSIM provider. This post is a side note from the engineering side, not about the product.

2 views

About the author

  • eSIMCircle provides affordable global eSIM plans with reliable data in 200+ countries.

No comments yet. Be the first to comment.

More from this blog