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.
| Operation | Action | Time complexity |
|---|---|---|
| Enqueue (push) | Write at head, advance head | O(1) |
| Dequeue (pop) | Read at tail, advance tail | O(1) |
| Peek | Read at tail without advancing | O(1) |
| Size | Compute distance from tail to head | O(1) |
| Random access by offset | Read at (tail + i) % N | O(1) |
| Resize | Allocate new array and copy in order | O(n) |
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.
| Strategy | How it works | Trade-off |
|---|---|---|
| Leave one slot empty | Full when the next head would equal tail | Usable capacity is N minus 1 |
| Separate count field | Track the number of stored items | Extra variable shared by producer and consumer |
| Full flag | Boolean set when head catches tail | Extra branch on every operation |
| Free-running counters | Indices grow without wrapping; mask on access | Needs power-of-two capacity and overflow-safe math |
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.
Comparison with related queue structures
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.
| Structure | Capacity | Memory layout | Typical use |
|---|---|---|---|
| Circular buffer | Fixed | Contiguous array | Streaming, bounded queues, real-time systems |
| Linked-list queue | Unbounded | Scattered nodes | General queues with unpredictable size |
| Dynamic array queue | Grows | Contiguous, occasional copies | Simple queues where shifting is acceptable |
| Deque | Usually grows | Ring or block list | Insertion and removal at both ends |
| Priority queue | Varies | Heap array | Ordering by priority, not arrival |
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.
| Model | Synchronization | Complexity |
|---|---|---|
| SPSC | Atomic indices, acquire and release | Low |
| MPSC | Atomic compare-and-swap on head | Moderate |
| MPMC | Per-slot sequence numbers or locks | High |
| Mutex-protected | Single lock around all operations | Low, but limited throughput |
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.
| Symptom | Likely cause | Fix |
|---|---|---|
| Buffer reports empty when full | Ambiguous head equals tail | Adopt one detection strategy consistently |
| Corrupted items under load | Missing memory barriers | Use atomic indices with acquire and release |
| Wrong size after overflow | Signed counter arithmetic | Use unsigned counters and masking |
| Slow modulo in hot loop | Non-power-of-two capacity | Round capacity up and mask |
| Throughput collapse on multicore | False sharing of indices | Pad indices to separate cache lines |
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.