Cloudflare WebSocket Disconnects: 100s Timeout and Heartbeats
When a WebSocket connection goes through Cloudflare and drops after sitting quiet for a while, the browser reports close code 1006. Most of the time, an idle timeout on some layer of the path has expired: no data crossed the connection for a while, so a proxy in the middle treated it as dead and reclaimed it. Cloudflare's edge typically caps idle proxied connections at around 100 seconds, and if Nginx sits in front of your origin, it cuts at 60 seconds by default. To fix a Cloudflare WebSocket disconnect, make the heartbeat interval shorter than the shortest idle timeout on the whole path, then add automatic reconnection. The rest of this post goes in that order: find which layer is cutting the connection, change the config, add heartbeats and reconnection.
Is it 60 seconds or 100 seconds? Identify the layer first
Before anything else, write down one number: how many seconds passed between the last message and the disconnect. Each layer has a different default timeout, so that gap usually tells you who closed the connection.
| Layer | Common default idle timeout | Configurable? | Typical symptom |
|---|---|---|---|
| Cloudflare edge (orange-cloud proxy) | About 100 seconds without data | Basically not on standard plans; use heartbeats | Drops at around 100 seconds, even with a different origin |
| Nginx reverse proxy | proxy_read_timeout defaults to 60 seconds | Yes | Drops at around 60 seconds; also reproduces when you bypass Cloudflare and hit the origin directly |
| Cloud load balancer | Varies by vendor, 60 seconds is common | Yes, in the console | Only reproduces in environments behind the load balancer |
| Browser background tab | Doesn't close the connection, but throttles timers | No | Drops only after the page has been in the background for a while, never in the foreground |
| Application server itself | Depends on the framework and your code | Yes | The server log shows an explicit close at disconnect time |
For exact Cloudflare values and behavior, refer to the official documentation (the WebSockets pages on developers.cloudflare.com). The docs also note that Cloudflare may restart servers when it releases new code to its global network, which interrupts in-flight WebSocket connections. So even with heartbeats set correctly, long-lived connections will occasionally drop, and you need reconnect logic regardless.
What does close code 1006 tell you?
1006 means "abnormal closure": the browser never received a Close frame from the other side, and the TCP connection simply disappeared. It is a status code generated locally by the browser and never appears on the wire. When an intermediate proxy cuts a connection because of an idle timeout, you get 1006.
A few common close codes for reference:
| Code | Meaning | Common cause |
|---|---|---|
| 1000 | Normal closure | Either side called close() on purpose |
| 1001 | Going away | Page navigation, or the server sends a Close when restarting |
| 1006 | Abnormal closure, no Close frame | Idle timeout, network interruption, a proxy dropping the TCP connection |
| 1011 | Internal server error | Backend code threw an exception |
When you see 1006, don't suspect your business logic first. Check whether the disconnect time consistently lands near 60 or 100 seconds.
How to confirm the disconnect time with DevTools
You don't need a packet capture. The browser's built-in tools are enough:
- Open DevTools, go to the Network panel, and filter by
WS. - Reload the page, click the WebSocket request, and open the Messages tab. It lists every frame by time, with sent and received frames marked by different colors or arrows.
- Do nothing and let the page sit idle. Note the time of the last message.
- After the connection drops, a close entry appears at the bottom of the message list. Also log the close event in your code:
ws.addEventListener('close', (e) => {
console.log('closed', e.code, e.reason, new Date().toISOString());
});
- Subtract the time of the last message from the time of the disconnect. Close to 60 seconds: check Nginx and the load balancer first. Close to 100 seconds: it is almost certainly the Cloudflare edge.
Then run a control test that bypasses Cloudflare: point the domain at your origin IP in your local hosts file (or temporarily switch the record to gray cloud in Cloudflare) and test again. If it still drops, the problem is on your own server. If it only drops through Cloudflare, it is the edge idle timeout. Remember to revert the change when you're done.
If the disconnect times look random, anywhere from a few seconds to tens of minutes, it is probably not an idle timeout. The network itself may be unstable, or a middlebox may be misbehaving. See how to read traceroute and mtr results and troubleshooting MTU black holes to dig further.
Which lines to change when running WebSocket behind Nginx
For WebSocket through Nginx you need at least two things: forward the Upgrade handshake headers correctly, and raise the read timeout above your heartbeat interval. Here is a config you can use directly:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 443 ssl;
server_name example.com;
location /ws/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
# Both default to 60s; raise them well above the heartbeat interval
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
}
Key points:
proxy_http_version 1.1is required. HTTP/1.0 does not support Upgrade.UpgradeandConnectionare hop-by-hop headers, which Nginx does not forward by default, so you must set them manually. If you leave them out, the handshake fails, usually showing up as a connection that drops right after connecting or a 400 response.- Raising
proxy_read_timeoutonly fixes the Nginx layer. Cloudflare still cuts at about 100 seconds, so changing Nginx is not a substitute for heartbeats. - If the same
locationalso serves streaming endpoints such as SSE, the buffering and timeout settings follow a similar approach. See a checklist for SSE output being buffered and troubleshooting LLM streaming responses that disconnect midway.
What heartbeat interval should you use?
The rules of thumb:
- List the idle timeout of every layer on the path and take the minimum, call it T. With Cloudflare alone, T is about 100 seconds. With Cloudflare plus a default-config Nginx, T is 60 seconds.
- Set the heartbeat interval to roughly half of T, leaving margin for network jitter and timer delay. For T = 100 seconds, 25 to 30 seconds is safe. For T = 60 seconds, use 20 to 25 seconds.
- Don't set it too short. If every connection sends a heartbeat every few seconds, the cost to servers and bandwidth adds up fast at scale, and mobile devices burn more battery.
- Besides keeping the connection alive, heartbeats detect dead connections. If two or three consecutive cycles get no response, close the connection and reconnect right away instead of waiting for TCP to time out on its own.
Why have the server send the heartbeat?
The browser WebSocket API cannot send protocol-level ping frames, only ordinary messages. In addition, once a page moves to the background, browsers limit how often timers like setInterval fire. In a long-hidden page, timers can be throttled to about once per minute, with specifics varying by browser and version. A client heartbeat set to every 30 seconds may become every 60 seconds in a background tab, and with a little extra delay it can cross the timeout line.
Server-side timers are not affected, so the more reliable division of labor is this: the server sends ping frames on a timer, and the browser automatically replies with pong (built-in browser behavior that needs no code and isn't subject to background throttling). The client then adds an application-level heartbeat as a supplement to check that the server is still alive.
Server-side ping/pong example (Node.js, ws library)
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
const PING_INTERVAL = 25_000; // roughly half the shortest idle timeout on the path
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
ws.on('message', (data) => {
// Handle the client's application-level heartbeat
if (data.toString() === '{"type":"ping"}') {
ws.send('{"type":"pong"}');
return;
}
// ...business messages
});
});
const timer = setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) { ws.terminate(); continue; } // no pong last round, treat as dead
ws.isAlive = false;
ws.ping();
}
}, PING_INTERVAL);
wss.on('close', () => clearInterval(timer));
Browser-side application-level heartbeat example
function startHeartbeat(ws, { interval = 25_000, timeout = 10_000 } = {}) {
let pongTimer;
const pingTimer = setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) return;
ws.send('{"type":"ping"}');
clearTimeout(pongTimer);
pongTimer = setTimeout(() => ws.close(4000, 'heartbeat timeout'), timeout);
}, interval);
ws.addEventListener('message', (e) => {
if (e.data === '{"type":"pong"}') clearTimeout(pongTimer);
});
ws.addEventListener('close', () => {
clearInterval(pingTimer);
clearTimeout(pongTimer);
});
}
Codes 4000 to 4999 are reserved for application-defined close codes. Using one to mark "heartbeat timeout" lets you tell it apart from 1006 in your logs.
If your WebSocket service runs on Cloudflare Workers Durable Objects and uses the hibernation API, you can configure a fixed request and response pair with setWebSocketAutoResponse, so the edge answers heartbeat messages directly without waking the object. Refer to the official Cloudflare documentation for details.
How to reconnect without taking your service down
Heartbeats only reduce idle disconnects. Server restarts, network switches, and edge releases will still drop connections. For reconnection, watch three things: grow the wait time exponentially, add random jitter, and cap it. Otherwise, after a single server restart, every client reconnects in the same second.
function connect(url, onOpen) {
let attempt = 0;
function open() {
const ws = new WebSocket(url);
ws.addEventListener('open', () => {
attempt = 0; // reset once connected
startHeartbeat(ws);
onOpen?.(ws);
});
ws.addEventListener('close', (e) => {
if (e.code === 1000) return; // intentional normal close, don't reconnect
const base = Math.min(30_000, 1_000 * 2 ** attempt); // 1s, 2s, 4s ... up to 30s
const delay = base / 2 + Math.random() * base / 2; // jitter
attempt++;
setTimeout(open, delay);
});
}
open();
}
A few details that are easy to miss:
- After a successful reconnect, resubscribe to channels and backfill messages missed during the gap. Ideally the server supports resuming "from a given sequence number."
- Listen for the
onlineandvisibilitychangeevents. When the network comes back or the page returns to the foreground and the connection is already down, reconnect immediately instead of waiting for the backoff timer. - Backoff with jitter is the same idea as HTTP API retries. For a fuller discussion, see how to write LLM API retries: exponential backoff with jitter.
Troubleshooting checklist
Go through these in order, and most Cloudflare WebSocket disconnect problems can be pinned down:
- Record the seconds from "last message" to disconnect, and check whether it consistently lands near 60 or 100 seconds
- Is the close code 1006 or 1000/1001/1011?
- Does it still disconnect when you bypass Cloudflare and hit the origin directly?
- Does Nginx set
proxy_http_version 1.1and theUpgradeandConnectionheaders? - Is Nginx's
proxy_read_timeoutlarger than the heartbeat interval? - What is the load balancer's idle timeout?
- Does the server send pings on a timer, with an interval under roughly half the shortest timeout?
- Does the client have heartbeat timeout detection and exponential backoff reconnection with jitter?
- If it only drops in background tabs, are you relying solely on client-side timers?
- Was there a Cloudflare incident around the time of the disconnect?
Don't skip the last item. cdnping's API status page syncs with the official Cloudflare status page every 15 minutes. According to sync records as of 2026-10-17, since 2026-09-17 the Cloudflare status page has listed 3 incidents marked major and 19 marked minor, several of which were regional network performance issues or increased 5xx errors (cdnping started collecting on 2026-10-17, so the history is still short). If many connections drop at the same moment and the timing doesn't match any timeout value, check the status page for incidents in the same window. For how to interpret incident severity and components, see how to read incident levels and components on a status page. For how the data is collected, see our methodology.
FAQ
Can I raise the 100-second limit in the Cloudflare dashboard?
On standard plans, generally no. You can only keep the connection alive by making sure data keeps flowing. Some plans or products allow adjusting proxy timeouts; check the options in your account and the official documentation. Even if you can raise it, keep the heartbeat, since it also detects dead connections.
My heartbeat runs every 30 seconds and it still drops occasionally. Is that normal?
Yes. Edge releases, origin restarts, and user network switches all cause drops. The test is whether the client reconnects automatically within a few seconds without losing business data. If drops are frequent and cluster at a fixed interval, go back and check which layer has a shorter timeout than you assumed.
Should I switch to SSE or long polling after adopting Cloudflare?
It depends on your use case. For one-way server push, SSE is simpler, but it is subject to the same idle timeouts and also needs periodic comment lines to stay alive. When you need two-way communication, WebSocket with heartbeats is still the right choice. For other Cloudflare settings around caching, rate limiting, and origin protection, see using Cloudflare to speed up AI applications. If you need edge acceleration built on Cloudflare's network, see the cdnping Edge overview.