SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Inverted Index
  • Trie (Prefix Tree)
  • LRU Cache Design
  • Heap and Priority Queue
  • Bitmaps and Roaring Bitmaps
  • Ring Buffer
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Data Structures for Scale

Ring Buffer

A fixed-size queue that wraps around and overwrites the oldest data. Fast, simple and never grows.

⏱ 11 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A ring buffer (or circular buffer) is a fixed-size queue stored in an array. Two numbers, a head (where to read) and a tail (where to write), move forward and wrap around to the start when they reach the end. It never grows and never shifts items.

  • Write: put the item at tail, then tail = (tail + 1) % size.
  • Read: take the item at head, then head = (head + 1) % size.
  • When full: either overwrite the oldest item, or reject / wait. You must pick one.

02Concept: What is it?

A normal queue that grows needs memory to be allocated and freed, and a simple array queue has to shift every item forward each time you remove one. A ring buffer avoids both. It reserves N slots once and then reuses them in a circle. When the writer reaches the last slot, the next write goes back to slot 0, because the reader has probably already freed it.

The wrap-around comes from the modulo operator: (i + 1) % N turns N into 0. If N is a power of two (8, 16, 1024...), the computer can replace the slow modulo with a fast bit mask: i & (N − 1).

Head and tail chase each other round a circle
✍️Producerwrites at tail
→↓slot by slot
⭕N slots in a ringhead → … → tail
→↓slot by slot
📖Consumerreads at head
Items between head and tail are waiting. The rest of the slots are free.

Full or empty? Same pointers, two meanings

When head == tail, the buffer could be completely empty or completely full, because both pointers are in the same place. There are three common fixes: keep a separate count, keep a one-slot gap (the buffer is full when tail + 1 == head, so one slot is always unused), or let the pointers count up forever and only use modulo when indexing (then full is tail − head == N).

🧠You must choose a full policy
When the buffer is full there are only two honest answers: drop the oldest (good for logs, metrics and video, where recent data matters most), or refuse the new item and make the writer wait or fail (good when no item may be lost).

03Real-Life Example

🍵The Sushi Conveyor Belt
A sushi bar has a belt with 12 plates and a loop that goes round and round. The chef puts a plate on the next free spot. A customer takes the plate in front of them. Nothing is moved, and the belt never gets longer. If the chef is faster than the customers, the belt fills up. Then the chef must either wait (reject) or slide a new plate on top of the oldest one (overwrite).
Sushi belt
Ring buffer
12 spots on the belt
N slots in an array
Chef puts a plate on the next free spot
Write at tail, advance tail
Customer takes the next plate
Read at head, advance head
The belt is a loop
Index wraps with modulo
The belt never gets longer
Fixed size, no allocation
Chef waits for space
Reject / block when full
Chef replaces the oldest plate
Overwrite when full

04Why Do We Need It?

🚀Constant time
Read and write are each O(1). No shifting, no searching.
📏Fixed memory
Allocated once, so there is no growth and no garbage to clean up while it runs.
🧊Cache friendly
One block of memory, walked in order. CPUs love that.
🔒Can be lock-free
With one producer and one consumer, each side only writes its own pointer, so no lock is needed.
🧯Bounded by design
A buffer that cannot grow cannot eat all the memory. Back pressure is built in.
🕒Keeps the recent past
In overwrite mode, it always holds the latest N items, which is perfect for a rolling view.
A ring buffer gives you a queue with a hard size limit, no allocation and constant-time operations. The price is that you must decide what happens when it fills.

05Where Do We Use It?

📜Log tails
Keep the last 1,000 log lines in memory for a debug page, dropping the oldest.
🎧Audio and video
A sound card reads from a buffer while the app writes into it, at slightly different speeds.
🌐Network cards
A NIC and the operating system share rings of packet descriptors.
⚡Low-latency trading
The LMAX Disruptor pattern passes events between threads through a ring buffer.
🐧Operating systems
Linux has kfifo, the kernel log buffer (dmesg) and the io_uring submission and completion rings.
📈Metrics windows
The last 60 seconds of samples, with the oldest value replaced each second.

06Types / Parts / How It Works

What to do when it is full

PolicyWhat happensGood forWatch out for
Overwrite oldestNew item replaces the oldest unread oneLogs, metrics, video frames, latest-value feedsSlow readers silently lose data
Reject newThe write fails or returns falseWork that must not be silently lostThe producer must handle failure
BlockThe writer waits until the reader frees a slotPipelines with back pressureCan stall the producer or deadlock if misused
Grow (not a ring any more)Allocate a bigger array and copyUnknown peak sizesGives up the fixed-memory promise

Ways to tell full from empty

TrickEmpty whenFull whenCost
Keep a countcount == 0count == NOne extra number to update
Waste one slothead == tail(tail + 1) % N == headOne slot is never used
Pointers that only go uptail == headtail − head == NUse 64-bit counters so they never overflow
Wrap-around in action
0️⃣slot 0item 5 (wrapped)
1️⃣slot 1item 2
2️⃣slot 2item 3
3️⃣slot 3item 4
Size 4. After writing 5 items with 2 reads, the tail has wrapped to slot 1.
Waiting items Item written after the wrap

Single or many writers

Who may touch which pointer
SPSC (one writer, one reader)
✍️Only the producer moves tail
📖Only the consumer moves head
MPMC (many of each)
🧵Pointers are sharedneeds atomic compare-and-swap or locks
One producer and one consumer need no lock. More threads need atomic operations or a lock.
VisualizerFill a ring and watch it wrapMake the producer faster than the consumer and press Play. Watch the tail wrap past slot 0. Then switch between “Overwrite the oldest” and “Reject the new item” and compare how many items are lost.
When the buffer is full...
01234567EMPTYtick 0
head = 0 next slot to read (oldest item)
tail = 0 next slot to write
a slot holding an item (#number)
tail = (tail + 1) % 8
empty: count == 0
Written
0
by the producer
Read
0
by the consumer
Overwritten
0
items lost
In buffer
0
of 8 slots
Press Play or Step. Each tick, the producer writes and the consumer reads at the speeds you set.

Writes (2/tick) are faster than reads (1/tick), so the buffer will fill up and then lose its oldest items. Items are numbered in the order they were written, so overwritten items are always the lowest numbers. A fixed speed per tick stands in for real timing, so the run is the same every time. The simulation stops after 60 ticks.

07How to Use It / Steps / Implementation

Building one

  1. 1
    Allocate the array once
    Pick a size N. Use a power of two if you can, so you can use a mask instead of modulo.
  2. 2
    Keep head and tail
    Both start at 0. Head is where you read, tail is where you write.
  3. 3
    Decide how to detect full
    Use a count, a one-slot gap, or pointers that only increase.
  4. 4
    Write
    If not full: store the item at tail and advance tail. If full: apply your policy.
  5. 5
    Read
    If not empty: take the item at head, advance head. If empty: return nothing or wait.
  6. 6
    Choose the full policy on purpose
    Overwrite for the latest data, reject or block when nothing may be lost. Count the drops.
  7. 7
    Make it safe across threads
    With one producer and one consumer, publish pointers with proper memory ordering. With more, use atomics or a lock.
💡Small and sharp
write: buf[tail & mask] = x; tail++ · read: x = buf[head & mask]; head++ · full: tail − head == N
⚠️Sizing is a decision, not a detail
Too small and you drop data in a burst. Too large and you hide a slow consumer, add delay and waste memory. Watch the drop count and the fill level.

08Key Terms to Know

TermMeaning in easy words
Ring bufferA fixed-size queue in an array whose indexes wrap around
Circular bufferAnother name for a ring buffer
HeadThe index of the oldest item, where the next read happens
TailThe index where the next write happens
ModuloThe remainder after division, used to wrap an index back to 0
MaskA bit trick for modulo when the size is a power of two
OverwriteReplace the oldest item when full
Back pressureMaking the producer slow down because the buffer is full
SPSCSingle producer, single consumer: the simplest lock-free case
MPMCMany producers, many consumers: needs atomics or locks
Lock-freeThreads cooperate through atomic operations, with no mutex
DisruptorA high-speed ring-buffer design for passing events between threads

09Pros, Cons and Trade-offs

✅ Pros
  • O(1) read and write
  • Memory is allocated once
  • No shifting or garbage
  • Easy to make lock-free for one reader and one writer
  • Perfect for rolling windows and streams
⚠️ Cons
  • Fixed size must be chosen in advance
  • Data can be lost on overwrite
  • Full versus empty needs care
  • Many writers or readers need extra safety
  • Does not support random insert or delete

Trade-offs

ChoiceWe gainWe lose
Overwrite when fullProducer never blockedOld data silently lost
Reject or block when fullNo data lossProducer can stall or fail
Power-of-two sizeFast mask instead of moduloMay waste some memory
Bigger bufferSurvives larger burstsMore memory and more delay
Lock-free SPSCVery low latencyHarder to reason about memory order

10Common Problems and Mistakes

Common mistakes

  1. Mixing up full and empty. head == tail means both. Use a count or a gap slot.
  2. Off-by-one at the wrap. Forgetting the modulo gives an index past the end of the array.
  3. Silent data loss. Overwriting without a counter means you never know you are dropping data.
  4. Sharing one pointer between threads without care. Writes may be seen out of order, and readers may read half-written items.
  5. Using the mask with a size that is not a power of two. The wrap is then wrong.
  6. Pointers that overflow. If they only go up, use 64-bit integers.
  7. Choosing the size by guessing. Measure peak bursts and the consumer speed.

Things to watch

📉Drop counter
Count every overwrite or rejection and alert if it rises.
🧵False sharing
Head and tail on the same cache line make threads slow each other. Pad them apart.
🐌Slow consumer
A buffer only hides a slow reader for a while. It is not a fix.
🔍Reading while overwritten
A reader looking at an old slot can be overtaken by a writer. Copy the item, then re-check.

11Real-World Examples

🐧Linux kernel
kfifo is a kernel ring buffer, the kernel log (dmesg) is one, and io_uring uses two rings shared with user space.
⚡LMAX Disruptor
A trading-system library built around a pre-allocated ring buffer for very low latency between threads.
🌐Network drivers
Cards and drivers pass packet descriptors through transmit and receive rings.
🎵Audio stacks
A callback fills or empties a ring buffer, so a short pause in the app does not cause a glitch.
📊Metrics libraries
Keep a fixed window of recent samples for percentiles and charts.
🪵Log shipping agents
A fixed-size in-memory buffer drops the oldest lines when the network is down.
📝Note
Message systems such as Kafka keep data in append-only log files and are not simple ring buffers. The ring-buffer idea does show up inside them, for example in network and I/O buffers.
Mini case: a spike in log lines
🔥Burst of 500 linesbuffer holds 100
→↓overwrite oldest
⭕Latest 100 lines400 dropped, counted
→↓agent ships them
📡Log server
The buffer keeps the newest lines. The oldest are replaced, and a counter records the loss.

12Related Topics to Read Next

Back Pressure→

What a full ring buffer tells the producer: slow down.

Message Queues→

Queues that live between services, bounded or unbounded.

LRU Cache Design→

Another fixed-size structure that throws out old data.

Heap and Priority Queue→

A queue where order depends on priority, not arrival.

Rate Limiting→

A sliding window of recent events is often stored in a ring.

Logging Best Practices→

Log agents use bounded buffers that drop the oldest lines.

Metrics and Instrumentation→

Rolling windows of samples for charts and percentiles.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Shape: fixed array, head (read) and tail (write), wrap with modulo.
  • ✔Write: buf[tail] = x; tail = (tail + 1) % N.
  • ✔Read: x = buf[head]; head = (head + 1) % N.
  • ✔Full or empty? Use a count, a gap slot, or ever-growing pointers.
  • ✔When full: overwrite oldest, or reject / block. Count the loss.
  • ✔Speed: power-of-two size gives index & (N − 1).
  • ✔Threads: SPSC can be lock-free. Many threads need atomics.
  • ✔One line: “A fixed circle of slots where the reader chases the writer, and a full circle forces a choice.”
← Previous
Bitmaps and Roaring Bitmaps
Next →
Geohash