Ring buffer
A fixed-size array used as a queue, with a write position that wraps back to the start when it reaches the end so the newest entry overwrites the oldest. It exists because many systems only ever need the most recent N things, and a ring buffer gives that with zero allocation, bounded memory and constant-time operations.
What it costs
| Operation | Cost | Note |
|---|---|---|
| Append (write) | O(1) | Store at slots[head], advance head modulo capacity; if full, the oldest slot is overwritten and tail advances too. |
| Read oldest (dequeue) | O(1) | Read slots[tail], advance tail. Used when the buffer is a queue between a producer and a consumer. |
| Read last k | O(k) | Walk backwards from head−1, wrapping. "Last 60 samples" is a 60-slot walk. |
| Snapshot / drain | O(n) | Copy or flush all live slots between tail and head in order. |
Memory: Exactly capacity × element size, allocated once; plus two integers for head and tail.
Eight slots, head and tail wrap around
Writes go to head and advance it; reads come from tail. When head laps the array it overwrites the oldest slot (sliding window) or waits for the consumer (bounded queue). Capacity never changes.
How it works
- Allocate an array of fixed capacity N and two indexes: head, where the next write goes, and tail, the oldest live element. Both start at 0 and only ever increase; the slot used is index modulo N, which is what makes the array a ring.
- A write stores the element at head mod N and increments head. If head − tail would exceed N, the buffer is full: either the write blocks or fails (a bounded queue, which is how backpressure is applied), or tail is incremented too so the oldest element is silently dropped (a sliding window of the last N).
- A consumer reads at tail mod N and increments tail. Because the producer touches only head and the consumer only tail, a single producer and single consumer can share the buffer with no locks, just memory ordering guarantees.
- Reading the last k entries walks backwards from head − 1, wrapping around the end of the array; reading everything live walks from tail to head.
- Making N a power of two turns the modulo into a bit mask, so each operation is an AND and a store.
Why it is shaped this way
- Memory never grows and is never freed, so there is no allocator work and no garbage collection pressure on a hot path.
- Overwriting the oldest entry is the right default for recent-history data (last minute of metrics, last 60 positions), and the fixed bound is a safety property: an overloaded system cannot eat all memory.
Worked example
Recent driver positions in the ride-matching service
- Each active driver sends a location every 4 seconds. The location service keeps the last 15 positions per driver (one minute of history) for heading and speed estimation and for showing the car sliding smoothly on the rider’s map.
- Ring buffer per driver: 15 slots × 24 B (lat, lng, heading, timestamp) = 360 B plus two indexes. For 2M active drivers that is 720 MB, allocated once; no per-update allocation, no cleanup job for stale history.
- Each update is one store at head mod 15 and an increment; the position from a minute ago is overwritten automatically. Estimating heading reads the last 3 slots walking backwards from head.
- The same shape at a different scale: a metrics agent keeps a 60-slot ring of per-second request counts per endpoint and computes the one-minute rate by summing it; the structured-logging agent buffers the last 10,000 log lines in a ring so a crash dump includes recent context, and a bounded ring between the network thread and the processing thread is what makes a Kafka producer apply backpressure when the broker is slow: when the ring is full, the sending thread waits.
- Compare with a growable list and a trim: the list allocates on every append and copies on trim; the ring does neither and is 20× fewer instructions on the hot path.
When it is the wrong choice
- You cannot afford to lose old entries and the consumer may fall behind indefinitely: a ring either drops or blocks, so an unbounded durable queue (a log on disk) is the right tool.
- Elements vary wildly in size: fixed slots waste space or need a second level of indirection.
- You need lookup by key or in sorted order: it is a queue, nothing more.
Interviewer follow-ups
Answer out loud before you open each one.
What happens when the producer is faster than the consumer?
The buffer fills. You choose the policy up front: block the producer until space frees (this is backpressure, and what bounded channels do), drop the newest write and report it, or overwrite the oldest entry (right for recent-history windows where old data has no value). The fixed capacity is what forces the decision instead of letting memory grow until the process dies.
Why does the single-producer single-consumer case need no lock?
Only the producer writes head and only the consumer writes tail, so there is no contended variable. Each side reads the other’s index to check for full or empty. The one requirement is that the element store becomes visible before the index increment, which a release/acquire memory ordering provides.
Why keep head and tail as ever-increasing integers rather than wrapping them?
With plain increasing counters, head − tail is the number of live elements and the full and empty cases are unambiguous. Wrapping the indexes themselves makes head == tail mean either empty or full, which needs an extra flag or a wasted slot.
How is a sliding-window rate limiter related to a ring buffer?
A per-second counter ring of 60 slots gives a one-minute sliding window: increment the slot for the current second, and the window total is the sum of all slots. Each new second overwrites the slot from 60 seconds ago, which is exactly the entry that just left the window.
Where it shows up
- Building blocks
- Ingest millions of position updates · Log so you can query · Measure what users feel · Slow the producer when the consumer is behind · Limit requests per client · Track online status cheaply
- Problems
- Ride Matching (Uber / Lyft) · Distributed Rate Limiter · Chat App (WhatsApp / Messenger)