Sub topic 3
How HTTP can deliver a response in pieces
This chapter explains the HTTP mechanics that make streaming possible. It assumes you know basic HTTP requests and responses (status line, headers, body) and can read Python and JavaScript. SSE, the format most LLM APIs layer on top of this, comes in the next chapter.
A response does not have to arrive all at once
A server that returns a complete JSON body usually sends a Content-Length header. The client reads that many bytes and knows the response is finished. This works only if the server knows the final size before it sends the first byte. A model that is still generating text cannot know that.
HTTP has other ways to mark the end of a body. Each one lets the server write bytes as they become available.
| Mechanism | How the client knows the body is over | Used for streaming |
|---|---|---|
| `Content-Length` | After the declared number of bytes | No. The size must be known up front. |
| `Transfer-Encoding: chunked` (HTTP/1.1) | A final chunk of size zero | Yes. This is the usual choice. |
| Connection close (HTTP/1.0 style) | The server closes the socket | Rarely. The client cannot tell a clean end from a crash. |
| HTTP/2 or HTTP/3 data frames | A frame with the end-of-stream flag | Yes. Framing is built into the protocol. |
Headers are sent first and are final. Once the server has sent 200 OK, it cannot change the status code. This matters later for error handling, because a failure in the middle of a stream can't be reported with a 500.
The chunked wire format
With chunked encoding, the body is a series of chunks. Each chunk starts with its size in hexadecimal, then \r\n, then that many bytes of data, then \r\n. A chunk of size 0 ends the body.
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
9\r\n
Streaming\r\n
3\r\n
is\r\n
0\r\n
\r\nThe first chunk is 9 bytes (Streaming) and the second is 3 bytes ( is). The client sees the first chunk as soon as it arrives. It does not wait for the rest.
Application code almost never sees this framing. HTTP libraries remove it and hand you the payload bytes. HTTP/2 and HTTP/3 do not use Transfer-Encoding: chunked at all. They split the body into DATA frames, and your code looks the same.
Seeing it happen
The program below runs a small HTTP/1.1 server that writes a chunk every half second. A client then reads the response as it arrives and prints the elapsed time for each piece. It uses only the Python standard library.
import threading
import time
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" # chunked encoding requires HTTP/1.1
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
for word in ["Streaming", " is", " incremental", "."]:
data = word.encode("utf-8")
# chunk = size in hex, CRLF, data, CRLF
self.wfile.write(f"{len(data):x}\r\n".encode() + data + b"\r\n")
self.wfile.flush()
time.sleep(0.5)
self.wfile.write(b"0\r\n\r\n") # zero-length chunk ends the body
self.wfile.flush()
def log_message(self, *args):
pass # keep the output clean
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
conn = HTTPConnection("127.0.0.1", server.server_address[1])
conn.request("GET", "/")
response = conn.getresponse()
print("status:", response.status, "| content-length:", response.getheader("Content-Length"))
start = time.monotonic()
while True:
piece = response.read1(1024) # returns as soon as some data is available
if not piece:
break
print(f"{time.monotonic() - start:4.1f}s {piece.decode('utf-8')!r}")
conn.close()
server.shutdown()The status line shows content-length: None. Each piece prints about half a second after the previous one, instead of all four arriving together after two seconds. The method that makes this work is read1. Calling response.read() would block until the whole body had arrived, which hides the streaming.
Chunks are not messages
The most common mistake is to treat one network chunk as one meaningful unit. Chunk boundaries are set by the server's write calls, and many layers can move them:
- TCP and TLS. A single server write can arrive as two reads, and two writes can arrive as one. TLS records and packet sizes add further splits.
- Proxies and libraries. An intermediary may re-chunk the body. Your HTTP client may merge several small chunks into one read.
- UTF-8 characters. A multi-byte character such as an emoji can be cut between two reads. Decoding each read separately raises an error or produces garbage. Use an incremental decoder, such as
codecs.getincrementaldecoder("utf-8")in Python orTextDecoderStreamin a browser.
The rule is that the transport gives you a stream of bytes, and you must find the message boundaries yourself. An LLM API does this with the event format in the next chapter. The chapter on parsing covers reassembling events that split across reads.
Conditions that defeat streaming
Streaming is a property of the whole path, not just your server. Any layer that waits to see the full body before passing it on removes the effect, even though the response is technically still chunked.
- Compression. A gzip encoder may hold output until its internal buffer fills. Many streaming endpoints skip compression or flush after each event.
- Server buffering. Frameworks and WSGI servers may buffer small writes. You need a response type that flushes (for example, a streaming response in your framework).
- Intermediaries. Reverse proxies, CDNs and some serverless platforms buffer responses by default. A later chapter covers these.
- Client reads. Calls such as
response.read(),response.text()orresponse.json()wait for the entire body.
Two behaviors follow from the protocol:
- Connection limits. With HTTP/1.1, a browser holds one TCP connection open per active stream, and browsers cap connections per host. HTTP/2 multiplexes many streams over one connection and avoids this limit.
- Idle timeouts. A stream that sends nothing for a long time (for example, while the model "thinks") can be closed by a proxy or load balancer. Servers send periodic keep-alive bytes to prevent this.
Failure signals
If the server fails after sending headers, it cannot send a new status code. The client sees one of these:
| Situation | What the client observes |
|---|---|
| Clean finish | The final zero-length chunk arrives, and the read ends normally. |
| Server crash or dropped connection | The read ends with an error, such as an incomplete chunked read. |
| Failure the server detected and reported | An error message inside the body, using a format both sides agreed on. |
A client that treats "the read ended" as success will silently accept truncated output. Check for a protocol-level completion signal (the final chunk, plus any end marker the API defines) before treating the text as complete.
Exercise
A teammate's streaming endpoint sets Transfer-Encoding: chunked and writes a token every 100 ms. In local testing the client shows tokens one at a time, but behind the company's reverse proxy the full answer appears all at once after 10 seconds. The status is 200 and the body is correct. Name two layers that could cause this and one way to confirm which one it is.
Show answer
The most likely causes are a reverse proxy or CDN that buffers the response before forwarding it, and gzip compression that holds output until its buffer fills. A server framework that does not flush small writes is also possible. To confirm, run curl -N directly against the application server, bypassing the proxy. If pieces appear one by one there but not through the proxy, the proxy is buffering. If the direct request is also delayed, check compression and server flushing.