Sub topic 13
Back Pressure in TCP, HTTP/2, and Reactive Streams
What this chapter assumes
You should know what a bounded queue is and why a producer waits when it is full. You should also be comfortable reading short Python asyncio examples and know what a socket is. The earlier chapters on bounded queues and back pressure showed the idea inside one process. This chapter shows the same idea in three systems you already use: TCP, HTTP/2, and reactive streams.
All three use the same mechanism. The receiver tells the sender how much more it can accept, and the sender must not exceed that amount. This is called credit-based flow control. Seeing it in these systems helps you recognize the pattern, and it shows where your own code can accidentally break it.
TCP: the receive window
Every TCP connection has a receive buffer in the kernel. The receiver puts its free buffer space in each acknowledgment, as the receive window. The sender may have at most that many unacknowledged bytes in flight.
When your application reads slowly, the buffer fills and the advertised window shrinks. At zero the sender stops transmitting and sends occasional small zero-window probes to learn when space returns. The sender's own kernel send buffer then fills too. A blocking send() call waits at that point. A non-blocking one returns EAGAIN or EWOULDBLOCK. The slow consumer's speed has reached the producer's code without any application message.
Window scaling, a TCP option, lets the window exceed 64 KiB. Modern kernels also grow the buffers automatically. A large buffer is a large queue, so a slow reader can still absorb many megabytes before the sender notices.
Using TCP back pressure from asyncio
In asyncio streams, writer.write() never blocks. It copies data into a user-space buffer that grows without limit. await writer.drain() is the back pressure point. It returns immediately while the buffer is below the high-water mark. Above it, drain() suspends until the socket has accepted enough data.
import asyncio
import time
async def slow_server(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
while await reader.read(65536):
await asyncio.sleep(0.01) # simulate slow processing
writer.close()
async def main() -> None:
server = await asyncio.start_server(slow_server, "127.0.0.1", 9009)
async with server:
_, writer = await asyncio.open_connection("127.0.0.1", 9009)
chunk = b"x" * 65536
start = time.monotonic()
for _ in range(200):
writer.write(chunk)
await writer.drain() # waits when the server falls behind
writer.close()
await writer.wait_closed()
print(f"sent 200 chunks in {time.monotonic() - start:.2f}s")
asyncio.run(main())The client could generate 12.8 MB almost instantly. The elapsed time shows it is paced by the server's reads. Delete the await writer.drain() line and the loop finishes at once. The data is then sitting in the client's memory, which is an unbounded queue.
HTTP/2: stream and connection windows
HTTP/2 multiplexes many streams over one TCP connection. TCP's window covers the whole connection, so it cannot slow one stream without slowing all of them. HTTP/2 therefore adds its own flow control on top, with two levels:
- Each stream has a window.
- The connection as a whole has a window, which is stream 0 in the protocol.
Only DATA frames count against the windows. The default window is 65,535 bytes, and SETTINGS frames can change the stream default. A sender subtracts each DATA frame's size from both windows. When either reaches zero, it stops sending on that stream. The receiver sends a WINDOW_UPDATE frame to grant more credit, and a well-behaved receiver does this only after the application has consumed the data.
This design has three consequences.
- A slow stream does not block fast streams, as long as the connection window has room. One slow download can still use up the shared connection window if its data sits unread, so receivers must size and release windows carefully.
- Windows cannot be turned off. A receiver that wants no limit can grant a very large window, but then it has chosen unbounded buffering.
SETTINGS_MAX_CONCURRENT_STREAMSlimits requests, not bytes. It works like the in-flight limit from the earlier chapter. A server that is at its limit refuses new streams withREFUSED_STREAM, and clients can safely retry them because nothing was processed.
gRPC runs on HTTP/2 and inherits these windows. Its client and server libraries also expose a readiness signal, such as isReady() and onReady in gRPC-Java. A streaming handler that ignores it and keeps calling send fills memory, just as write() without drain() does.
Reactive streams: explicit demand
TCP and HTTP/2 count bytes. Reactive streams count items. The Reactive Streams specification, which Java adopted as java.util.concurrent.Flow, defines four interfaces: Publisher, Subscriber, Subscription, and Processor. The rule that matters is this: a Publisher may call onNext only as many times as the subscriber has requested through Subscription.request(n).
In this model the consumer pulls data. A subscriber that asks for 10 items gets at most 10, then waits until it asks again. Libraries such as Project Reactor and RxJava are built on this contract.
Two details cause most problems:
request(Long.MAX_VALUE)means unbounded demand. Many operators use it by default, and then back pressure no longer exists.- When a source cannot be slowed, such as a timer or user input, the pipeline needs a policy for the excess. Reactor's
onBackpressureBuffer,onBackpressureDrop, andonBackpressureLatestare exactly the choices from earlier chapters: queue it, shed it, or keep only the newest.
Python's async generators are pull-based in the same way. The producer code runs only when the consumer asks for the next item:
import asyncio
async def source(count: int):
for i in range(count):
print(f"produced {i}")
yield i
async def main() -> None:
async for item in source(3):
await asyncio.sleep(0.1) # slow consumer
print(f"consumed {item}")
asyncio.run(main())The output alternates produced 0, consumed 0, produced 1, and so on. The producer never gets ahead, so there is no queue to overflow.
Comparing the three
| Property | TCP | HTTP/2 | Reactive streams |
|---|---|---|---|
| Unit of credit | Bytes | Bytes in `DATA` frames | Items |
| Signal from receiver | Window field in ACKs | `WINDOW_UPDATE` frame | `request(n)` call |
| Scope | One connection | One stream and the whole connection | One subscription |
| Sender when credit is zero | Blocks, or gets `EAGAIN` | Stops sending `DATA` | Stops calling `onNext` |
| Common way it is defeated | Unbounded user-space buffer | Huge windows, or a proxy that buffers | `request(Long.MAX_VALUE)` |
Where back pressure stops
Protocol-level back pressure works one hop at a time. A proxy that reads quickly from a client and buffers the data in memory hides a slow upstream, and the client sees no slowdown. The proxy's memory becomes the queue. The same happens inside your service when you read from a socket and put each message into an unbounded list or an unbounded queue. Back pressure only crosses a boundary if the code at that boundary waits for the downstream signal.
Back pressure also does not protect you from many independent clients. A thousand clients each sending at a polite rate can still exceed capacity. TCP slows each connection but cannot reject any of them. Slowing senders is not enough in that case, and you need load shedding or an in-flight limit at admission.
Exercise
A streaming service reads messages from a TCP connection with asyncio, parses each one, and calls writer.write(response) to reply, without ever awaiting drain(). Clients on slow networks cause the process's memory to grow until it is killed. Which mechanism is being bypassed, and what is the fix?
Show answer
TCP flow control is being bypassed on the sending side. write() copies responses into an unbounded user-space buffer, so the slow client's closed window never reaches the handler. Await writer.drain() after writing, so the handler pauses while the client is behind. For clients that stay too slow, also add a timeout on drain() and close the connection.
Exercise
An HTTP/2 receiver advertises a window of 65,535 bytes and its application stops reading from one stream. What does the sender do on that stream, and what happens to other streams on the same connection?
Show answer
The sender sends up to 65,535 bytes of DATA on that stream, then stops until it receives WINDOW_UPDATE. Other streams continue as long as the connection-level window has room. The unread data still counts against the connection window, so enough stalled streams can eventually block every stream.
Exercise
A Reactor pipeline reads from a fast source and calls a slow downstream service. A developer adds an operator that requests Long.MAX_VALUE from upstream. Why does this remove back pressure, and what should replace it?
Show answer
Unbounded demand tells the publisher it may emit as fast as it can, so items pile up in a buffer before the slow stage. Replace it with bounded demand, such as a small prefetch, so the source emits only as the slow stage finishes items. If the source cannot be slowed, choose an explicit overflow policy such as drop or keep latest.