Sub topic 17
Backpressure and slow clients
This chapter assumes you have read the chapters on server relays and cancellation. You should be comfortable with Python asyncio and know that a relay reads a provider's stream and writes it to a browser.
What backpressure means
Backpressure is a signal that a consumer cannot keep up, passed back to the producer so it slows down. Without it, the data between them piles up in memory.
A streaming relay has two speeds. The model produces tokens at a rate the provider controls, often 30 to 100 tokens per second. The client consumes them at whatever rate its network and device allow. A phone on a weak connection, a browser tab throttled in the background, or a corporate proxy that drains slowly can all fall behind.
When the client is slower than the model, the bytes have to wait somewhere.
Where the data waits
Each hop between the model and the screen has a buffer:
- The provider's own output buffer.
- The TCP receive buffer on your server.
- Your relay's in-process queue or generator.
- The TCP send buffer and any proxy buffer between your server and the client.
- The browser's network stack and your JavaScript handler.
If your relay writes to the socket with await, a full send buffer pauses your code at that point. That pause stops your reads from the provider. The provider's TCP window then shrinks and the provider's writes block. This is automatic backpressure, and it works as long as every step in your relay is awaited in sequence.
It breaks when you add your own unbounded buffer. A common bug is a reader task that pushes every chunk into an asyncio.Queue() with no maxsize. The reader never blocks, so the queue grows for as long as the client is slow.
How bad can it get?
For one chat reply the answer is usually "not bad". A reply of 4,000 tokens is a few tens of kilobytes. The risk comes from scale and from long-lived streams:
- Thousands of concurrent slow clients, each holding a queue, add up.
- Agents and long-form generation can run for minutes.
- A stalled client keeps its upstream request open, which holds a provider connection and a rate-limit slot, and you may keep paying for tokens nobody reads.
Slow clients are therefore mostly a resource-management problem, not a correctness problem.
Options when the client falls behind
Pausing the upstream read is not always the best choice. Generation on the provider side usually continues regardless of how fast you read, so you cannot truly slow the model down. You only move the buffer to the provider's side, where it may time out.
| Strategy | What it does | Trade-off |
|---|---|---|
| Block on write | Await each write. Upstream reads pause. | Simple. Holds the upstream connection open and risks a provider timeout. |
| Bounded queue | Reader blocks when the queue is full. | Same effect as blocking, with a fixed memory cap per client. |
| Coalesce | Merge pending deltas into one larger write. | Fewer writes, no data lost. Updates become chunkier. |
| Drop intermediate state | Keep only the latest snapshot. | Only valid if events are snapshots, not deltas. |
| Disconnect | Close slow clients after a deadline and cancel upstream. | Protects the server. The user must retry. |
For text deltas, coalescing is the best default. Dropping a delta would corrupt the message, but joining two deltas into one gives the same final text. The client sees fewer, larger updates, which is usually invisible.
A coalescing buffer
This buffer stores pending text and hands the consumer everything accumulated since its last read. A fast consumer gets small pieces. A slow one gets fewer, larger pieces. Memory stays bounded by the length of the reply, because the text is joined rather than queued as separate events.
import asyncio
class Coalescer:
def __init__(self):
self._parts = []
self._event = asyncio.Event()
self._closed = False
def push(self, text):
self._parts.append(text)
self._event.set()
def close(self):
self._closed = True
self._event.set()
async def get(self):
"""Return all pending text joined, or None once closed and drained."""
while True:
if self._parts:
text = "".join(self._parts)
self._parts.clear()
return text
if self._closed:
return None
self._event.clear()
await self._event.wait()
async def produce(buf):
for i in range(40):
await asyncio.sleep(0.01)
buf.push(f"tok{i} ")
buf.close()
async def consume(buf, delay):
writes = 0
total = ""
while (text := await buf.get()) is not None:
writes += 1
total += text
await asyncio.sleep(delay) # simulates a slow socket write
return writes, total
async def main():
for delay in (0.0, 0.1):
buf = Coalescer()
producer = asyncio.create_task(produce(buf))
writes, total = await consume(buf, delay)
await producer
print(f"delay={delay}: {writes} writes, {len(total.split())} tokens")
asyncio.run(main())Both runs deliver all 40 tokens. The fast consumer makes about 40 writes. The slow one makes roughly 5 to 10, each carrying several tokens. The clear() call is safe here because asyncio is single-threaded and nothing awaits between checking _parts and clearing the event.
Cleaning up when the client is gone
A client that disconnects is the extreme slow client. Your relay must notice and stop the upstream request. In ASGI frameworks such as FastAPI, a disconnect cancels the response generator, so put cleanup in finally:
async def relay(upstream_events):
"""upstream_events must be an async generator so it has aclose()."""
try:
async for event in upstream_events:
yield f"data: {event}\n\n"
finally:
await upstream_events.aclose() # releases the provider connectionWithout this, the provider request can keep running to completion even though no one is listening.
Edge cases
- Stalled but connected clients. A client that never reads, but never closes, will not raise an error. Put a deadline on each write, for example with
asyncio.wait_for, and disconnect clients that exceed it. - Proxy buffering hides the problem. If a proxy accepts your writes quickly and holds them, your relay sees a fast client while the real user waits. Backpressure only works up to the first buffering hop.
- Heartbeats count as writes. Keep-alive comments are small, but a blocked socket blocks them too. Do not treat a successful heartbeat as proof that the client is reading real content.
- Usage data is at the end. If you disconnect a slow client early, you may lose the final usage event. Record token counts yourself, or estimate them, before cancelling.
- Per-client limits. Cap the total bytes you will hold for any one client. Beyond that cap, disconnect instead of buffering.
Exercise
A relay reads provider events in one task and puts each into an asyncio.Queue() with no maxsize. A consumer task writes them to the client. Under what conditions does memory grow, and what are two ways to fix it?
Show answer
Memory grows whenever the client writes slower than the provider produces, because the reader never blocks and the queue keeps accumulating events. This is worst with many concurrent slow clients or long generations. Fix it by giving the queue a maxsize so the reader blocks when it is full, or by replacing the queue with a coalescing buffer that joins pending deltas into one string. Adding a write deadline that disconnects stalled clients and cancels the upstream request also bounds the cost.
Exercise
Why can backpressure not make the model itself generate more slowly, and what does that imply for how long you should wait on a slow client?
Show answer
The provider generates tokens at its own pace, whatever your read rate. Pausing your reads only makes the provider buffer the data, and it may eventually time out or drop the connection. So you should not wait indefinitely. Set a deadline, coalesce while the client catches up, and cancel the upstream request if the client stays stalled past the deadline.