Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Queues: preserve arrival order without front shifts

Last updated: 4 Oct 20269 min read
tutorial
IntermediateBy AITrove Editorial

A first-in-first-out queue removes the oldest enqueued item first. Python's collections.deque supports appending at the right and removing from the left without shifting the entire collection. Those endpoint operations are O(1) in the intended queue use. A queue decides order; it does not provide durable delivery, retries, consumer acknowledgment, or fairness among external workers. A bound on queue length and a behavior when full matter in a live service, because constant-time insertion does not prevent unbounded memory growth when producers outrun consumers.

Operational case

A loading dock receives pallets P-47, P-52, and P-61. The next pickup is P-47, and P-61 remains waiting. Using a list with pop(0) would shift later entries on each pickup, which becomes expensive for a large backlog. A deque keeps the endpoint contract clear. If P-47's pickup fails after it has been removed, this in-memory queue alone cannot know whether to retry safely; the application needs a separate receipt and retry policy.

Working Python program

python
from collections import deque

waiting_pallets = deque(["P-47", "P-52", "P-61"])
next_pickup = waiting_pallets.popleft()
print(next_pickup)
print(list(waiting_pallets))

Output

Output
P-47
['P-52', 'P-61']

Time, space, and tradeoff

Enqueue and dequeue at opposite ends are O(1), while scanning the queue for a specific pallet is O(n). Space is O(n) for n waiting items. A deque is often the right in-process choice; a distributed queue has different guarantees about persistence, visibility, and duplicate delivery. Set backpressure or a maximum backlog before production use, and define whether an empty dequeue raises or returns a sentinel so callers do not mistake no work for a valid item.

Common Mistakes

  • Do not use list.pop(0) for a large FIFO backlog.
  • Do not mistake an in-memory deque for durable messaging.
  • Do not let the queue grow without a capacity or backpressure rule.

Connected lessons

Two-stack window aggregation: keep FIFO order under a monoid adds a distinct structure contract to compare.

Persistent two-list queues: fork FIFO dispatch history adds a distinct structure contract to compare.

data structures
stacks-and-queues
Storage details