Sub topic 10
Where ring buffers are used
This chapter assumes you know how head and tail indices work, how modulo wraparound works, and the difference between rejecting and overwriting when the buffer is full. It shows where those choices appear in real systems.
What these systems have in common
Ring buffers fit problems with three traits:
- Data arrives as a stream and is consumed in order (FIFO).
- The amount of memory must be fixed and known ahead of time.
- Operations must take constant time, with no allocation on the hot path.
The use cases differ mainly in two decisions: what happens when the buffer is full, and whether one or several threads touch it.
Common applications
| Application | Producer and consumer | Policy when full | Why a ring fits |
|---|---|---|---|
| Serial port or UART receive buffer | Interrupt handler writes, main loop reads | Reject (drop new byte, set an error flag) | Fixed RAM, no allocation inside an interrupt |
| Audio playback and capture | Driver thread and application thread | Reject or pause: gaps or glitches are audible | Steady stream, constant-time operations |
| Network packet queues | Network card writes, kernel reads | Reject (drop packets) | Fixed descriptor count, no per-packet allocation |
| Log or telemetry history | Application writes, a debugger reads on demand | Overwrite oldest | Only recent events matter |
| Moving average over the last N samples | Same thread | Overwrite oldest | The window is the buffer |
| Keyboard input and pipes | Device or process writes, another reads | Reject or block the writer | Bounded memory |
Reject or overwrite: matching the policy to the data
Choose reject when every item matters and the producer can react, for example by retrying or applying backpressure. A UART driver cannot ask the sender to slow down, so it drops the byte and records an error. The error flag tells the program that data was lost.
Choose overwrite when only recent data has value. A flight recorder that keeps the last 1,000 events is useful because it holds the moments before a crash. Keeping the oldest events would defeat its purpose.
The overwrite helper from earlier in this tutorial shows the pattern for a moving average:
class RingBuffer:
def __init__(self, capacity):
self._buf = [None] * capacity
self._head = 0
self._count = 0
def __len__(self):
return self._count
def push(self, item):
if self._count == len(self._buf):
raise OverflowError("buffer full")
tail = (self._head + self._count) % len(self._buf)
self._buf[tail] = item
self._count += 1
def pop(self):
if self._count == 0:
raise IndexError("buffer empty")
item = self._buf[self._head]
self._buf[self._head] = None
self._head = (self._head + 1) % len(self._buf)
self._count -= 1
return item
def items(self):
return [self._buf[(self._head + i) % len(self._buf)]
for i in range(self._count)]
def push_overwrite(rb, item):
if len(rb) == len(rb._buf):
rb.pop()
rb.push(item)
window = RingBuffer(3)
for sample in [10, 20, 30, 40, 50]:
push_overwrite(window, sample)
values = window.items()
print(values, sum(values) / len(values))The last line printed is [30, 40, 50] 40.0. The buffer never grows, and the average always covers the latest three samples.
Shapes of concurrency
Where the buffer sits in a system also determines how it must be protected:
- Same thread only, such as the moving average: no protection is needed.
- One producer thread and one consumer thread, such as audio or a network driver: a lock-free design with acquire and release ordering works, as a later chapter explains.
- Several producers or several consumers: the single-writer rule for each index no longer holds, so you need a lock or a more complex algorithm.
An interrupt handler and the main loop on a microcontroller behave like a producer and consumer pair. Even without two threads, the same single-writer discipline applies.
A decision checklist
- Does losing old data hurt, or losing new data? That answer picks overwrite or reject.
- Can the producer slow down or wait? If yes, reject plus backpressure is usually better than silent loss.
- How many threads write, and how many read? That answer picks no lock, a lock-free single-producer, single-consumer design, or a lock.
- Is the capacity a power of two? If so, a bit mask can replace modulo.
Exercise
A device records temperature readings every second and keeps them in a ring buffer of 600 slots so an engineer can inspect the last ten minutes after a fault. Should the buffer reject or overwrite when full, and why?
Show answer
Overwrite the oldest. The engineer wants the most recent ten minutes, so discarding the oldest reading is correct. Rejecting new readings would freeze the buffer on stale data and lose the period right before the fault.
Exercise
Two worker threads both push events into one ring buffer, and one thread pops them. Why is the lock-free single-producer, single-consumer design unsafe here?
Show answer
That design relies on each index having exactly one writer. With two producers, both write the tail index and the slot at that index, so they can read the same tail value and overwrite each other's item. You need a lock or a multi-producer algorithm.