Sub topic 13
A Single-Producer Single-Consumer Ring Buffer
This chapter assumes you have read the earlier chapters on Atomics.load, Atomics.store, Atomics.wait, Atomics.notify, and the happens-before guarantee. You should also know how to start a Node.js worker thread and pass it a SharedArrayBuffer.
A ring buffer is a fixed-size queue stored in a circular array. A single-producer single-consumer (SPSC) ring buffer has exactly one thread writing and exactly one thread reading. With that restriction it needs no lock. Each index has a single writer, so no thread ever needs compareExchange. This makes the SPSC ring the most common shared-memory structure in real JavaScript code, for example in audio worklets that stream samples or in WebAssembly threads that pass work items.
The Working Model
The buffer lives in one SharedArrayBuffer that holds two regions:
- A header of two
Int32slots:head(the next slot to read) andtail(the next slot to write). - A data region of
capacityInt32slots.
The ownership rules make the design safe:
| Field | Written by | Read by | How it is accessed |
|---|---|---|---|
| `tail` | Producer only | Both | `Atomics.load` / `Atomics.store` |
| `head` | Consumer only | Both | `Atomics.load` / `Atomics.store` |
| `data[i]` | Producer, before publishing `i` | Consumer, after seeing `i` published | Plain typed-array access |
The buffer is empty when head === tail. It is full when advancing tail by one would make it equal head. This "one empty slot" convention means a buffer with capacity slots holds at most capacity - 1 items. You give up one slot so that you can tell full from empty without a separate counter that both threads would have to write.
Why Plain Data Access Is Safe Here
The data slots are read and written without Atomics, but this is not a data race. The producer writes data[t] and then performs an atomic store to tail. The consumer performs an atomic load of tail, sees the new value, and only then reads data[t]. Sequentially consistent atomics create a happens-before edge from the store to the load that observes it. Every write the producer made before the store is therefore visible to the consumer after the load.
The same reasoning applies in reverse for head. The consumer finishes reading data[h] before it stores the new head, so the producer cannot overwrite that slot while the consumer is still reading it.
This only holds if the order inside each thread is right. If the producer stored tail first and wrote the data second, the consumer could read a stale slot.
The Implementation
The program below is a complete Node.js script. The main thread produces the numbers 0 to 999, and a worker consumes them and reports their sum. Save it as ring.js and run node ring.js.
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
const HEAD = 0;
const TAIL = 1;
const HEADER_BYTES = 8;
class SpscRing {
static bytesFor(capacity) {
return HEADER_BYTES + capacity * Int32Array.BYTES_PER_ELEMENT;
}
constructor(sab, capacity) {
this.header = new Int32Array(sab, 0, 2);
this.data = new Int32Array(sab, HEADER_BYTES, capacity);
this.capacity = capacity;
}
// Producer only. Blocks while the buffer is full.
push(value) {
const h = this.header;
const tail = Atomics.load(h, TAIL);
const next = (tail + 1) % this.capacity;
for (;;) {
const head = Atomics.load(h, HEAD);
if (next !== head) break;
// Sleep only while head still equals the value that made us full.
Atomics.wait(h, HEAD, head);
}
this.data[tail] = value; // 1. write the payload
Atomics.store(h, TAIL, next); // 2. publish it
Atomics.notify(h, TAIL, 1); // 3. wake the consumer if asleep
}
// Consumer only. Blocks while the buffer is empty.
pop() {
const h = this.header;
const head = Atomics.load(h, HEAD);
for (;;) {
const tail = Atomics.load(h, TAIL);
if (tail !== head) break;
// Sleep only while tail still equals the value that made us empty.
Atomics.wait(h, TAIL, tail);
}
const value = this.data[head]; // 1. read the payload
Atomics.store(h, HEAD, (head + 1) % this.capacity); // 2. free the slot
Atomics.notify(h, HEAD, 1); // 3. wake the producer if asleep
return value;
}
}
const CAPACITY = 8;
const COUNT = 1000;
const DONE = -1;
if (isMainThread) {
const sab = new SharedArrayBuffer(SpscRing.bytesFor(CAPACITY));
const ring = new SpscRing(sab, CAPACITY);
const worker = new Worker(__filename, { workerData: sab });
worker.on('message', (sum) => console.log('sum:', sum)); // sum: 499500
for (let i = 0; i < COUNT; i++) ring.push(i);
ring.push(DONE);
} else {
const ring = new SpscRing(workerData, CAPACITY);
let sum = 0;
for (;;) {
const value = ring.pop();
if (value === DONE) break;
sum += value;
}
parentPort.postMessage(sum);
}The main thread starts pushing before the worker has even started. After seven items the buffer is full, so push sleeps on HEAD. When the worker starts and pops its first item, it stores a new head and notifies, and the producer continues. Node.js allows Atomics.wait on its main thread, which is why this example can block there.
Common Errors
Waiting on a freshly loaded value
The most common bug is to reload the index right before waiting:
// Buggy consumer wait
if (Atomics.load(h, HEAD) === Atomics.load(h, TAIL)) {
Atomics.wait(h, TAIL, Atomics.load(h, TAIL)); // third load may see a NEW tail
}If the producer publishes between the emptiness check and the third load, the consumer waits on the new tail value. The buffer now holds an item, but the consumer sleeps until the next push, and if no push comes it never wakes. The correct code passes Atomics.wait the exact value that showed the buffer was empty. If the value has changed since then, wait returns 'not-equal' immediately and the loop checks again.
Breaking the single-writer rule
Two producers sharing one ring will both read the same tail, both write the same slot, and both store the same next. One item is silently lost. If you need several producers, use one ring per producer, or move to a multi-producer design built on compareExchange.
Forgetting that `capacity - 1` is the real limit
A ring of capacity 1 can never hold anything: next always equals head, so push blocks forever. Size the ring as the item count you need plus one.
Notifying the wrong index
The consumer sleeps on TAIL, so the producer must notify TAIL. Notifying HEAD after a push wakes nobody useful and leaves the consumer asleep.
Design Edge Cases and Trade-offs
The cost of notifying every time
Atomics.notify is cheap when nobody is waiting, but it still costs more than a plain store. High-throughput rings often add a third header slot that the consumer sets to 1 just before it sleeps, and the producer calls notify only when that slot is 1. This cuts the per-item cost, but it adds an ordering rule: the consumer must set the flag and then re-check tail before waiting, or it can miss a wake-up.
Batching
Pushing one Int32 at a time means one atomic store and one notify per item. If you write a batch of items and then publish tail once, many items cost a single synchronization step. The consumer can do the same by reading everything between head and tail before storing head.
Variable-size messages
The ring above carries fixed-size integers. To send strings or structured records, encode them into a Uint8Array data region with a length prefix. You also need to handle a record that would straddle the end of the array, either by splitting it across the boundary or by writing a padding marker and wrapping to index 0.
Free-running counters
Some implementations never take % capacity on the stored indices. They let head and tail grow and compute tail - head for the item count. With a power-of-two capacity, the slot is index & (capacity - 1). This uses every slot, but you must make sure Int32 wraparound (at 2³¹) still gives correct differences. Applying | 0 to the difference does this, because the subtraction then wraps modulo 2³².
Exercise
A teammate changes push so that it runs Atomics.store(h, TAIL, next) first and only then this.data[tail] = value. Tests pass on their machine. What can go wrong, and why might tests not catch it?
Show answer
The consumer can observe the new tail, read data[tail] before the producer has written it, and return a stale or zero value. The atomic store of tail is what publishes the slot, so any data written after it is not covered by the happens-before edge. The bug only shows up when the consumer runs between the two producer statements, so it depends on timing and can stay hidden in small or lightly loaded tests.
Exercise
You need to pass 100 items at a time between two threads without the producer ever blocking. What is the minimum capacity of this ring, and why?
Show answer
101. The one-empty-slot convention means a ring of capacity N holds at most N - 1 items, so holding 100 items at once needs a capacity of 101.
Exercise
Why does this design never need Atomics.compareExchange, while a mutex does?
Show answer
Each index has exactly one writer: only the producer stores tail and only the consumer stores head. No two threads ever try to change the same slot, so a plain atomic store is enough. A mutex has several threads competing to change the same lock word, which needs an atomic check-and-set.