Streaming LLM Responses:Proxies, Timeouts, Resumption
Streaming LLM responses breaks in the proxy layer, not the model: response buffering, the four idle-timeout clocks, and what resumption really costs you.
Your streaming bug is in the proxy, not the model
A token stream that works on localhost and stalls in production is almost never a model problem. Three layers sit between the model and the browser, and each one has a default that is wrong for streaming: a reverse proxy or ingress that collects the response body before forwarding it, a load balancer and a CDN that each count idle time on their own separate clock, and a client that has no way to rejoin a stream once it drops.
The reason this keeps catching teams out is that every one of those layers was tuned for request and response. A JSON endpoint that answers in 200 milliseconds wants buffering, because buffering means fewer writes and better compression, and a 60 second idle timeout is generous for it. A token stream inverts both requirements. You want bytes forwarded the instant they exist, and you want the connection held open for minutes while a model reasons.
What follows is the transport layer in roughly the order it fails: the wire format and what most applications quietly give up, buffering, the timeout clocks, stream resumption, and the checks that surface all of it before your users do.
Server-sent events is a small spec, and most apps quietly leave it
The format is defined in section 9.2 of the HTML Living Standard, and it is short. A response whose Content-Type is not text/event-stream fails the connection outright. Encoding is not negotiable: the spec says event streams are always decoded as UTF-8 and that there is no way to specify another character encoding. The body is newline-delimited field lines, and a line that starts with a colon is a comment the client ignores.
Two fields do real work. An id line sets the client's last event ID, which the browser sends back in the Last-Event-ID request header when it reestablishes the connection, and the spec is explicit that this buffer does not get reset, so the value persists until the server sends a new id. A retry line, when its value is only ASCII digits, sets the reconnection time. The spec refuses to pick a default for that, saying only that it must initially be an implementation-defined value, probably in the region of a few seconds. A server that wants the client to stop reconnecting answers 204.
Here is the catch that shapes almost every LLM chat implementation. The browser's EventSource constructor accepts a URL and exactly one option, withCredentials. No custom request headers, no request body. A chat turn needs an Authorization header and a JSON payload, so teams reach for fetch with a ReadableStream and parse the event stream by hand. In doing that they also give up automatic reconnection, the retry hint and all Last-Event-ID handling, usually without anyone writing down that they made the trade.
It is a defensible trade. Just make it deliberately, because if you hand-roll the reader you own reconnection and nothing in the platform is coming to help. Keep the wire format anyway. It costs nothing, and it means every proxy, log pipeline and engineer with curl can read your stream without a custom client.
One more thing the spec warns about, which matters once a user has your app open in several tabs. Clients that honour HTTP's per-server connection limitation might run into trouble when opening multiple pages from a site if each page has an EventSource to the same domain. The spec's own suggested workaround is to share a single connection through a shared worker. Over HTTP/2 the streams multiplex onto one connection and the problem largely dissolves, which is a reason to confirm what your edge actually negotiates rather than what your framework assumes.
Buffering: the proxy that holds your tokens until the answer is finished
The symptom is unmistakable once you have seen it. Nothing happens for twenty seconds, then the entire answer lands at once. That is a proxy accumulating the response body before passing it on. Your application's own time-to-first-token metric looks healthy, because the application did stream; the user's time to first token is the full generation time.
Nginx-family proxies are the common cause, because buffering proxied responses is a sensible default for ordinary traffic. Apache APISIX ships a plugin whose entire purpose is to switch it off, and its documentation describes the effect precisely: with proxy buffering disabled, nginx streams the upstream response directly to the client without accumulating it in memory or on disk first. That plugin's own disable flag defaults to false, so streaming is something you opt into per route.
The per-response escape hatch is a response header. Kong's guidance for server-sent events tells the upstream to send the X-Accel-Buffering: no response header for SSE connections, which it says explicitly disables buffering for those responses when proxied through Kong Gateway. Set it from the application, on streaming endpoints only. Because it rides along with the response it also survives infrastructure you do not control. Kong's own advice is worth repeating: do not disable proxy buffering globally to fix a streaming endpoint, because the rest of your traffic genuinely wants it.
Buffering is not only an edge concern. Response compression middleware will happily accumulate a stream in order to compress it, some serverless adapters collect a body before returning a response, and a framework that advertises streaming may still flush on a schedule of its own. So test the whole chain, not a layer of it. Run curl with the no-buffer flag against the public hostname and watch the arrival times, rather than curling the application port behind everything.
Timeouts: four clocks, and the shortest one decides
An idle timeout is not a request timeout. It measures quiet time on the connection, and a model that spends forty seconds on a long reasoning pass before emitting a first token is perfectly quiet.
On AWS, the Application Load Balancer attribute is idle_timeout.timeout_seconds, and the documentation states that the default is 60 seconds. The same page explains the piece that causes most of the confusion: when processing a request the load balancer maintains two connections, one with the client and one with the target. There is also a separate client_keep_alive.seconds attribute whose default is 3600 seconds, which is a different knob for a different purpose and will not save a stream that goes quiet for longer than the idle timeout.
On Cloudflare, the relevant number is the Proxy Read Timeout. The error 524 documentation says the status is returned when the origin did not provide an HTTP response before the default 125 seconds, and separately when a write did not complete before the 30 seconds Proxy Write Timeout, which it states cannot be adjusted. Enterprise zones can raise the read timeout as far as 6,000 seconds; the documented option for everyone else is to move long-running endpoints to a subdomain that is DNS-only rather than proxied. Cloudflare's connection limits page adds the rule that decides every one of these arguments: when both layers apply, the shorter timeout takes precedence.
One honest gap, because it is the question everyone asks. Cloudflare's documentation frames the read timeout in terms of the origin providing a response, and does not state whether bytes trickling down an already-open stream reset that timer. Do not assume an answer in either direction. Force a generation longer than the limit behind your real edge configuration and observe what happens, because the behaviour is what you are shipping, not the reading of the doc.
The general fix is a heartbeat, and the spec anticipated this long before anyone streamed a token: authors can include a comment line, one starting with a colon character, every 15 seconds or so, specifically so that proxies do not drop a connection they consider idle. Model providers do the same at their own layer. Claude's streaming documentation notes that event streams might also include any number of ping events. Your service should do both things: forward the provider's keepalives rather than filtering them out as noise, and emit its own on a timer, so that no clock anywhere in the path ever sees an idle connection.
Resumption is a product decision you are probably making by accident
Closing a tab does not stop a generation. Vercel's AI SDK documentation states it plainly: closing a tab, refreshing the page or calling stop only closes the current HTTP connection, and should not cancel the underlying generation. So the model continues producing tokens you are billed for, writing into a socket nobody is reading, while the user loses the answer entirely. Doing nothing here is a decision, and it has a line on your invoice.
The working shape is three pieces. Persist the assistant message as it is produced, keep a per-conversation pointer to whichever stream is currently live, and expose a second endpoint the client can call to rejoin. The AI SDK's reference implementation writes the stream into Redis through its resumable-stream package, stores an activeStreamId on the chat record, clears that field when the stream ends, and has the resume endpoint answer 204 No Content when there is nothing active. Replays are full replays by default, meaning the client throws away the partial response it was holding and rebuilds from the beginning.
This design is contested, and the disagreement is instructive. Ably, which sells a competing transport and therefore has an interest, argues that the Redis-plus-SSE approach reliably handles only a full page reload, and that SSE as a protocol carries no session identity, no reconnect protocol and no fan-out, so what you actually need is offset-based replay where a reconnecting client presents its last known position. Several of its specific claims conflict with the AI SDK's own documentation, including stream expiry behaviour and whether the client reconnects when a backgrounded tab becomes visible again. Resolve it with a test rather than a vendor page: start a long generation on a phone, switch apps for a minute, come back, and see what survives.
Then decide what your stop button means. A real stop needs its own server endpoint that cancels the upstream call, persists whatever was generated up to that point, and clears the active-stream pointer. Without that, stop means hide the output and keep paying for it.
Five checks that find this before your users do
Check 1 — Time to first byte, measured at the edge. Run curl with buffering disabled against the public hostname and note when the first data line arrives. If that interval matches total generation time, something between your application and the client is buffering, and no application-side metric will ever tell you so.
Check 2 — A generation longer than every timeout in the path. Force a long response and then walk the chain, writing down four numbers: the application read timeout, the ingress timeout, the load balancer idle timeout and the CDN read timeout. The smallest is your real ceiling. A 60 second load balancer default sitting behind a 125 second CDN timeout typically shows up as a stream that truncates silently, with no error recorded anywhere you are looking.
Check 3 — Abort propagation. Disconnect a client mid-stream and confirm the upstream provider request is genuinely cancelled rather than orphaned. The server has to notice the closed socket and abort the call it made; nothing does this for you. Whether providers charge for tokens generated after an abort is not documented consistently enough to take on faith, so verify it against your own invoice rather than trusting either claim.
Check 4 — The resume path, including its empty case. Reload mid-generation and confirm the client rejoins and the text is not duplicated. Then reload after the response has finished and confirm the resume endpoint returns its no-content answer promptly, rather than replaying a completed stream or hanging until a timeout.
Check 5 — Unknown events, and several tabs at once. Claude's streaming documentation is explicit that new event types may be added and that your code should handle unknown event types gracefully, so a parser that throws on an unrecognised event is a scheduled outage. Then open the same conversation in four tabs and watch what happens to the fourth, keeping in mind the connection limitation the SSE spec warns about and whether your edge is really serving HTTP/2.
Working with Darvi Labs
This is the layer we work in. Darvi Labs is a software engineering team in Kathmandu building agentic AI features and the scalable web architecture underneath them, which in practice means the streaming transport, the resumption design and the edge configuration that decides whether a long generation survives a mobile network. It is unglamorous work, and it is most of the difference between a good model and a product that feels good to use.
There is more on how we approach agentic systems and web architecture on our blogs page, and examples of delivered work on our portfolio page. If you are evaluating an engineering partner for AI product work, get in touch through the Contact page and we will talk about your stack rather than ours.
Thinking through a similar decision?
Send us the constraint, the workflow, or the decision that keeps resurfacing. We can help clarify what should change first.
Start a conversation→Keep the decision trail moving.
Three more short reads from DarviLab work across product, systems, and operating constraints.
Nepal's Software Talent Pool: Size, Shape and Limits
Nepal's software talent pool, in figures: how big it really is, where the engineers are trained, what the employability gap means, and who keeps leaving.
Outsourcing HIPAA and PCI Work to an Offshore Team
Outsourcing HIPAA and PCI work offshore: what the BAA chain must cover, how to keep your developers out of PCI scope, and what DORA adds for EU firms.
Zero-Downtime Postgres Schema Migrations Under Load
Zero-downtime Postgres schema migrations: how the ACCESS EXCLUSIVE lock queue stalls reads, why lock_timeout and retries fix it, when expand-contract pays.