A RAG answer takes seconds to finish. Users judge the wait by when something appears. So: what does streaming change in a FastAPI endpoint, and what breaks it?
Short answer: send the retrieved sources as the first SSE event, then the tokens. In my test the first byte arrived after 52 ms instead of 1,664 ms, and the first token after 453 ms. The total time stayed the same (1,673 ms vs 1,664 ms). The most common way to break it is a blocking call inside an async generator: with 5 clients the median first byte rose to 3,280 ms.
Tested on a 2 vCPU GitHub runner (CPU only), Python 3.12, fastapi 0.161.1, starlette 1.9.0, uvicorn 0.54.0, httpx 0.28.1, real uvicorn server on localhost. Retrieval (50 ms), LLM first token (400 ms) and token rate (60 tokens x 20 ms) are simulated with asyncio.sleep, so absolute numbers are not what a real model gives.
Setup
The endpoint is a plain StreamingResponse with media_type="text/event-stream" and hand-formatted events. Recent FastAPI versions also ship a dedicated EventSourceResponse in fastapi.sse; I did not test it, and the manual version works the same way on older releases.
The stream has three kinds of event:
-
sources: one event with the retrieved chunks (sent right after retrieval). -
token: one event per token. -
done: a final marker so the client knows the stream ended cleanly.
The comparison endpoint does the same work and returns one JSON body at the end. A client script (httpx) times the first byte, the sources event, the first token event and the end. Each case ran in a real uvicorn process.
Results
All times in milliseconds (median over runs; last column is the worst first byte).
| Case | First byte | Sources | First token | Total | Worst first byte |
|---|---|---|---|---|---|
| Non-streaming JSON, 1 client | 1664 | - | - | 1664 | 1666 |
| SSE sources-first, 1 client | 52 | 52 | 453 | 1673 | 53 |
| SSE sources-first, 20 concurrent | 71 | 71 | 472 | 1715 | 86 |
| SSE, 5 concurrent (control) | 54 | 54 | 455 | 1685 | 56 |
SSE + blocking time.sleep, 5 concurrent |
3280 | 3280 | 3681 | 4894 | 6510 |
SSE + GZipMiddleware, 1 client |
52 | 52 | 453 | 1673 | 53 |
What the numbers mean
- Streaming moves the first visible byte, not the finish. First byte improved by 1,612 ms. The first token showed up 401 ms after the sources, which is the simulated model delay. Total time did not improve.
- Sources first is nearly free. Retrieval is done before generation starts, so the user sees the evidence 52 ms in while the model is still thinking.
- 20 concurrent streams were fine (71 ms median first byte), as long as the event loop is not blocked.
-
Blocking the loop is the real hazard. The
time.sleepvariant does the same simulated work with a blocking call. With 5 clients the median first byte was 3,280 ms, about 61 times the control (54 ms), and the worst was 6,510 ms. One client's stream stalls everyone else's. In real code the culprit is a sync SDK call, a CPU-heavy rerank or a blocking DB driver insideasync def. Use the async client, or run sync work in a thread (run_in_threadpool,asyncio.to_thread). -
GZip did not buffer the stream here. Starlette's
GZipMiddlewareleavestext/event-streamalone, and all 62 events arrived as separate chunks, with first byte unchanged at 52 ms. Other middleware, or a proxy, may behave differently.
Caveats
- The model and retrieval are fakes. A real provider adds network jitter and a longer, variable first-token time; the shape of the gain (first byte early, total unchanged) should hold, the numbers will not.
- Localhost has no proxy. nginx buffers responses by default; the
X-Accel-Buffering: noheader below asks it not to, but I did not test it. - I did not test client disconnects. In production, stop the upstream LLM call when the client leaves, or you pay for tokens nobody reads.
- The blocking case is deliberately extreme (every token blocks). Shorter blocks hurt less but still add to every stream's latency.
Copyable code
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
def sse(event: str, data) -> bytes:
return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()
@app.get("/ask")
async def ask(q: str):
async def events():
chunks = await retrieve(q) # async vector search
yield sse("sources", chunks) # evidence first
async for token in llm_stream(q, chunks): # async client, never blocking
yield sse("token", token)
yield sse("done", {})
return StreamingResponse(
events(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
retrieve and llm_stream are your own functions. The full test server and benchmark script are on the original post.
Rule of thumb
- Send
sourcesas the first event, then tokens, then an explicitdone. - Everything inside the generator must be
await-able or pushed to a thread. - Measure first byte under 5-20 concurrent clients, not just one, and put that number in CI.
- Test through your real proxy before shipping; localhost results do not cover buffering.
If you want to check the sources the model cites afterwards, I wrote up validating LLM citations in FastAPI.
Top comments (6)
The separate sources event at 52 ms makes the waiting period useful, but I would label those items as retrieved candidates in the UI. At that point the model has not yet established which passages its answer will actually use, and a later citation can select only a subset.
A final citation map, attached to the completed answer, would let the interface promote the used sources without silently presenting every retrieved chunk as support. That preserves the early feedback benefit while keeping retrieval provenance distinct from answer-level attribution, including when generation ends before the done event.
Agreed, and the demo blurs exactly that. The first event is the top-k from retrieval, so "Sources" is the wrong label for it; "Retrieved" is closer.
What I'd change: keep the early event for the 52 ms feedback, then put a cited list in the done event (chunk ids the answer actually referenced), and have the UI promote only those. If the stream ends without a done event, the UI keeps the retrieved list greyed out instead of upgrading it to citations.
That also gives a cheap metric: cited / retrieved per answer. If it sits near 1 of 5 most of the time, k is probably too high.
Promoting only the done-event IDs gives the UI a much clearer completion contract. I would be cautious about using a 1-of-5 citation ratio alone to lower k, though. The other passages might resolve ambiguity or corroborate the selected source without becoming separate citations.
An ablation that removes those four candidates and checks the resulting answers would distinguish unused retrieval from useful supporting context. The ratio is a useful diagnostic for choosing cases to inspect, but it does not by itself measure how much evidence the model needed.
Fair, and sorry this sat for a while. A passage can do its job without being cited: it rules out the wrong reading of the question, or it's the second source that makes the model confident enough to answer at all.
So I'd use cited/retrieved only to pick which answers to look at. For those, your ablation is the real test: drop the uncited candidates, regenerate, and check whether the answer or its citations change. If nothing changes across a batch, k can come down. If answers get vaguer or start refusing, the "unused" passages were carrying weight.
Using cited-over-retrieved purely as a triage filter for the ablation pass is a clean workflow. Running regeneration ablations on every query gets expensive quickly, whereas targeting only the low-ratio outliers keeps the cost bounded while still catching passages that quietly act as disambiguators.
One nuance when you drop uncited candidates is checking confidence shifts alongside answer diffs. Even when the final text stays identical, watching whether the model starts hedging or swaps which passage it cites tells you whether the removed context was stabilizing the decision.
Agreed, an identical answer can still hide a shift. The cheap version I'd log per ablated query: did the set of cited ids change, did a hedge or refusal appear that wasn't in the full run, and did the answer text change at all. A citation swap with the same text is the interesting case, because it means the dropped passage was steering which source the model trusted.
I haven't measured those columns yet. When I rerun the ablation I'll add them and post the counts here.