Sub topic 1
Why stream LLM output, and how HTTP streaming works
Prerequisites
This chapter assumes you already have the following:
- Basic Python, including
asyncandawait. - Familiarity with HTTP requests and responses: methods, status codes, headers, and bodies.
- A rough idea of what an LLM chat API is: you send messages and get generated text back.
- A basic FastAPI route and Pydantic model. Later chapters build on these, but this chapter only needs the idea of a route.
You do not need an API key to follow this chapter. The runnable example uses a plain FastAPI app.
Why stream LLM output
A language model produces text one small piece at a time. Each piece is called a token. A token is often a word fragment, a whole short word, or a punctuation mark. The model cannot write the last word of a reply before it has written the first.
A non-streaming endpoint hides this. It waits until the model has finished, then sends the whole reply in one response. For a long answer this can take ten seconds or more. The user sees nothing until the end.
A streaming endpoint sends each token as soon as the model produces it. The total generation time is about the same. What changes is when the user sees the first words.
Two numbers describe the difference:
- Time to first token (TTFT) is the delay before the first piece of text reaches the user.
- Total latency is the delay until the last piece arrives.
Streaming improves TTFT a great deal and leaves total latency about the same. This is called perceived latency. A user who sees text appear within a second believes the app is fast. A user who stares at a spinner for ten seconds does not, even if the final text is identical.
| Approach | First text appears | Last text appears | What the user sees |
|---|---|---|---|
| Non-streaming | After the full generation | After the full generation | Spinner, then the whole reply |
| Streaming | After the first token | About the same as non-streaming | Text growing as it is written |
Streaming has other benefits:
- The user can start reading while the model is still writing.
- The user can stop early if the answer is going the wrong way.
- The server can stop generating when the client leaves, which saves money. A later chapter covers this.
- Long replies are less likely to hit a client or gateway timeout, because bytes keep flowing.
It also has costs. The code is more complex. Errors can happen after the response has started. Proxies may buffer the output and defeat the purpose. Later chapters deal with each of these.
How a normal HTTP response works
In the usual case, the server builds the whole response body, then sends it. The response has a status line, headers, and a body. The headers usually include Content-Length, which tells the client how many bytes to expect. The client reads exactly that many bytes and knows the response is complete.
This only works if the server knows the size before it starts sending. With a model that is still generating, it does not.
How HTTP streaming works
HTTP lets a server send the body in pieces over one connection. The status line and headers go out first. The body follows as a series of writes, and the server keeps the connection open between them. The connection closes, or the body is marked finished, when there is no more data.
There are two ways the client knows where the body ends:
- Chunked transfer encoding. In HTTP/1.1 the server sends
Transfer-Encoding: chunkedinstead ofContent-Length. Each chunk is prefixed with its size, and a final zero-size chunk marks the end. - HTTP/2 and HTTP/3 frames. These versions do not use chunked encoding. They carry the body in data frames, and a flag on the last frame marks the end.
Your application code does not write chunk sizes or frames. The web server (for example Uvicorn) handles that. Your code only has to hand the server data piece by piece.
Three details matter in practice:
- The status code and headers are sent before the body. Once they are out, you cannot change them. If something fails halfway, you can no longer return a
500. You must signal the failure inside the body. This is why mid-stream errors get their own chapter. - A chunk is not a message. Network layers may split or merge chunks. A client must not assume that one read equals one token. A message format with clear boundaries solves this. Server-Sent Events, covered later, is one.
- Every layer between server and client can buffer. The server, a reverse proxy, a CDN, and the client library may each hold data until a buffer fills. Streaming only works if none of them do.
A first streaming endpoint
FastAPI supports streaming through StreamingResponse. You give it an iterator, and it sends each item it yields as a piece of the body. The next chapters explain each part. For now, this example shows the shape.
The endpoint below produces a line every half second. Nothing here calls a model.
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def count():
for i in range(5):
yield f"chunk {i}\n"
await asyncio.sleep(0.5)
@app.get("/count")
async def stream_count():
return StreamingResponse(count(), media_type="text/plain")Save this as main.py and install the packages with pip install fastapi uvicorn. Start the server:
uvicorn main:app --reloadThen call it with curl. The -N flag turns off curl's own output buffering, so you see lines as they arrive:
curl -N http://localhost:8000/countYou should see chunk 0 immediately, then one more line every half second. The whole response takes about two and a half seconds, but the first line shows up at once.
Compare this with a version that builds the full text first and returns it as a normal response. The total time would be the same, yet curl would print nothing for two and a half seconds and then print all five lines together. That gap is the perceived latency problem in small form.
What the generator does here
The function count contains yield, so it is an async generator. Calling it does not run its body. It returns an object that produces values on demand. StreamingResponse pulls one value, writes it to the connection, then pulls the next.
The await asyncio.sleep(0.5) line stands in for waiting on a model. While the generator is waiting, the event loop is free to serve other requests. This is why async matters for streaming. A blocking time.sleep in this place would freeze the whole server for every client. The next chapters cover async generators in detail.
Common mistakes
- Collecting all the tokens into a list, then returning them. This works but is not streaming. The client gets nothing until the list is full.
- Using a blocking call inside the generator. A synchronous model client or
time.sleepstalls the event loop and delays other users. - Expecting to change the status code after the first chunk. Headers are already sent.
- Testing only through a proxy that buffers, then concluding that streaming does not work. Test directly against Uvicorn first, then add layers one at a time.
- Assuming one network read equals one token. Chunks can be split or merged in transit.
When streaming is not worth it
Streaming is not always the right choice.
- If the reply is short, such as a classification label, the gain is small.
- If you must validate or post-process the whole reply before showing any of it, you cannot show tokens early. Content filters that need the full text are an example.
- If the client is another service that needs the complete result, streaming only adds complexity.
- If the platform in front of your app buffers responses and you cannot change that, streaming will not reach the user.
For chat-style interfaces, streaming is nearly always worth the added work.
Exercise
A non-streaming endpoint takes 8 seconds to generate a reply. You switch to streaming and the model still takes 8 seconds in total, but the first token arrives after 0.6 seconds. Which numbers change, and why does the user feel the app is faster? Also, name one thing you cannot do once the first chunk has been sent.
Show answer
Time to first token drops from about 8 seconds to about 0.6 seconds. Total latency stays about 8 seconds, because the model still needs the same time to write the whole reply. The user feels the app is faster because text starts appearing almost immediately and they can read while the rest is generated. Once the first chunk is sent, the status code and headers are already on the wire, so you cannot change the status code (for example, to a 500) if an error occurs later. You must report the error inside the body.
Exercise
Your streaming endpoint works when you call Uvicorn directly with curl -N, but through a reverse proxy the client receives the whole reply in one burst at the end. Where do you look first, and which part of the HTTP response is relevant to the problem?
Show answer
Look at the reverse proxy, because it is the layer that was added between the working and failing setups, and proxies often buffer response bodies until they are complete or a buffer fills. Check the proxy's response buffering setting and the response headers that tell it not to buffer. A later chapter covers these headers and settings in detail.