DEV Community

Fiaz Miah
Fiaz Miah

Posted on

A bounded deque drops history; it does not reject new work

A collection that never grows beyond two items sounds useful for a tiny work queue. The important question is what happens to item three.

Python's deque(maxlen=2) accepts an append when it is full. It removes an item from the opposite end. That is useful for a rolling history, but it is a poor contract for pending work that must stay queued until a consumer takes it.

Make overflow visible

This synthetic example compares eviction with explicit rejection. It does not run workers or model a durable job service.

from collections import deque
from queue import Queue, Full

history = deque(['job-a', 'job-b'], maxlen=2)
history.append('job-c')
assert list(history) == ['job-b', 'job-c']

q = Queue(maxsize=2)
q.put_nowait('job-a')
q.put_nowait('job-b')
try:
    q.put_nowait('job-c')
except Full:
    pass
else:
    raise AssertionError('expected Full')

assert q.get_nowait() == 'job-a'
assert q.get_nowait() == 'job-b'
q.put_nowait('job-c')
assert q.get_nowait() == 'job-c'
Enter fullscreen mode Exit fullscreen mode

The assertions passed locally. The rejected insertion leaves the two accepted items available in order, and a later insertion succeeds after they are removed.

Decide what a full queue means

Handle Full at the point where work is offered: return a clear rejection, retain the work elsewhere, or retry under an explicit policy. Silently ignoring it would merely move the data-loss problem into the caller.

Do not check q.full() and assume a later insertion will succeed. Other threads can change the queue between those operations; put_nowait() supplies the outcome of the insertion itself.

A Queue is still in-memory. This example supplies no persistence, crash recovery, processing acknowledgement or exactly-once execution. Those require separate design decisions.

Use bounded history when losing the oldest item is intended. For pending work, choose an insertion operation whose overflow behavior the caller can handle.

References: deque and Queue.

Top comments (0)