Sub topic 5
Back pressure: slowing the producer
This chapter assumes you can read short Python examples and know what a producer and a consumer are. It also assumes you know the basics of async tasks or worker pools. It builds on bounded queues from the previous chapter.
What back pressure means
Back pressure is a way for a slow consumer to make a fast producer slow down. The producer is forced to wait until the consumer has room for more work. Work is never dropped. It is delayed at the source.
The term comes from plumbing. If a pipe is blocked downstream, pressure builds up and pushes back against the flow. In software, the "pressure" is a full queue, a closed window, or a missing permit. The producer has to notice it and wait.
Back pressure keeps the system's total in-flight work bounded without rejecting anything. If a queue holds at most 10 items, the producer cannot be more than 10 items ahead of the consumer. Memory use and queueing delay both stay bounded.
The simplest implementation: a blocking put
A bounded queue produces back pressure as a side effect. When the queue is full, put() does not return until a consumer calls get() and frees a slot.
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 consumer handles about 100 items per second. The producer could generate items much faster. After the first 10 items the queue fills, and the producer's speed drops to the consumer's speed. The producer spends most of its time suspended inside put().
Without maxsize, asyncio.Queue is unbounded. In that case put() never waits, and the producer would enqueue all 100 items at once. With a million items, the queue would hold a million items.
How the signal travels
The waiting happens inside the call the producer already makes. The producer needs no special code to receive the signal.
The same pattern appears in other places:
- A thread calling
queue.Queue.put()blocks the thread. - A coroutine awaiting
asyncio.Queue.put()suspends the coroutine, and the event loop runs other tasks. - A socket
send()blocks, or returns "would block", when the peer's receive buffer is full.
Back pressure must propagate
A single bounded queue only protects that one hop. Real systems are pipelines: an HTTP handler feeds a parser, which feeds a database writer. If only the last stage is bounded, the stages before it may still pile up work in their own unbounded buffers.
For back pressure to work end to end, each stage needs two things:
- A bounded buffer on its input.
- A way to stop reading its own input when its output is blocked.
If a stage is stuck in put() on the next queue, it is not calling get() on its own queue. That queue fills, and the stage before it blocks. The blockage travels backward until it reaches the original source.
| Pipeline design | What happens when the last stage is slow |
|---|---|
| Every stage bounded | The block propagates back to the source, which slows down. |
| Only the last stage bounded | Earlier stages keep accepting and buffering. Memory grows there instead. |
| Unbounded everywhere | Nothing slows down. Latency and memory grow without limit. |
A single unbounded buffer in the middle of a pipeline silently cancels the back pressure from everything after it.
Waiting is not free
Blocking in put() keeps the work in memory and keeps the resources attached to it. Consider a web handler that does await queue.put(job) when the queue is full:
- The client connection stays open.
- The request body stays in memory.
- A task, a thread, or a worker slot is held.
- The client's timer keeps running.
If requests arrive faster than the queue drains, the waiting handlers pile up. You have moved the unbounded queue from your explicit queue into the pool of blocked handlers. The waiting needs a limit of its own. The usual limit is a timeout on the wait:
import asyncio
async def put_with_timeout(queue: asyncio.Queue, item, timeout: float) -> bool:
"""Try to enqueue item, waiting at most timeout seconds. Return True on success."""
try:
await asyncio.wait_for(queue.put(item), timeout)
return True
except asyncio.TimeoutError:
return Falsewait_for cancels the pending put() when the timeout expires, so the item is not added. A False result tells the caller to give up on this request and report an error. At that point the system has switched from back pressure to rejecting work, which is the subject of the next chapter.
When back pressure works and when it does not
Back pressure only works if the producer can actually be slowed down and is willing to wait. That holds in some situations and not in others.
Back pressure fits when:
- The producer is under your control, such as a file reader, a queue consumer in a pipeline, or a batch job.
- The producer can pause without losing data, because the source holds the data. Examples are a file on disk, a Kafka partition, or a database cursor.
- Delay is acceptable. Nobody needs the result by a hard deadline.
Back pressure does not fit when:
- The producer is the public internet. Users do not slow down because your queue is full. They retry, or they leave.
- The source produces data in real time and cannot hold it. A sensor or a market feed keeps emitting whether or not you read it.
- Waiting would exceed the client's own timeout. Work done after the client has given up is wasted.
In these cases you must decide what to drop, because you cannot make the source wait.
Edge cases and failure modes
Deadlock in cyclic pipelines. If stage A writes to B and B writes back to A, both can block on full queues, each waiting for the other to read. Avoid cycles between bounded queues. If you need one, give the feedback path its own unbounded or reserved capacity, or make one side non-blocking.
Head-of-line blocking. A single slow item at the front of a queue holds up everything behind it, even if other consumers are idle. Use several consumers on one shared queue so that one slow item blocks only one worker.
Multiple consumers and sentinels. The None sentinel in the example stops one consumer. With N consumers, the producer must put N sentinels, or the other consumers wait on get() forever.
Size of the bound. A very large maxsize allows long waits before back pressure begins. A tiny maxsize such as 1 couples the stages tightly, so any jitter in the consumer stalls the producer. A common starting point is the number of items a consumer can process in the time you are willing to wait. Little's law, from earlier in this tutorial, gives that estimate: queue length is arrival rate times time spent waiting.
Blocking the event loop. A blocking queue.Queue.put() inside a coroutine freezes the whole event loop, not only that task. In async code, use asyncio.Queue or run the blocking call in an executor.
Back pressure versus load shedding
| Row | Back pressure | Load shedding |
|---|---|---|
| Action when overloaded | Make the producer wait | Reject or drop some work |
| Work lost | None | Some |
| Latency under overload | Grows, up to the bound plus the wait | Stays low for accepted work |
| Needs a cooperative producer | Yes | No |
| Typical place | Internal pipelines, batch jobs | Public-facing request handling |
The two are often combined. Use back pressure inside a pipeline, where producers cooperate. Use shedding at the edge, where they do not.
Exercise
A pipeline has three stages connected by queues: reader, parser, writer. The reader-to-parser queue is bounded at 100, but the parser-to-writer queue is unbounded. The writer becomes slow. What happens to memory, and how do you fix it?
Show answer
The writer's slowness never reaches the parser, because the parser's put() on the unbounded queue never blocks. The parser keeps running at full speed and the parser-to-writer queue grows without limit, so memory climbs until the process fails. The reader-to-parser bound does not help because the parser is never slowed. Fix it by giving the parser-to-writer queue a maxsize. Then the parser blocks in put() when the writer lags, its input queue fills, and the reader blocks too. Back pressure now reaches the source.