Loading...

Performance

What is WebSocket? The upgrade handshake, proxies and timeouts

HTTP is built around a question and an answer: the browser asks, the server replies, and the exchange is over. WebSocket turns one HTTP request into a connection that stays open, so either side can send a message the moment it has one. This guide explains the handshake, when WebSocket is the right tool, why connections drop behind proxies, and how to run WebSocket through a CDN.

9 min read Intermediate Updated

What is WebSocket? The upgrade handshake, proxies and timeouts

Why plain HTTP is not enough

Classic HTTP is request and response. The client asks, the server answers, and the server cannot speak again until it is asked. For a page that changes when the user clicks, that is fine. For a chat window, a price ticker or a game, the server has news the client did not ask for.

The workarounds have names. Polling asks every few seconds whether anything changed; most answers are "no", and each one costs a full request. Long polling keeps a request open until the server has something to say, then starts over. Both work, and both add latency and overhead to bend request and response into something they were not designed for.

WebSocket (RFC 6455) solves this in the protocol: one connection, opened once, over which client and server send messages whenever they like, in both directions, with a few bytes of framing per message.

The upgrade handshake

A WebSocket begins life as HTTP. The browser sends a GET request with Upgrade: websocket and Connection: Upgrade, a random Sec-WebSocket-Key and the protocol version. A server that agrees answers 101 Switching Protocols with a Sec-WebSocket-Accept value computed from the key, which proves it understood the request rather than replaying a cached answer.

After the 101, HTTP is finished on that connection. The same TCP and TLS connection now carries WebSocket frames: text or binary messages, plus small control frames called ping, pong and close. The URL scheme is ws://, or wss:// over TLS. On a public site always use wss://: it runs on port 443 like HTTPS and passes through networks that block anything unusual.

This is the HTTP/1.1 form. HTTP/2 and HTTP/3 have their own way to carry WebSocket (RFC 8441 and RFC 9220), but the HTTP/1.1 upgrade is still what most servers and proxies speak towards the application.

The handshake: request and response

GET /chat HTTP/1.1
Host: app.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

When to use WebSocket, and when not

Good fits. Chat and support widgets, live dashboards and trading screens, multiplayer games, collaborative editors, presence ("who is online"), and any app where the server pushes events and the client answers quickly.

Server-Sent Events (SSE) are the simpler choice when only the server talks: news feeds, build logs, progress bars, notifications. SSE is plain HTTP with a response that keeps streaming, reconnects by itself and passes wherever HTTP passes.

Plain HTTP is still right for everything that is request and response: pages, APIs, file downloads. Those can be cached; a WebSocket message cannot. A healthy design uses both: HTTP to load data and assets, one WebSocket for live updates.

Why WebSocket connections drop behind proxies

A WebSocket crosses every hop between the browser and your application: corporate proxies, load balancers, a CDN, nginx in front of your app. Each of them has to get two things right.

Pass the upgrade. Upgrade and Connection are hop-by-hop headers: a proxy does not forward them unless it is told to. If one hop drops them, your application receives an ordinary GET and answers 400 or 404, and the browser reports that the handshake failed.

Allow idle time. Proxies close connections on which nothing has happened for a while. A WebSocket can be silent for minutes between messages, so an idle limit meant for HTTP closes it. In nginx that limit is proxy_read_timeout, 60 seconds by default: if the backend sends nothing for 60 seconds, nginx closes the connection and the browser sees close code 1006.

The fix has two halves. Raise the idle limit on the hops that carry WebSocket traffic, and have the application send a ping, or a small heartbeat message, more often than the shortest idle limit on the path; every 20 to 30 seconds is typical. As long as data flows, the connection stays open.

nginx in front of a WebSocket app

If nginx proxies to your application, the WebSocket location needs HTTP/1.1 towards the backend, the two upgrade headers, and timeouts longer than your heartbeat interval. The map sends Connection: upgrade for WebSocket requests and closes ordinary ones normally, so one location serves both.

proxy_read_timeout is how long nginx waits for the backend to send something; proxy_send_timeout is how long it waits while sending to the backend. Neither limits the total length of a connection: a socket that carries a message every 30 seconds can stay open for days.

nginx: proxy WebSocket connections to an app on port 3000

# http {} level
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    # ...
    location /ws/ {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;

        # longer than the app's ping interval
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}

WebSocket on cdn.com.tr

On cdn.com.tr WebSocket is a setting of each delivery rule. Create a rule for the path your application uses for WebSocket, such as /ws/ or /socket.io/, and switch on Allow WebSocket connections. The edge passes the visitor's handshake to your origin, and once your origin answers 101 the connection stays open between them while data flows. Responses on that path are not cached, which is exactly what a live connection needs.

The same rule has two timeouts, each from 1 to 3,600 seconds: how long the edge waits for your origin to send something, and how long it waits while sending to your origin. The default is 60 seconds. On the domain of your Managed Container apps, WebSocket is on by default and both timeouts are 300 seconds unless the rule sets other values. Set the read timeout above your application's ping interval and idle sockets stay open.

Give WebSocket its own rule. The rest of the site keeps its caching, image optimization and compression, and the WebSocket path gets a connection passed straight through to your origin. The origin connection guide shows the fields; the same timeouts also serve long-running HTTP requests, which otherwise end in a 504 Gateway Timeout.

Keep clients connected

Even with every timeout right, connections end: a phone changes networks, a laptop sleeps, a new version of your app is deployed. Treat a closed socket as a normal event and design for it.

Reconnect automatically, with a delay that grows after each failed attempt (for example 1, 2, 4 and 8 seconds, up to a ceiling) plus a little randomness, so thousands of clients do not all reconnect in the same second.

Resume, do not restart. Send the last message ID or timestamp when reconnecting, so the server can replay what the client missed.

Send heartbeats from the server, or from the client if your library does not, and treat a missing pong as a dead connection.

Socket.IO and many WebSocket client libraries do most of this for you; check that it is switched on.

Where WebSocket shines

Chat and support

Messages and typing indicators arrive the moment they are sent, without a request every few seconds.

Live dashboards

Prices, orders and metrics pushed to the screen as they change.

Games and collaboration

Moves, cursors and edits shared between players or editors with minimal delay.

How to set it up

Step-by-step guides in the help centre:

WebSocket FAQ

Is WebSocket faster than HTTP?

For frequent small messages, yes: after the handshake each message carries a few bytes of framing instead of a full set of HTTP headers, and the server can send without waiting for a request. For pages, files and API responses, HTTP is the better tool, and it can be cached.

What is the difference between ws:// and wss://?

wss:// is WebSocket over TLS, the way https:// is HTTP over TLS. It is encrypted and passes through proxies and firewalls far more reliably. Use wss:// on any public site.

Why does my WebSocket close after exactly 60 seconds?

A proxy on the path closes connections that stay idle for 60 seconds, which is the nginx default for proxy_read_timeout. Raise the timeout on that hop and have your application send a ping every 20 to 30 seconds.

Do WebSocket connections work through a CDN?

Yes, when the CDN passes the upgrade. On cdn.com.tr you switch on WebSocket in the delivery rule for that path; the connection then reaches your origin and stays open while data flows.

Can WebSocket messages be cached?

No. Messages belong to one live connection. Cache the HTTP side of your application, its pages, assets and API responses, and keep the WebSocket path on a rule of its own.

How long can a WebSocket connection stay open?

On cdn.com.tr there is no limit on the total length: as long as data flows, the connection stays open. What you set per rule, up to 3,600 seconds, is how long it may stay idle.