Circular buffer

Also known as: ring buffer

On this page 8

A circular buffer, also called a ring buffer, is a fixed-capacity array whose end is logically joined to its beginning, so that read and write positions wrap around instead of running off the end. Among data structures in programming, it is the standard way to implement a bounded first-in, first-out (FIFO) queue with constant-time insertion and removal and no data movement.

Circular buffers appear wherever a producer and a consumer exchange a stream of items at different speeds: audio and network drivers, logging systems, serial ports, inter-thread message passing and sliding-window computations. Their appeal lies in predictable memory use and cache-friendly sequential access.

How a circular buffer wraps its indices

A circular buffer consists of a contiguous block of storage with a capacity N and two indices: the head, where the next item is written, and the tail, where the next item is read. After each operation the relevant index advances by one and wraps to zero when it reaches N, which is computed as (index + 1) % N.

Because elements never shift, both enqueue and dequeue run in O(1) time. The structure behaves as if the array were bent into a ring, while in memory it remains an ordinary array. When the capacity is a power of two, the modulo operation can be replaced by a bitwise AND with N minus 1, which is cheaper on most processors.

The table below lists the basic operations and their cost.

OperationActionTime complexity
Enqueue (push)Write at head, advance headO(1)
Dequeue (pop)Read at tail, advance tailO(1)
PeekRead at tail without advancingO(1)
SizeCompute distance from tail to headO(1)
Random access by offsetRead at (tail + i) % NO(1)
ResizeAllocate new array and copy in orderO(n)
Circular buffer operations and complexity

Telling a full buffer from an empty one

The classic difficulty is that head equals tail both when the buffer is empty and when it is full, so an implementation needs one extra rule to distinguish the two states. Every serious implementation chooses one of the strategies below, and mixing strategies is a common source of bugs.

StrategyHow it worksTrade-off
Leave one slot emptyFull when the next head would equal tailUsable capacity is N minus 1
Separate count fieldTrack the number of stored itemsExtra variable shared by producer and consumer
Full flagBoolean set when head catches tailExtra branch on every operation
Free-running countersIndices grow without wrapping; mask on accessNeeds power-of-two capacity and overflow-safe math
Strategies for detecting full and empty states

The free-running counter approach is popular in high-performance and lock-free code: size equals head minus tail using unsigned arithmetic, which remains correct even when the counters overflow, provided the capacity divides the integer range.

Overwrite and reject policies

When a producer writes to a full buffer, the implementation must apply an explicit overflow policy. The choice depends on whether old data or new data matters more to the application.

  • Overwrite oldest: the head advances over the tail and the oldest item is lost, which suits telemetry, logs and audio monitoring where only recent history matters.
  • Reject or drop newest: the write fails and the caller decides what to do, which suits command queues where every accepted item must be processed.
  • Block the producer: the writer waits until space frees up, providing natural back-pressure in bounded producer-consumer pipelines.
  • Grow the buffer: a dynamic variant reallocates, which removes the fixed-memory guarantee and turns the structure into a deque.

A buffer used as a last-N history, such as the most recent 1,000 log lines, almost always overwrites. A buffer used for reliable delivery should never overwrite silently.

A circular buffer is one of several ways to implement a queue, and its strengths become clear next to the alternatives from the same family of data structures.

StructureCapacityMemory layoutTypical use
Circular bufferFixedContiguous arrayStreaming, bounded queues, real-time systems
Linked-list queueUnboundedScattered nodesGeneral queues with unpredictable size
Dynamic array queueGrowsContiguous, occasional copiesSimple queues where shifting is acceptable
DequeUsually growsRing or block listInsertion and removal at both ends
Priority queueVariesHeap arrayOrdering by priority, not arrival
Circular buffer compared with neighboring structures

Compared with a linked list, a ring buffer avoids per-node allocation and pointer chasing, which improves cache locality and eliminates allocator latency. Many standard library deques, such as Rust’s VecDeque and Java’s ArrayDeque, are in fact growable circular buffers internally.

Concurrent and lock-free ring buffers

With exactly one producer and one consumer (SPSC), a circular buffer can be made lock-free because each index is written by only one thread. The producer updates the head, the consumer updates the tail, and each reads the other’s index to check for space or data.

Correctness then depends on memory ordering. The producer must write the item before publishing the new head with release semantics, and the consumer must read the head with acquire semantics before reading the item. Placing head and tail on separate cache lines prevents false sharing, which otherwise degrades throughput significantly.

The following table summarizes concurrency configurations.

ModelSynchronizationComplexity
SPSCAtomic indices, acquire and releaseLow
MPSCAtomic compare-and-swap on headModerate
MPMCPer-slot sequence numbers or locksHigh
Mutex-protectedSingle lock around all operationsLow, but limited throughput
Concurrency models for ring buffers

Well-known designs include the LMAX Disruptor, which uses a pre-allocated ring with sequence counters, and the Linux kernel’s io_uring, whose submission and completion queues are shared-memory ring buffers between user space and the kernel.

Common mistakes when implementing a ring buffer

Most defects in circular buffers come from index arithmetic and concurrency assumptions, not from the concept itself. The table pairs frequent symptoms with their causes.

SymptomLikely causeFix
Buffer reports empty when fullAmbiguous head equals tailAdopt one detection strategy consistently
Corrupted items under loadMissing memory barriersUse atomic indices with acquire and release
Wrong size after overflowSigned counter arithmeticUse unsigned counters and masking
Slow modulo in hot loopNon-power-of-two capacityRound capacity up and mask
Throughput collapse on multicoreFalse sharing of indicesPad indices to separate cache lines
Typical ring buffer bugs

Understanding it simply

A circular buffer works like a round table with a fixed number of seats. One person keeps placing plates in the next free seat, going around the table, while another person picks plates up in the same order.

When the placer gets back to the first seat, it simply continues around again. Nothing is ever moved, so the work stays fast. The only rule is deciding what happens when every seat is taken: either wait, refuse the new plate or replace the oldest one.

Applied in practice

An embedded engineer designs firmware for an industrial vibration sensor that samples an accelerometer at 10 kHz. An interrupt routine reads each sample and must finish within microseconds, while the main loop computes a frequency analysis on blocks of 1,024 samples.

The engineer allocates a 4,096-sample ring buffer in static memory with free-running unsigned counters and a mask. The interrupt routine acts as the single producer and the main loop as the single consumer, so no locks are required. When the network link stalls, the policy overwrites the oldest samples, because only recent vibration matters for fault detection.

The result is a system with fixed memory use and no dynamic allocation, which passes the timing requirements of the control system and has never lost an interrupt deadline in field testing.