Sub topic 17
Backpressure and slow clients
This chapter assumes you have read the chapter on relaying a stream through your own server. It also assumes you are comfortable with Python asyncio basics.
What backpressure is
Backpressure is the way a slow consumer tells a fast producer to wait. A model can emit tokens faster than a phone on a weak connection can receive them. If your relay reads from the provider and writes to the client without any limit, the unsent data piles up in your server's memory.
For a single chat reply this rarely matters, because the text is only a few kilobytes. It matters when you serve thousands of connections at once, or when a client stalls and its buffer grows for as long as the stream stays open.
Where the buffers are
Several buffers sit between the model and the screen:
- The operating system's socket send buffer.
- Your web server's or framework's write buffer.
- Any proxy between your server and the client.
- Your own queues, lists, or string accumulators.
TCP already provides flow control. When the client stops reading, the socket buffers fill and a write call waits or blocks. Backpressure only works if your code lets that wait reach the upstream read. An unbounded queue between the two loops hides the wait, and memory grows instead.
A bounded queue
The simplest fix is a queue with a maximum size. When it is full, put suspends the producer until the consumer catches up.
import asyncio
async def producer(queue):
for i in range(8):
await queue.put(f"token{i}") # waits while the queue is full
print("produced", i)
await queue.put(None) # end marker
async def consumer(queue):
while (item := await queue.get()) is not None:
await asyncio.sleep(0.3) # simulates a slow client
print("sent", item)
async def main():
queue = asyncio.Queue(maxsize=3)
await asyncio.gather(producer(queue), consumer(queue))
asyncio.run(main())The first few "produced" lines appear quickly. After that, production slows to the speed of "sent".
Policies for slow clients
Waiting is not always the right response. Choose a policy deliberately:
| Policy | Behavior | Use when |
|---|---|---|
| Wait | Stop reading from the provider until the client drains | Few clients, and you want every token delivered |
| Coalesce | Merge queued deltas into one larger event | The UI only needs the latest text |
| Time out | Close the connection if a write stalls too long | Clients that vanish without closing |
| Drop | Discard data you can rebuild | Progress hints, not message text |
Never drop text deltas silently. The user would see a corrupted message. Coalescing is safe because it joins the same text into fewer events.
Limits of waiting
Pausing your read does not pause the model. The provider keeps generating, and its own buffers hold the tokens until its write timeout expires. You also pay for those tokens. If a client is too slow or has gone away, cancel the upstream request, as described in the cancellation chapter. Don't wait indefinitely.
Exercise
A relay reads provider tokens into an unbounded asyncio.Queue, and a separate task writes them to the client. Memory grows when clients are slow. What two changes would you make?
Show answer
Give the queue a maxsize so the provider reader waits when it is full, and add a write timeout that closes the connection and cancels the upstream request when a client stays stalled.