Why your LLM app works locally and gets cut off in production
Anyone who has shipped a generative AI feature knows the pattern. A chat app, an agent or a RAG endpoint works perfectly on a laptop. Deployed, short answers still work, but long ones stop halfway, the browser shows a 502, 504 or 524, or the request hangs with no useful log line. Neither the model nor the code changed. What changed is that the request now crosses several pieces of infrastructure, each running its own clock.
We see this from the host side. At Hal9 we build Cloudish, a host where AI agents deploy apps, and the clocks described below exist on every platform, whichever one you choose. This article is generic though; nothing described here is particular to Cloudish in any way.
ยท ยท ยท ยท ยท
On localhost there is usually one hop, straight to a development server that has no reason to cut anything. In production the same request may go through a CDN, a load balancer, a platform router, a reverse proxy, a serverless runtime and finally your app server, which itself calls a model API through an HTTP client with its own timeouts. LLM workloads are unusually good at hitting these limits because they break the assumption most web infrastructure was tuned for, namely that a response starts quickly and finishes quickly. A reasoning model may think for a long time before its first visible token, an agent may sit silently inside a tool call, and a long generation can keep a single response open for minutes.
This article covers which clocks exist, what the major platforms document, why streaming fixes some limits but not others, and how to measure your own stack instead of guessing.
Three clocks (and a fourth one inside your server)
"Timeout" is used for at least three different measurements, and mixing them up is how a fix ends up not working. Raising a total-duration limit does nothing for an idle timeout, and sending heartbeats does nothing for a total-duration limit.
| Clock | What it measures | Reset by new bytes? | Typical owner |
|---|---|---|---|
| Time to first byte | From the request being forwarded until the first byte of the response comes back | Ends at the first byte | Platform routers, CDNs, reverse proxies |
| Idle (read) timeout | The gap between two successive reads or writes on the connection | Yes, every byte resets it | Load balancers, proxies, HTTP clients |
| Total duration | Wall-clock time of the whole request or function invocation | No | Serverless platforms, request-based runtimes, API gateways |
| Worker liveness | How long a worker process may stay "silent" before the app server kills it | Depends on the worker model | App servers such as Gunicorn |
The fourth row is easy to forget because it lives in your own container. Gunicorn's timeout setting defaults to 30 seconds, and the docs describe it as "Workers silent for more than this many seconds are killed and restarted." With the default sync worker class, a worker blocked on a 45-second model call is exactly such a silent worker. For async worker classes, the docs note that the setting only means the worker process is still communicating, and it is not tied to the duration of a single request. If you run a sync stack in front of an LLM, this one can bite before any proxy does.
What the platforms document
The table collects the limits that providers publish today. It is not a ranking: these products have different execution models, and each offers a way around its limit. The point is that the numbers differ, and the shortest one on your path wins.
| Layer | Documented limit | Clock | Configurable? |
|---|---|---|---|
| Heroku router | 30 s to send the first byte, then a rolling 55 s window that each byte resets | First byte, then idle | No |
| Cloudflare proxy (orange cloud) | 125 s Proxy Read Timeout, then error 524 | Waiting on the origin's response | Enterprise only, up to 6,000 s |
| AWS Application Load Balancer | Connection idle timeout 60 s by default | Idle | Yes, 1 to 4,000 s |
| AWS API Gateway (REST) | Integration timeout 50 ms to 29 s | Total | Raisable above 29 s for Regional and private APIs, not for edge-optimized |
nginx proxy_pass |
proxy_read_timeout 60s, measured between two successive reads |
Idle | Yes |
| Vercel Functions (fluid compute) | 300 s default on all plans; Hobby max 300 s, Pro and Enterprise up to 800 s, 1,800 s in beta | Total | Yes, maxDuration |
| Netlify Functions | 60 s synchronous and streaming, 20 MB streamed payload; background functions 15 min | Total | No |
| Google Cloud Run | 300 s default, up to 3,600 s, then 504 | Total | Yes, --timeout |
| Railway | Up to 15 min if data keeps transferring; closed after 5 min with no data | Total and idle | Not stated |
| Fly.io proxy | http_options.idle_timeout in fly.toml (the docs show an example value, not a default) |
Idle | Yes |
A few details matter more than the headline numbers. Cloud Run notes that closing the connection does not stop the container from working on the aborted request, and Heroku says the same about the router: it returns an error to the client while your application keeps processing. For an LLM call, that means you can be billed for tokens that nobody will ever read. Cloudflare recommends status polling for long HTTP processes, or moving them to a subdomain that is not proxied. And Cloud Run's own guidance, for timeouts above 15 minutes, is to make clients tolerant of reconnecting, because the longer a connection lives, the more likely something between the client and the instance will drop it.
Hugging Face Spaces and Render do not publish an HTTP request timeout in the pages we checked, so they are not in the table.
Why streaming helps, and when it silently does not
Streaming the model's output as it is generated, typically as Server-Sent Events (text/event-stream) over a chunked HTTP/1.1 response or an HTTP/2 stream, solves the first-byte problem and most idle problems at once: the first token arrives in seconds, and every following token resets the idle clocks. The catch is that streaming only works if every layer forwards bytes as they arrive, and several common components do not by default.
The classic culprit is a buffering reverse proxy. nginx ships with proxy_buffering on, reading the upstream response into its buffers; with buffering disabled, the docs say the response "is passed to a client synchronously, immediately as it is received." An X-Accel-Buffering: no response header from the upstream switches buffering off for one response without touching the proxy config. If you control the nginx in front of your app, a minimal streaming location looks like this:
location /api/chat {
proxy_pass http://app:8000;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off; # forward each chunk as it arrives
proxy_read_timeout 300s; # idle gap allowed between two reads (default 60s)
}
Compression is the second place where small chunks can get held back, because a compressor wants enough bytes to work with. Starlette's GZipMiddleware, which FastAPI uses, excludes text/event-stream from compression by default in its current documentation. Cloudflare documents that a Cache-Control: no-transform header from the origin stops it from re-encoding the response with gzip or Brotli. If you add compression middleware of your own, check that it skips event streams.
The third case is a runtime that buffers the whole response by design. AWS Lambda function URLs, for instance, default to the BUFFERED invoke mode, in which "invocation results are available when the payload is complete"; streaming requires the RESPONSE_STREAM mode, which Lambda supports natively on its Node.js runtimes. The symptom of any buffering layer is the same and easy to recognize: locally, tokens trickle in; in production, nothing arrives for a long time and then the whole answer lands at once, or the request dies before it does.
Finally, streaming does nothing for a total-duration clock. A Netlify streaming function still stops at 60 seconds and a Vercel function still stops at its maxDuration, however many tokens it has sent. On those platforms, streaming improves the experience and avoids idle cutoffs, but the duration limit must be raised or the work must move out of the request.
Heartbeats: keeping a quiet stream alive
Streaming tokens is not the same as streaming continuously. An agent that runs a tool for 90 seconds, or a model that reasons before answering, can leave the connection silent long enough to trip an idle timeout even though the response has started. The fix is a heartbeat: a small message that keeps bytes flowing without meaning anything to the client.
SSE has one built in. In the HTML specification's event stream format, a line that begins with a colon is a comment and is ignored by the client, and the spec's authoring notes suggest sending such a comment line "every 15 seconds or so" to protect against proxies that drop connections after a short timeout. Some model APIs do the same upstream (Anthropic's streams may include ping events), but those reach your server, not your user. Vercel's docs make the point from the platform side: over HTTP/2 it sends PING frames while a response is idle, but HTTP/1.1 has no equivalent, so it recommends streaming progress or heartbeat data. AWS ALB, for its part, documents that HTTP/2 PING frames do not reset its idle timeout, so data-level heartbeats are the portable option.
Recent FastAPI versions do this for you. EventSourceResponse, added in FastAPI 0.135.0, sends a keep-alive comment every 15 seconds when no message has been sent, sets Cache-Control: no-cache, and sets X-Accel-Buffering: no. Here is a complete endpoint that streams from any OpenAI-compatible API, in this case Hugging Face Inference Providers:
import os
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
from openai import AsyncOpenAI
from pydantic import BaseModel
app = FastAPI()
client = AsyncOpenAI(
base_url="https://router.huggingface.co/v1",
api_key=os.environ["HF_TOKEN"],
timeout=120.0, # fail well before the proxies in front of you do
max_retries=0, # a silent retry restarts the whole generation
)
class Prompt(BaseModel):
text: str
@app.post("/chat", response_class=EventSourceResponse)
async def chat(prompt: Prompt) -> AsyncIterable[ServerSentEvent]:
stream = await client.chat.completions.create(
model="openai/gpt-oss-120b",
messages=[{"role": "user", "content": prompt.text}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield ServerSentEvent(data=chunk.choices[0].delta.content, event="token")
yield ServerSentEvent(raw_data="[DONE]", event="done")
data is JSON-encoded, which keeps tokens that contain newlines from breaking the SSE framing. On an older FastAPI, or with a plain StreamingResponse in any Starlette app, you can add the heartbeat yourself by racing the next event against a timer:
import asyncio
import json
from collections.abc import AsyncIterable, AsyncIterator
async def with_heartbeat(events: AsyncIterable[str], every: float = 15.0) -> AsyncIterator[str]:
"""Wrap text deltas as SSE frames; emit a comment whenever `every` seconds pass in silence."""
it = aiter(events)
nxt = asyncio.ensure_future(anext(it))
try:
while True:
done, _ = await asyncio.wait({nxt}, timeout=every)
if not done:
yield ": ping\n\n"
continue
try:
item = nxt.result()
except StopAsyncIteration:
return
yield f"data: {json.dumps(item)}\n\n"
nxt = asyncio.ensure_future(anext(it))
finally:
nxt.cancel()
# return StreamingResponse(with_heartbeat(deltas()), media_type="text/event-stream",
# headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
In a Next.js App Router route handler, the same ideas fit in one file: raise maxDuration where your plan allows it, send a first byte immediately, interleave comments while the model is quiet, and stop the timer when the client goes away. generate stands in for your model call.
// app/api/chat/route.ts
export const maxDuration = 800; // seconds; Pro/Enterprise on Vercel, Hobby caps at 300
declare function generate(prompt: string, signal: AbortSignal): AsyncIterable<string>;
export async function POST(req: Request): Promise<Response> {
const { prompt } = await req.json();
const enc = new TextEncoder();
let ping: ReturnType<typeof setInterval> | undefined;
let closed = false;
const body = new ReadableStream<Uint8Array>({
async start(controller) {
const send = (s: string) => {
if (!closed) controller.enqueue(enc.encode(s));
};
send(": open\n\n"); // first byte now, not when the model answers
ping = setInterval(() => send(": ping\n\n"), 15_000);
try {
for await (const delta of generate(prompt, req.signal)) {
send(`data: ${JSON.stringify(delta)}\n\n`);
}
send("event: done\ndata: {}\n\n");
} catch (err) {
send(`event: error\ndata: ${JSON.stringify(String(err))}\n\n`);
} finally {
clearInterval(ping);
if (!closed) controller.close();
}
},
cancel() {
closed = true; // the client went away
clearInterval(ping);
},
});
return new Response(body, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
},
});
}
In Next.js, maxDuration is a route segment option whose default is "set by deployment platform", so it only has an effect where the platform reads it. The Vercel AI SDK's troubleshooting page describes exactly the symptom this article started with, responses that stream fine locally and get "chopped off" on Vercel, and its fix is the same setting.
The clocks in your own client code
Your server is itself a client of the model API, and HTTP library defaults vary widely.
| Client | Documented default |
|---|---|
Python httpx |
Raises a timeout after 5 seconds of network inactivity |
Node.js built-in fetch (implemented by undici) |
headersTimeout 300 s to receive headers; bodyTimeout 300 s between body chunks |
| OpenAI Python SDK | Requests time out after 10 minutes; timed-out requests are retried twice by default |
| Anthropic Python SDK | Requests time out after 10 minutes; retried twice by default; raises an error for non-streaming requests expected to take longer than about 10 minutes |
Two consequences are worth spelling out. First, a hand-rolled httpx call to a model endpoint with default settings fails as soon as the model is silent for more than 5 seconds, for example while it processes a long prompt, so a direct REST integration can fail where the vendor SDK, with its 10-minute default, works. Second, the SDK defaults are generous compared with the infrastructure in front of you: a 10-minute client timeout behind a 60-second idle limit means your server keeps waiting long after the user's connection is gone, and the two default retries can turn one abandoned request into three paid generations. A client timeout somewhat shorter than the shortest limit in front of your app, with retries turned off or made explicit, keeps those failures visible and cheap. The Anthropic SDK docs also recommend streaming for long requests specifically because some networks drop idle connections, and the SDK sets TCP keep-alive on its sockets for the same reason.
SSE or WebSockets?
WebSockets are sometimes suggested as the way out of HTTP timeouts. They do give you a bidirectional channel, which matters for voice, collaborative editing or agents that need user input mid-task, but they do not escape the clocks. Heroku says its normal HTTP routing timeout rules apply to WebSocket connections and that either side should send an occasional ping to prevent idling. Cloud Run treats a WebSocket as a long-running HTTP request subject to the service's request timeout, five minutes by default. Render imposes no fixed WebSocket timeout, but its FAQ notes that connections close when the instance is replaced, for example during a deploy. A WebSocket therefore needs the same heartbeat and the same reconnection logic as an SSE stream.
For the common case of a model streaming text to a browser, SSE has practical advantages: it is plain HTTP, so proxies, logging and authentication work as for any other request; the browser's EventSource reconnects automatically and sends the last received event id in a Last-Event-ID header, which the server can use to resume (FastAPI's docs show this pattern). The limitation is that the EventSource constructor accepts only a URL and a credentials flag, with no method, headers or body, so chat apps that POST a prompt usually read the stream with fetch and lose the automatic reconnection, which is one reason resumable streams exist as a separate feature in some frameworks.
When to stop holding the request open
Streaming and heartbeats cover answers that take seconds to a few minutes. For work that can take longer than the shortest total-duration clock, such as a long agent run, a batch of generations or a large document pipeline, the robust answer is to stop tying the work to one HTTP request. The request creates a job and returns an identifier immediately, a worker does the work, and the client learns the result by polling a status endpoint, by receiving a webhook, or by subscribing to a stream that can be resumed. This is what Heroku recommends for anything longer than its 30-second window, what Cloudflare recommends for its 524 error, and what Netlify's background functions implement: they return a 202 immediately and keep running for up to 15 minutes.
The hard part is state. The job's progress and partial output must live somewhere shared, such as a database or Redis, so that a reconnecting client can land on any instance. Cancellation must be explicit, because a disconnect no longer means "stop". The Vercel AI SDK's resumable streams are a good example of the trade-off: useChat with resume reconnects to an active generation after a page reload, using the resumable-stream package with Redis to store the stream, and its docs warn that in this setup closing the tab or calling stop() only closes the HTTP connection, so a real stop needs its own endpoint that cancels the underlying work. AWS documents the same property for Lambda response streaming, where streamed responses are not stopped when the client disconnects and the full duration is billed.
Measure the limits of your own stack
Documentation tells you what each layer promises; only a test tells you what your chain of CDN, proxy and platform actually does. A deliberately badly behaved endpoint makes this quick. This one sends nothing at all, not even headers, for first seconds, and then emits count events gap seconds apart, with no heartbeat:
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.get("/probe")
async def probe(first: float = 0, gap: float = 1, count: int = 10):
"""No heartbeats on purpose. Wait `first` s before sending anything
(headers included), then send `count` events `gap` s apart."""
await asyncio.sleep(first)
async def body():
for i in range(count):
if i:
await asyncio.sleep(gap)
yield f"data: {i}\n\n"
return StreamingResponse(body(), media_type="text/event-stream",
headers={"X-Accel-Buffering": "no"})
Deploy it behind the same layers as your real app and probe each clock separately. Use curl -N so that curl itself does not buffer, and its -w timing variables to see when the first byte arrived and when the transfer ended:
URL=https://your-app.example.com/probe
# First-byte clock: increase `first` until the request fails.
curl -sN -o /dev/null -w 'ttfb=%{time_starttransfer}s total=%{time_total}s http=%{http_code}\n' \
"$URL?first=40&count=1"
# Idle clock: start immediately, then go quiet for `gap` seconds.
curl -sN "$URL?gap=70&count=3" | while IFS= read -r line; do printf '%s %s\n' "$(date +%T)" "$line"; done
# Total clock: never idle for long, but run for ~6 minutes; also shows buffering.
curl -sN "$URL?gap=5&count=72" | while IFS= read -r line; do printf '%s %s\n' "$(date +%T)" "$line"; done
If the first command returns an error status at some value of first, you have found the first-byte limit; the status code and error page often identify the layer. If the second stream dies during the gap, an idle timeout shorter than gap sits somewhere on the path. If the third stream ends early at a round number of seconds, that is a total-duration limit; if its timestamps arrive in bursts instead of every five seconds, something is buffering. Run the tests both against the platform's own URL and through your CDN or custom domain; the difference is the CDN's contribution. Users' networks add proxies you cannot test, which is the best argument for heartbeats even when your measurements look comfortable.
A checklist
- List every layer between the user and your model API, including your own HTTP client and app server, and write down each one's first-byte, idle and total limits with a link to the documentation.
- Stream the response, and make sure the first byte leaves immediately rather than when the model produces its first token.
- Send an SSE comment line about every 15 seconds whenever nothing else has been sent.
- Disable buffering on every proxy you control (
proxy_buffering offorX-Accel-Buffering: no), keep compression off event streams, and check that your runtime is not in a buffered response mode. - Raise total-duration limits only where the platform allows it, and do not rely on raising them as the only fix.
- Set the model client's timeout just under the shortest limit in front of you, and decide deliberately whether a timed-out generation should be retried.
- Treat a client disconnect as an event: cancel the model call or, if you resume streams, provide a real stop endpoint.
- Move anything that can outlive the shortest total-duration clock into a job, with polling, a webhook or a resumable stream.
- Re-measure with a probe endpoint after every infrastructure change, such as adding a CDN or a custom domain.
If a coding agent builds or deploys your app, the same checklist works as an instruction. A prompt along these lines asks it for sources rather than memory, which matters because these limits change:
Before deploying, list every layer between the user's browser and the model API in this project: CDN, load balancer, platform router or function runtime, reverse proxy, app server and the HTTP client used for model calls. For each, give its time-to-first-byte, idle and total-duration limits, each with a link to the official documentation, and say "not documented" where you cannot find one. Then check our longest expected AI request against the shortest limit. If it does not fit, propose the smallest change that does: streaming with an early first byte, SSE heartbeats every 15 seconds, disabling proxy buffering, a higher duration limit, or moving the work into a job with polling. Finally, add a /probe endpoint and the curl commands to verify the limits after deploy.
We checked every limit and default in this article against the providers' own documentation on 2026-10-29, ran the code samples locally, and wrote the article with help from an AI assistant; Cloudish, the host we build for apps that AI agents deploy, is at https://cloudish.ai/?ref=cc-hf-timeouts.

