Ring buffer

A fixed-size array whose read and write positions wrap around the end, giving an O(1) queue with no allocation: ideal for streams, logs and recent history.

Description

A ring buffer is an array of fixed capacity used as a queue. A write index (the tail) marks where the next item goes, a read index (the head) marks the oldest item. Both move forward and wrap around to index 0 when they reach the end, so the array behaves like a circle.

Because the memory is allocated once and never moves, ring buffers are predictable and fast, with no garbage and no resizing. That's why they appear in audio and video pipelines, network drivers, logging systems, metrics windows ("the last 60 seconds") and producer–consumer queues between threads.

When the buffer is full you have to choose: reject new items (applying back-pressure to the producer), or overwrite the oldest (keeping only the most recent history). Both are common; the right one depends on whether losing old data is acceptable.

How it works

410421234375386407tailhead

Capacity 8 with 5 items. The tail has wrapped around past the end.

  1. index 0: 41
  2. index 1: 42
  3. index 2:
  4. index 3:
  5. index 4:
  6. index 5: 37
  7. index 6: 38
  8. index 7: 40
Capacity 8 with 5 items. The tail has wrapped around past the end.

Complexity

OperationAverageWorst
Write (enqueue)O(1)O(1)
Read (dequeue)O(1)O(1)
Access the i-th oldest itemO(1)O(1)

Space: O(capacity), allocated once

No allocation after creation also means no garbage-collection pauses, which matters in latency-sensitive code.

TypeScript implementation

A ring buffer that keeps the last N values and can compute their average: a typical metrics window.

ring-buffer.ts
// A fixed-size ring buffer that overwrites the oldest value when full.
// Used here as a moving window: the average of the last N measurements.

export class RingBuffer {
  private buf: Float64Array;
  private head = 0; // oldest value
  private count = 0;
  overwritten = 0;

  constructor(capacity: number) {
    this.buf = new Float64Array(capacity);
  }

  get size(): number {
    return this.count;
  }

  push(v: number): void {
    const tail = (this.head + this.count) % this.buf.length;
    this.buf[tail] = v;
    if (this.count < this.buf.length) this.count++;
    else {
      this.head = (this.head + 1) % this.buf.length; // full: drop the oldest
      this.overwritten++;
    }
  }

  shift(): number | undefined {
    if (!this.count) return undefined;
    const v = this.buf[this.head];
    this.head = (this.head + 1) % this.buf.length;
    this.count--;
    return v;
  }

  toArray(): number[] {
    return Array.from({ length: this.count }, (_, i) => this.buf[(this.head + i) % this.buf.length]);
  }

  average(): number {
    return this.count ? this.toArray().reduce((a, b) => a + b, 0) / this.count : 0;
  }
}

export function demo(): string[] {
  const latency = new RingBuffer(4); // keep the last 4 response times
  const lines: string[] = [];
  for (const ms of [120, 80, 95, 110, 300, 90]) {
    latency.push(ms);
    lines.push(`+${ms} ms → window [${latency.toArray().join(", ")}], average ${latency.average().toFixed(1)}`);
  }
  lines.push(`overwritten: ${latency.overwritten}`);
  return lines;
}

When to use it

Use it when

  • You need a bounded queue or the last N items: recent log lines, moving averages, rate limiting.
  • Streaming data between a producer and a consumer at different speeds.
  • Real-time or embedded systems where allocation must be avoided.

Avoid it when

  • The number of items is unbounded and you can't drop any: use a growable deque.
  • You need to search or insert in the middle.

Pitfalls

  • Telling full from empty: if head equals tail, the buffer could be either. Keep a separate count, or leave one slot unused.
  • Off-by-one wrap-around errors in the modulo arithmetic.
  • Silently overwriting data when the consumer falls behind, without anyone noticing. Count overwrites.
  • Concurrency: single-producer, single-consumer ring buffers can be lock-free, but multiple producers need careful synchronization.

Alternatives

Deque

Choose it when the queue must grow without limit.

Dynamic array

Choose it when you keep everything and only append.