Sub topic 4
Bounding the queue
This chapter assumes you can read short Python examples, know the basics of asyncio or worker pools, and have seen Little's law (in-flight work equals arrival rate times time in system). An unbounded queue hides overload until memory runs out. A bounded queue makes overload visible and forces a decision.
Why a bound helps
With an unbounded queue, a producer that outpaces its consumer keeps adding work. Wait time and memory use grow with the backlog. A bound caps both. If the maximum queue size is N and the consumer finishes work at rate μ, the longest an accepted item can wait is roughly N / μ. That figure is your worst-case queueing delay, and you can set it deliberately.
Choosing the size
Pick the size from the latency you can tolerate, not from the memory you have available.
- Decide the longest acceptable wait, for example 200 ms.
- Estimate the consumer's throughput, for example 500 items per second.
- Multiply: 0.2 s × 500/s = 100 items.
A queue that is small relative to this figure rejects bursts that it could have absorbed. A queue that is large relative to it stores work that will be stale before anyone processes it. Start small and raise the bound only if you measure bursts being rejected while the consumer is still idle at other times.
What happens when the queue is full
A full bounded queue leaves you two choices.
- Block the producer. The producer waits until space is free. This is back pressure, and the next chapter covers it.
- Reject the work. The producer gets an error immediately. This is the simplest form of load shedding.
The first example blocks. await queue.put(i) suspends the producer while the queue is full, so it can never get more than 10 items ahead of the consumer.
import asyncio
async def producer(queue: asyncio.Queue, count: int) -> None:
for i in range(count):
await queue.put(i) # suspends while the queue is full
await queue.put(None) # sentinel: no more work
async def consumer(queue: asyncio.Queue) -> None:
while True:
item = await queue.get()
if item is None:
break
await asyncio.sleep(0.01) # simulate slow work
async def main() -> None:
queue = asyncio.Queue(maxsize=10)
await asyncio.gather(producer(queue, 100), consumer(queue))
asyncio.run(main())The second example rejects. put_nowait raises asyncio.QueueFull at once, and the caller turns that into an application error.
import asyncio
class Overloaded(Exception):
pass
def submit(queue: asyncio.Queue, request) -> None:
try:
queue.put_nowait(request)
except asyncio.QueueFull:
raise Overloaded("queue full") from NoneCommon errors
- Setting a huge bound. A queue of a million items is effectively unbounded. Check the bound against the latency calculation above.
- Forgetting that
maxsize=0means unlimited. Inasyncio.Queue, a size of 0 or less removes the bound. - Blocking when the producer cannot afford to wait. A request handler that waits on
put()holds its connection open and can pile up waiting handlers elsewhere. Reject in that case. - Bounding one queue and leaving others unbounded. Overload then moves to the next unbounded buffer, such as a socket backlog or a thread pool's internal queue.
Exercise
A worker processes 200 items per second, and you want no accepted item to wait longer than 150 ms in the queue. What maximum queue size should you use, and what happens to the 31st arriving item if the burst arrives while the queue is empty and the worker is busy?
Show answer
Size = 0.15 s × 200/s = 30 items. The first 30 queued items fit, so the 31st finds the queue full. It either blocks (back pressure) or is rejected with an error (load shedding), depending on the policy you chose.