The bug report said "the analysis just stops sometimes." No error toast, no stack trace. The browser's network tab showed a stream that opened, sat there, and then closed with a Cloudflare 524 timeout. My server logs for that exact request said 200 OK, 7,412 output tokens, completed.
So the model finished. I paid for it. And nobody ever saw a single word of it.
Over 14 days, this happened to 63 of 1,184 requests on my document analysis endpoint. That's 5.3%. Here's the autopsy, because the cause was a filter I wrote myself, three lines long, that I was proud of at the time.
TL;DR
- Cloudflare returns a 524 when your origin sends no bytes for 100 seconds (the proxy read timeout on non-Enterprise plans). Streaming doesn't protect you if the stream goes quiet.
- Claude's extended thinking can go quiet from your client's point of view. My proxy forwarded only
text_deltaevents and dropped thinking deltas andpingevents, so the browser received nothing during long thinking phases. - The origin keeps running after a 524. All 63 completions finished upstream. Add client auto-retry and I paid for 80 completions nobody read.
- The fix is an SSE heartbeat: send a
: pingcomment every 15 seconds. After the change: 611 requests over 7 days, 0 timeouts, longest stream 6 minutes 40 seconds. - Also cancel the upstream call on disconnect, or a 524 still costs you a full completion.
What is a Cloudflare 524 timeout, exactly?
A Cloudflare 524 means Cloudflare connected to your origin, but the origin didn't send data within the proxy read timeout, which is 100 seconds unless you're on Enterprise. Cloudflare gives up, sends the 524 to the client, and drops the connection.
The part people miss: this isn't a "request must finish in 100 seconds" rule. It's a "something must arrive every 100 seconds" rule. A stream that runs for ten minutes is fine as long as bytes keep flowing. A stream that pauses for 101 seconds is dead.
I knew about the first version. I'd moved this endpoint to streaming specifically to dodge it. I didn't think about the second version at all.
Why did my Claude stream go silent for over 100 seconds?
The endpoint takes a long contract or spec document and returns a structured critique. I'd turned on extended thinking with a generous budget because the answers were noticeably better.
Here's roughly what my FastAPI proxy looked like:
async def relay(prompt: str): async with client.messages.stream( model=MODEL, max_tokens=16000, thinking={"type": "enabled", "budget_tokens": 10000}, messages=[{"role": "user", "content": prompt}], ) as stream: async for event in stream: if event.type == "content_block_delta" and event.delta.type == "text_delta": yield f"data: {json.dumps({'text': event.delta.text})}\n\n" @app.post("/analyze") async def analyze(req: AnalyzeRequest): return StreamingResponse(relay(req.prompt), media_type="text/event-stream") See that if? I wrote it so the frontend wouldn't have to deal with thinking blocks, ping events, or message metadata. Clean contract: the client only ever gets text.
It also meant that while the model was thinking, my server yielded nothing. The upstream connection to the API was busy and healthy. The downstream connection to Cloudflare was a flat line.
The API was even sending ping events to keep things alive. My filter threw those away too.
How did I prove the gap was the cause?
I logged the timestamp of every chunk my server actually yielded, then computed the largest gap between consecutive yields per request (counting the gap from request start to first yield).
The split was about as clean as data gets:
| Group | Requests | Max gap between yielded bytes |
|---|---|---|
| Completed normally | 1,121 | median 31s, worst 98s |
| Ended in 524 | 63 | median 121s, worst 187s |
Every one of the 63 failures had a silent gap of at least 100 seconds. None of the 1,121 successes did. The 98-second request that survived was a near miss I'd have lost on a slower day.
The gaps lined up with thinking. Long documents produced long thinking phases, and the first visible text often appeared after two minutes of silence. Short documents never got close to the limit, which is why my test suite (short fixtures, obviously) never caught it.
Does the request keep running after a 524?
Yes, and this is the expensive part. A 524 happens between Cloudflare and the browser. Your origin has no idea. My server kept consuming the stream until the model finished, logged a happy 200, and wrote to a socket nobody was reading.
Why didn't it notice? Because it wasn't writing anything. A dropped connection usually surfaces as a failed write. No writes, no failure, no signal. By the time text started flowing, the full completion was already paid for.
Then it got worse. My frontend auto-retried once on any 5xx. So:
- 63 requests hit a 524 on the first try
- 41 of them auto-retried (the rest had a closed tab or a user who clicked away)
- 17 of those retries hit a 524 again, because the same long document produced the same long thinking phase
Total: 80 full completions generated and thrown away. They averaged about 6,900 output tokens each, so roughly 550,000 output tokens went straight into the void. Retrying a deterministic timeout is just paying twice for the same failure.
How do you fix a Cloudflare 524 on a streaming LLM endpoint?
Send bytes during the silence. Server-Sent Events have a built-in way to do this: any line starting with : is a comment, and the browser's EventSource (and every sane SSE parser) ignores it. Cloudflare doesn't ignore it, though. It counts as data on the wire, so the 100-second clock resets.
I merged the model stream with a heartbeat using a queue:
HEARTBEAT_SECONDS = 15 async def relay(prompt: str, request: Request): queue: asyncio.Queue = asyncio.Queue() async def pump(): try: async with client.messages.stream(...) as stream: async for event in stream: if event.type == "content_block_start" and event.content_block.type == "thinking": await queue.put(f"event: status\ndata: {json.dumps({'phase': 'thinking'})}\n\n") elif event.type == "content_block_delta" and event.delta.type == "text_delta": await queue.put(f"data: {json.dumps({'text': event.delta.text})}\n\n") finally: await queue.put(None) task = asyncio.create_task(pump()) try: while True: try: chunk = await asyncio.wait_for(queue.get(), timeout=HEARTBEAT_SECONDS) except asyncio.TimeoutError: if await request.is_disconnected(): break yield ": ping\n\n" continue if chunk is None: break yield chunk finally: task.cancel() Three things changed:
- Heartbeat every 15 seconds. Far under 100, so even a slow network hop or a GC pause won't push it over.
- A
statusevent when thinking starts. The UI now shows "Reading the document..." instead of a frozen spinner. Users stopped closing the tab at 40 seconds, which I hadn't realized was its own small leak. -
task.cancel()infinally. When the client disconnects, the generator gets closed, thefinallyruns, and the upstream stream is cancelled. Heartbeat writes also give the server a regular chance to discover a dead connection.
I also turned off client retry for this endpoint on 524 specifically. If a 524 ever comes back, retrying won't help, and I'd rather see it in the error rate.
What were the results after adding the heartbeat?
Over the next 7 days: 611 requests, 0 responses with a 524. The longest single stream ran 6 minutes 40 seconds, most of it thinking, and arrived intact. Worst silent gap on the wire dropped to 15.2 seconds, which is the heartbeat interval plus scheduling noise.
Orphaned completions dropped to 4, all from users closing the tab mid-stream, and all four were cancelled upstream within one heartbeat interval instead of running to the end.
Are there other ways around the 100-second limit?
Yes, and each has a real tradeoff:
- DNS-only (grey cloud) subdomain for the API. No proxy, no timeout. You also lose Cloudflare's WAF, caching, and DDoS protection on that hostname.
- Enterprise plan. You can raise the proxy read timeout. Expensive way to fix a missing
yield. - Async jobs.
POSTreturns a job ID, the client polls or subscribes. This is the right design for truly long agent runs, but it's more moving parts than a single streamed answer needs. - Turn thinking down. It works, and it made my answers worse. I'd rather keep the budget and send a heartbeat.
For a streamed LLM endpoint, the heartbeat is the smallest change that fixes the actual problem.
The lesson I'm keeping
I treated "filter out events the client doesn't need" as tidy API design. On a proxied connection, those events were also the only proof of life. Every byte you drop is a byte that doesn't reset someone's timeout: Cloudflare's, a load balancer's, a corporate proxy's, or the user's patience.
So why did Cloudflare return a 524 on 63 of my 1,184 Claude streams? Because Cloudflare's 524 timeout fires when the origin sends nothing for 100 seconds, and my proxy forwarded only visible text, so every extended-thinking phase longer than 100 seconds looked like a dead server. The model kept running and finished every one of those responses, billed and unseen. Sending an SSE comment heartbeat every 15 seconds, emitting a status event when thinking starts, and cancelling the upstream call on disconnect took the failure count from 63 to 0.
Written by the developer behind Preterview, an interview prep platform.