Sixty seconds is the number behind most "WebSocket connection closed" tickets that reach a platform team. It is the default value of proxy_read_timeout in nginx, and it means that when the upstream application sends nothing for one minute, nginx closes the connection on its side. The browser reports close code 1006, the frontend reconnects, and somebody writes in the incident channel that the socket is "flaky".

The second big cause is a handshake that never upgrades in the first place. By default nginx talks HTTP/1.0 to upstream servers and does not forward the Upgrade and Connection headers, so the backend receives an ordinary GET and answers it like one.

The two failures look alike in a chat widget or a live trading screen, yet they happen at opposite ends of the connection's life, and the fix for one changes nothing about the other. Reloads, cloud load balancers and a quiet redirect rule cover most of what is left.

Two failures hide behind one vague error

Start by asking when the socket dies, because timing separates the cases faster than any config review. A connection that fails within the first few hundred milliseconds never finished its handshake.

Chrome prints something like "WebSocket connection to 'wss://app.example.com/ws/' failed", and the network tab shows the response the browser got instead of 101 Switching Protocols: often a 400 from the application, a 200 with an HTML page, a 301, or a 502 from nginx itself. A connection that opens, exchanges messages and then closes after a while did upgrade correctly. The problem there is something deciding to end a live tunnel.

The nginx logs confirm which side you are on. In the access log, an upgraded WebSocket appears as one line with status 101, written only when the connection ends, and its request time equals the lifetime of the socket.

If you see dozens of 101 entries with request times of 60.001, 60.003 and 60.002 seconds, you are looking at an idle timeout, not a bug in the application. The error log usually adds a line ending in "while proxying upgraded connection" with "upstream timed out (110: Connection timed out)".

Handshake failures look different. You will see 400 or 426 statuses with request times of a few milliseconds, or the familiar "upstream prematurely closed connection while reading response header from upstream" when the backend hung up on a request it did not understand.

Two minutes with tail and grep usually tells you which half of this article you need. Engineers who run that check before opening the config file tend to be the ones that hiring managers in Lisbon and Porto remember from on-call interviews, because the habit transfers to every proxy, not just nginx.

The handshake needs headers nginx will not forward on its own

Upgrade and Connection are hop-by-hop headers. The HTTP specification says a proxy must not pass them along to the next hop, and nginx follows that rule. For WebSockets you have to forward them explicitly and switch the upstream protocol to HTTP/1.1, which is the version the upgrade mechanism in RFC 6455 is built on. The pattern from the nginx documentation looks like this:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 443 ssl;
    server_name app.example.com;

    location /ws/ {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

The map block matters more than it looks. Without it, people hard-code Connection "upgrade", which tells the upstream that every request through that location wants a protocol switch, including plain HTTP polling requests from libraries such as Socket.IO when they fall back. With the map, requests that carry no Upgrade header get Connection: close and behave normally.

One refinement trips up teams that use keepalive to their upstream pool. If the upstream block contains a keepalive directive, mapping the empty value to close forces nginx to tear down the pooled connection after every normal request. In that setup map the empty case to an empty string instead, so ordinary requests reuse pooled connections and only real upgrades switch protocol.

Then check the location itself. If the location is defined as /ws/ with a trailing slash and the client connects to /ws, nginx answers with a 301 redirect to the slashed path. Browsers do not follow redirects during a WebSocket handshake, so the connection fails with a 301 that looks baffling in the console. Either make the client use the exact path or add a matching location without the slash.

Idle timeouts are why sockets die at minute one

Once the handshake works, nginx stops parsing HTTP and simply relays bytes in both directions. Two timers still apply. proxy_read_timeout limits how long nginx waits between two successive reads from the upstream, and proxy_send_timeout does the same for writes towards it. Both default to 60 seconds. The timer measures silence, not total duration: a socket that carries one message every 50 seconds can stay open for a week, while one that goes quiet for 61 seconds gets closed.

The tempting fix is to set proxy_read_timeout 3600s in the WebSocket location and move on. That works for the nginx hop and fails for every other hop you do not control. An AWS Application Load Balancer has its own idle timeout, 60 seconds by default and adjustable from 1 to 4000 seconds. Corporate proxies, mobile carrier NAT tables and home routers keep idle state for wildly different periods, some as short as 30 seconds. Raising one timer just moves the disconnect to the next box in the chain.

A heartbeat fixes the whole path at once. If the server sends a WebSocket ping frame every 25 to 30 seconds, every hop sees traffic and resets its idle timer, and browsers answer pings with pongs automatically. Browser JavaScript cannot send protocol-level pings, so a client-side heartbeat has to be an application message, such as a small JSON object the server ignores.

Socket.IO ships this behaviour by default in version 4, with a pingInterval of 25000 ms and a pingTimeout of 20000 ms, which is one reason Socket.IO apps rarely hit the 60-second wall while hand-rolled WebSocket servers hit it constantly.

The counterargument deserves a fair hearing: heartbeats cost bandwidth and wake mobile radios. For 10000 connected clients, a 40-byte ping every 30 seconds adds roughly 13 KB per second, which is noise on a server but real battery on a phone. If your users are mostly on mobile, a longer interval near 50 seconds plus a raised proxy_read_timeout is a reasonable compromise. Just measure the shortest idle timeout on your real path before you choose the number.

Reloads, deploys and the connections nobody drained

Some teams fix headers and timeouts and still see disconnect waves at odd times. Look at reload history. When you run nginx -s reload, the master process starts new workers with the new configuration and asks the old workers to shut down gracefully. Old workers stop accepting new connections but keep serving the ones they have. For short HTTP requests that takes seconds. For WebSockets it can take days, and ps will show rows of "nginx: worker process is shutting down" eating memory.

The directive worker_shutdown_timeout, added in nginx 1.11.11, caps that wait: once it expires, old workers close whatever they still hold. That keeps memory under control, but it also means every reload disconnects every WebSocket after the timeout. ingress-nginx in Kubernetes exposes the same setting as worker-shutdown-timeout in its ConfigMap, with a default of 240 seconds, and its reloads happen whenever Ingress objects or certificates change, not only when someone edits nginx.conf by hand.

An illustrative case shows how this hides. A payments dashboard team in Lisbon (composite example) had about 400 operators connected through ingress-nginx. Every 10 to 15 minutes, a wave of reconnects hit the backend, and all 400 clients reconnected within the same second, which briefly pushed authentication latency from 40 ms to 900 ms. Timeouts were already at 3600 seconds and heartbeats were on.

The cause was a CI job that re-applied a set of Ingress manifests on every pipeline run, each apply triggering a reload. The fix had two parts: the pipeline stopped re-applying unchanged manifests, and the client added reconnection with random jitter between 1 and 5 seconds so the next unavoidable reload would not create a synchronized stampede.

A decision tree for the next ticket

When a new report arrives, walk these questions in order. Each one is answerable in a minute or two from the browser devtools and the nginx logs.

  1. Does the browser network tab show a 101 response for the WebSocket request? If no, go to question 2. If yes, go to question 4.
  2. Is the response a 301 or 308? If yes, the client path and the location path differ by a trailing slash or a scheme redirect; align them. If no, continue.
  3. Is the response a 400, 426 or 200? If yes, the Upgrade and Connection headers are not reaching the backend, or proxy_http_version is still 1.0; fix the location block. If it is a 502 or 504, check that proxy_pass points to a port where the app listens for WebSocket traffic.
  4. Does the connection close after a nearly constant duration, such as 60 or 120 seconds of silence? If yes, an idle timer is closing it; add a heartbeat and then align proxy_read_timeout and any load balancer idle timeout.
  5. Do disconnects arrive in waves across many clients at once? If yes, compare their timestamps with nginx or ingress controller reloads and with deploys of the backend.
  6. Do only some users disconnect, on specific networks? If yes, suspect corporate proxies or mobile NAT and shorten the heartbeat interval.
  7. Do you run several backend instances with a polling fallback enabled? If yes, the fallback needs sticky sessions, for example ip_hash or a cookie-based method, or the polling requests land on instances that do not know the session.

Most tickets end at question 3 or 4. The later questions matter after the obvious fixes are in, when the remaining failures are intermittent and nobody can reproduce them on a laptop.

Verifying the fix and the mistakes that survive review

Do not trust a config change until you have tested both the handshake and an idle period. A short procedure covers it:

  1. Run nginx -t, then reload, and confirm with ps that the new workers are up.
  2. Send a manual handshake with curl, using the sample key from RFC 6455: curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" https://app.example.com/ws/
  3. Expect HTTP/1.1 101 Switching Protocols in the first line. Anything else means the handshake is still broken.
  4. Open a real connection with a client such as websocat, send nothing, and time how long it lives. Wait at least 70 seconds, or 10 seconds past your longest configured idle timeout.
  5. Check the access log for the 101 line and confirm that its request time matches what you observed.
  6. Repeat step 4 through the public load balancer, not only against nginx directly, so that every hop is in the test.

The mistakes that keep coming back in code review are predictable:

  • Hard-coding Connection "upgrade" for a location that also serves normal HTTP requests.
  • Raising proxy_read_timeout to 86400 seconds and calling that a fix, while the load balancer still closes at 60.
  • Forgetting proxy_http_version 1.1 in a location copied from an older HTTP-only block.
  • Adding the WebSocket headers in one location while the client actually connects through another one, often the catch-all location / block.
  • Treating every 1006 close code as a server crash. Code 1006 only means the connection ended without a proper close frame, which is exactly what a timeout produces.
  • Setting worker_shutdown_timeout very low to save memory without telling the frontend team that every reload will now disconnect users.

Your next concrete step is a single command against today's access log: filter lines with status 101 and sort them by request time. A cluster sitting at 60 seconds tells you to add a heartbeat; a spread of short lifetimes tells you to look at reloads.