By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Speed is experienced as time-to-first-token, not time-to-last-token. A three-second answer that starts streaming at 400 ms feels faster than a two-second answer that arrives all at once, because the agent can start reading while the rest generates. Streaming is therefore a latency feature, and it changes the failure model: once bytes are on the wire, the response cannot be a clean 500 any more.
The gateway streams server-sent events: one data: line per event, a start event, token events, then a terminal event that carries the request ID, token usage and any degradation flag. The deadline ticks from admission — not from the model call — and the stream must stop cleanly when the deadline expires or the client goes away.
import asyncio
import json
from collections.abc import AsyncIterator
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
app = FastAPI()
GATEWAY_DEADLINE_SECONDS = 4.0
async def stream_draft(request: Request) -> AsyncIterator[str]:
loop = asyncio.get_running_loop()
deadline = loop.time() + GATEWAY_DEADLINE_SECONDS
yield 'data: {"event": "start"}\n\n'
for chunk in ("Northline ", "clause 4.2 ", "supports a delay credit."):
# Stop paying for tokens nobody will see.
if await request.is_disconnected():
return
if loop.time() > deadline:
yield 'data: {"event": "deadline_exceeded"}\n\n'
return
payload = json.dumps({"event": "token", "text": chunk})
yield f"data: {payload}\n\n"
await asyncio.sleep(0.01)
yield 'data: {"event": "done"}\n\n'
@app.post("/v1/assist/stream")
async def assist_stream(request: Request) -> StreamingResponse:
return StreamingResponse(
stream_draft(request),
media_type="text/event-stream",
)A four-second end-to-end budget is not one four-second timeout. It is a set of stage budgets that add up, each with an owner. Propagate the remaining budget to every downstream call instead of giving each layer its own independent timeout; otherwise a slow retrieval and a slow model each think they have four seconds and the caller waits eight.
| Stage | Budget | Owner | On breach |
|---|---|---|---|
| Gateway admission, auth, tenant lookup | 50 ms | Platform | Fail fast with 401/403/429 |
| Policy retrieval | 350 ms | Waypoint service | Use cached policy snapshot, flag it |
| Model first token | 1,200 ms | Model provider | Fall back to the cheaper alias |
| Model full answer | 2,800 ms | Model provider | Truncate, mark degraded, finish |
| Approval record write | 150 ms | Data layer | Do not execute; return 503 |
| Response serialisation | 50 ms | Gateway | Log and return a structured error |
await request.is_disconnected() between chunks is enough; check between tokens, not after every byte.cancelled status; it counts toward cancellation rate and, indirectly, toward cost.Key takeaways
Streaming is a latency feature; time-to-first-token is the metric users feel.
Budget the deadline by stage, propagate the remaining time downstream, and keep provider timeouts shorter than the budget.
Cancel on disconnect: detect between chunks, stop provider work and release concurrency slots.
After the first byte, errors become terminal events or degradation flags — design them before launch.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.