Skip to content
Techniques & Technology

Ring Buffer

Circular data, fixed memory

A fixed-size data structure that wraps around, enabling efficient FIFO queues without memory allocation—essential for audio, networking, and game mechanics like snake tails.

cross-platform data-structureaudionetworkingmemorysnake

Overview

A ring buffer (circular buffer) is a fixed-size array that wraps around from end to beginning, treating the storage as a continuous loop. It enables efficient first-in-first-out (FIFO) operations without memory allocation, making it essential for audio processing, network packets, and game mechanics like snake body segments.

Fast Facts

AspectDetail
Also calledCircular buffer, cyclic buffer
OperationsO(1) read, O(1) write
MemoryFixed, pre-allocated
Common usesAudio, networking, input history

How It Works

PointerPurpose
Head (write)Where new data goes
Tail (read)Where old data comes from
WrapWhen pointer exceeds size, reset to 0
Buffer: [A][B][C][D][E][F][G][H]
         ^tail          ^head

Write X: [X][B][C][D][E][F][G][H]
            ^tail          ^head (wrapped)

Implementation

OperationLogic
Writebuffer[head] = value; head = (head + 1) % size
Readvalue = buffer[tail]; tail = (tail + 1) % size
Full(head + 1) % size == tail
Emptyhead == tail

Gaming Applications

Snake Body

FrameHead PositionTail Position
1Write new headRead (remove) old tail
2Write new headRead old tail
GrowWrite new headDon’t read tail

The snake’s body is naturally a ring buffer of positions.

Input Replay

UseBenefit
Fighting gamesStore last N inputs for combos
ReplaysRecord input history
Undo systemsFixed-depth undo stack
Ghost racingStore position history

Audio

ApplicationWhy Ring Buffer
StreamingProducer/consumer decoupling
EffectsDelay lines are ring buffers
MixingLock-free audio threads

Vintage Implementation (6502)

On limited hardware, the power-of-two trick avoids division:

Buffer SizeWrap Method
256 bytesNatural 8-bit overflow
128 bytesAND #$7F
64 bytesAND #$3F

Using AND instead of modulo is much faster.

Modern Applications

SystemUsage
FMOD/WwiseAudio streaming buffers
TCP/IP stacksPacket receive buffers
GGPO (rollback)Input history for netcode
LoggingCircular log files

Lock-Free Benefits

Ring buffers enable lock-free producer/consumer patterns:

  • Audio thread writes, main thread reads
  • Network thread writes, game thread reads
  • No mutexes needed with single producer/consumer

Trade-offs

AdvantageDisadvantage
No allocationFixed maximum size
O(1) operationsCan overflow if full
Cache-friendlyMust handle wrap-around
Lock-free possiblePower-of-two size optimal

Legacy

Ring buffers appear everywhere in systems programming. Understanding them connects game development to audio engineering, networking, and operating systems—fundamental computer science in action.

See Also