Sub topic 4
Bounding the queue
This chapter assumes you can read short Python examples and know what a producer/consumer pair is. It also assumes you have seen the previous chapter's argument that an unbounded queue turns overload into growing latency and memory use. Here you will fix that by putting a limit on the queue, choosing a size for it, and deciding what happens when the limit is reached.
What a bound changes
A bounded queue is a queue with a maximum number of items. Adding that number does two things.
- It caps memory. The queue can never hold more than
maxsizeitems. - It caps waiting time. An item can wait behind at most
maxsizeothers, so the worst-case wait is bounded too.
A bound does not make the system faster. If work arrives faster than it finishes, the queue still fills. The bound forces you to decide, at the moment of overload, what to do with the next item. An unbounded queue never asks that question, which is why it fails slowly and badly instead.
Choosing a size with Little's law
Little's law says that the average number of items in a system equals the arrival rate times the average time each item spends in it. Use it backwards to size a queue from the waiting time you can tolerate.
Suppose a service has 4 workers and each request takes 50 ms to process.
- Capacity is 4 workers ÷ 0.05 s = 80 requests per second.
- Your latency target allows a request to wait at most 200 ms in the queue.
- Depth ≈ capacity × allowed wait = 80 × 0.2 = 16 items.
So a queue of about 16 is a reasonable starting point. A queue of 10,000 would let a request wait 125 seconds (10,000 ÷ 80) before a worker even starts on it. Most clients would have given up long before that.
The same arithmetic also shows what a bound is for. A queue should absorb short bursts, not sustained excess. If load stays above capacity, no queue size helps. It only decides how much latency you add before you start rejecting.
| Queue size | Burst absorbed | Worst-case queue wait at 80 req/s |
|---|---|---|
| 0 to 2 | Almost none | Under 30 ms |
| 16 | About 0.2 s of traffic | 200 ms |
| 160 | About 2 s of traffic | 2 s |
| Unbounded | Everything, until memory runs out | Grows without limit |
Larger is not safer. Past the point where a request's wait exceeds what its client will tolerate, extra capacity in the queue only stores work that nobody is waiting for.
What happens when the queue is full
A full queue forces one of four choices.
| Policy | What the producer sees | What is lost | Typical use |
|---|---|---|---|
| Block | `put()` waits until there is room | Nothing, but the producer is delayed | Internal pipelines where the producer can safely wait |
| Reject newest | An immediate error | The incoming item | Request handlers that can reply "busy" |
| Drop oldest | Success | The item that has waited longest | Live data where fresh values matter more than old ones |
| Drop by priority | Success or error | The least important item | Mixed traffic, covered in a later chapter |
Blocking is back pressure, and the next chapter covers it in detail. Rejecting is the simplest form of load shedding, and a later chapter expands on it. This chapter covers the mechanics common to all of them.
A bounded queue in asyncio
asyncio.Queue takes a maxsize argument. Both ways of adding an item respect it:
await queue.put(item)suspends the caller while the queue is full.queue.put_nowait(item)raisesasyncio.QueueFullinstead of waiting.
The following program sends 30 items at 100 per second to a single worker that handles 20 per second. The queue holds 5 items, and the producer rejects anything that does not fit.
import asyncio
import time
async def worker(queue: asyncio.Queue, waits: list[float]) -> None:
while True:
enqueued_at, item = await queue.get()
waits.append(time.monotonic() - enqueued_at)
await asyncio.sleep(0.05) # simulate 50 ms of work
queue.task_done()
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue(maxsize=5)
waits: list[float] = []
rejected = 0
task = asyncio.create_task(worker(queue, waits))
for i in range(30):
try:
queue.put_nowait((time.monotonic(), i))
except asyncio.QueueFull:
rejected += 1
await asyncio.sleep(0.01) # arrivals every 10 ms
await queue.join() # wait until accepted items are processed
task.cancel()
print(f"accepted={len(waits)} rejected={rejected}")
print(f"max queue wait={max(waits):.3f}s")
asyncio.run(main())Exact counts vary from run to run, but accepted + rejected is always 30. The maximum queue wait stays at or below roughly 0.25 s, because an accepted item has at most five items ahead of it, counting the one being processed, at 0.05 s each. With an unbounded queue the same program would accept all 30 items, and the last one would wait over a second. Scale the arrival rate up and that wait keeps growing.
The task_done() and join() calls are optional. They let main wait until the accepted work is finished.
Dropping the oldest item
Python's queues have no built-in "drop oldest" mode, but in a single event loop you can build one. There is no await between the steps, so no other task can run in the middle.
import asyncio
from typing import Any
def offer_drop_oldest(queue: asyncio.Queue, item: Any) -> Any:
"""Enqueue item. If the queue is full, evict and return the oldest item."""
try:
queue.put_nowait(item)
return None
except asyncio.QueueFull:
evicted = queue.get_nowait()
queue.task_done() # keep join() accounting correct for the evicted item
queue.put_nowait(item)
return evicted
async def main() -> None:
queue: asyncio.Queue = asyncio.Queue(maxsize=3)
for i in range(5):
evicted = offer_drop_oldest(queue, i)
if evicted is not None:
print(f"evicted {evicted}")
print([queue.get_nowait() for _ in range(queue.qsize())])
asyncio.run(main())This prints evicted 0, evicted 1, and then [2, 3, 4]. Use this policy when old data is worthless, for example a stream of sensor readings where only the latest matters. Do not use it for requests that a user is waiting on, because it throws away the work whose client has waited longest and is most likely to still be there.
Python's collections.deque(maxlen=n) does this silently, with no error and no count of what was lost. If you use it, count the evictions yourself. Silent loss is hard to notice later.
Edge cases and gotchas
- Hidden unbounded buffers. Bounding your queue does not help if work then moves into another unbounded one.
concurrent.futures.ThreadPoolExecutorkeeps submitted tasks in an unbounded internal queue, so callingexecutor.submit()in a loop never blocks. A boundedqueue.Queueahead of the executor, or a semaphore aroundsubmit(), restores the limit. qsize()is a hint. In threaded code, the value can be stale by the time you act on it. Checkingqsize() < maxsizeand then callingput()is a race. Callput_nowait()and handleQueueFull, which performs the check and the insert as one step.- Sentinels can block. The producer in a shutdown protocol often does
await queue.put(None)to signal the end. On a full queue that call waits like any other. Make sure a consumer is still running, or shutdown will hang. - Blocking with no timeout can wait forever. In threaded code,
queue.Queue.put(item, timeout=1.0)raisesqueue.Fullafter a second. This gives you a bound on the producer's wait as well as on the queue. - Count your rejections. A bound that rejects silently hides overload. Increment a counter on every
QueueFulland export it. A later chapter covers which metrics to watch. - The bound includes only waiting items. Items already taken by workers are not in the queue. Total work in the system is queue depth plus the number of busy workers, which matters when you compute latency with Little's law.
Choosing a policy
Ask who is on the other side of the producer.
- If the producer is part of your own pipeline and can safely slow down, block.
- If the producer is a remote client that can be told to try later, reject, and say so with a status code the client can act on.
- If only the freshest data has value, drop the oldest, and count what you drop.
You can combine these. A common design blocks briefly with a timeout, then rejects if no room appears. That absorbs tiny bursts without letting waits grow.
Exercise
A service has 8 workers, each request takes 25 ms, and clients time out after 500 ms. You want requests to wait in the queue for at most 100 ms. About how large should the queue bound be, and why is a bound of 1,000 a poor choice?
Show answer
Capacity is 8 ÷ 0.025 s = 320 requests per second. Depth ≈ 320 × 0.1 s = 32 items. A bound of 1,000 would allow a wait of about 1,000 ÷ 320 ≈ 3.1 seconds, far past the 500 ms client timeout. Under sustained overload, workers would spend their time on requests whose clients have already given up, so useful throughput would fall to nearly zero.
Exercise
Why is if queue.qsize() < queue.maxsize: queue.put(item) unsafe in threaded code, and what should you write instead?
Show answer
Another thread can add an item between the check and the put(), so the queue may be full when put() runs, which then blocks unexpectedly. Call queue.put_nowait(item) and catch queue.Full, or call put(item, timeout=...). Either one checks for room and inserts in a single step.