Sub topic 8
When the buffer is full: reject or overwrite
This chapter assumes you can implement push and pop on a ring buffer with head and tail indices, modulo wraparound, and a count field. It covers what the buffer should do when a producer pushes into a full buffer.
The two policies
A fixed-capacity buffer cannot grow, so a push into a full buffer needs a rule. There are two common rules.
- Reject on full. The push fails and the buffer is unchanged. The caller learns that the item was not stored. The
RingBufferfrom the previous chapter does this by raisingOverflowError. In C you usually returnfalse. - Overwrite oldest. The push succeeds by discarding the item at the head. The buffer always holds the most recent
capacityitems.
Overwrite in code
Overwrite can be built on the existing pop and push. If the buffer is full, remove the oldest item first, then push.
class RingBuffer:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self._buf = [None] * capacity
self._head = 0
self._count = 0
def __len__(self):
return self._count
def push(self, item):
if self._count == len(self._buf):
raise OverflowError("buffer full")
tail = (self._head + self._count) % len(self._buf)
self._buf[tail] = item
self._count += 1
def pop(self):
if self._count == 0:
raise IndexError("buffer empty")
item = self._buf[self._head]
self._buf[self._head] = None
self._head = (self._head + 1) % len(self._buf)
self._count -= 1
return item
def push_overwrite(rb, item):
"""Add item; if the buffer is full, drop the oldest item first."""
if len(rb) == len(rb._buf):
rb.pop()
rb.push(item)
rb = RingBuffer(3)
for n in range(1, 6):
push_overwrite(rb, n)
print([rb.pop(), rb.pop(), rb.pop()]) # [3, 4, 5]Five items went into a buffer of three. Items 1 and 2 were discarded, and the buffer kept the newest three. Both operations stay O(1), so overwriting costs nothing extra.
Choosing a policy
The right policy depends on which loss is worse: losing new data or losing old data.
| Situation | Policy | Reason |
|---|---|---|
| Task or job queue | Reject | Every item must be processed. Dropping one silently is a bug. |
| Network packets with backpressure | Reject | The sender can slow down or retry when it sees the failure. |
| Recent log lines or telemetry | Overwrite | Only the latest window matters, and the producer must never block. |
| Sensor samples feeding a display | Overwrite | A stale reading is worth less than the current one. |
| Undo history | Overwrite | The oldest steps can be forgotten when the limit is reached. |
A useful rule: reject when the producer can react to failure, and overwrite when the producer cannot wait and recent data is what counts.
Pitfalls
- Silent loss. Overwriting hides the fact that data was dropped. If you need to know, keep a counter of dropped items and expose it.
- Consumer confusion. After an overwrite, the consumer sees a gap in the sequence. If items carry sequence numbers, the consumer can detect it.
- Concurrency. Overwrite moves the head, but the consumer owns the head. In the lock-free single-producer, single-consumer design covered later, the producer must not advance the head. The overwrite policy therefore needs a different design or a lock. Reject-on-full works with no changes.
- Wrong default. Choose the policy deliberately. A buffer that rejects without anyone checking the return value loses data just as silently as an overwrite does.
Exercise
A ring buffer of capacity 4 uses the overwrite-oldest policy. You push 1, 2, 3, 4, 5, 6 in order, with no pops. What does the buffer hold, and in what order are items popped?
Show answer
Pushes 5 and 6 each find the buffer full, so each drops the oldest item (1, then 2). The buffer holds 3, 4, 5, 6. Pops return them in FIFO order: 3, 4, 5, 6.
Exercise
You are building a buffer for audio samples written by a real-time interrupt handler that cannot block. Should it reject or overwrite when full? Name one cost of your choice.
Show answer
Overwrite is usually the better fit, because the handler cannot wait and recent audio matters most. The cost is that old samples are lost without notice, so you should count dropped samples. (Rejecting is also defensible if you count failed pushes, but the new samples would be the ones lost.)