Coding

WebSocket vs HTTP: Differences and When to Use Each

HTTP is request-response: the client asks, the server answers, and the server can't speak first. A WebSocket starts as an HTTP request that is upgraded into one long-lived, two-way connection, so either side can send messages at any time with only a few bytes of overhead each.

WebSocket vs HTTP at a glance

HTTPWebSocket
CommunicationClient sends a request, server sends one responseBoth sides send messages whenever they want
Who can start a messageOnly the clientClient or server
ConnectionCan be reused, but each exchange is a separate requestOne connection stays open for the whole session
Per-message overheadRequest line plus headers on every request (82 bytes for a minimal curl request, more from browsers)2 to 14 bytes of frame header
CachingResponses can be cachedMessages are not cacheable HTTP responses
URL schemehttp://, https://ws:// (port 80), wss:// (port 443)
StandardRFC 9110 and the per-version RFCsRFC 6455 (2011)
Typical usesPages, files, REST and GraphQL APIs, formsChat, multiplayer games, collaborative editing, live trading data

How a WebSocket connection starts: the HTTP upgrade

Every WebSocket begins life as an HTTP/1.1 GET request asking to switch protocols. This is the client handshake from RFC 6455:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

If the server agrees, it replies with status 101 instead of 200:

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

From that point, the same TCP connection stops carrying HTTP and carries WebSocket frames. RFC 6455 puts it plainly: WebSocket is an independent TCP-based protocol, and its only relationship to HTTP is that the handshake is interpreted by HTTP servers as an Upgrade request.

The Sec-WebSocket-Accept value proves the server understood the WebSocket request rather than being a plain HTTP server echoing headers. The RFC defines it as the base64-encoded SHA-1 hash of the client's key joined with a fixed GUID, 258EAFA5-E914-47DA-95CA-C5AB0DC85B11. You can check the RFC's example yourself in Python:

import hashlib, base64
key = b"dGhlIHNhbXBsZSBub25jZQ=="
guid = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
print(base64.b64encode(hashlib.sha1(key + guid).digest()).decode())

Output:

s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

This is not a security feature. It only confirms both sides are speaking WebSocket.

What a WebSocket message costs on the wire

After the handshake, data moves in frames. Per RFC 6455, a frame header is 2 bytes, plus 2 or 8 more bytes for the length when the payload is longer than 125 bytes, plus a 4-byte masking key on frames sent by the client. Clients must mask every frame they send to the server, and servers must not mask theirs; the RFC requires this to avoid confusing intercepting proxies.

We ran a minimal handshake and one exchange between two Python sockets on our machine, sending the text "hi" each way. The real bytes:

client frame bytes: 81 82 37 fa 21 3d 5f 93 (8 bytes)
server frame bytes: 81 02 68 69 (4 bytes)

Reading the client frame: 81 means "final frame, text" (opcode 1); 82 means "masked, payload length 2"; 37 fa 21 3d is the masking key; 5f 93 is "hi" XORed with that key. The server's frame is 2 header bytes plus the unmasked letters 68 69. So a two-character message costs 8 bytes from the client and 4 from the server.

For comparison, the smallest HTTP request curl 8.13 sent to the same kind of local server, with no cookies and no body, was 82 bytes of headers:

GET /chat HTTP/1.1
Host: 127.0.0.1:8766
User-Agent: curl/8.13.0
Accept: */*

Browsers send far more than curl, often including cookies, and every response carries its own headers too. Each exchange is also a full request and response. If you send ten small updates a second, the WebSocket overhead is a few bytes each; the HTTP equivalent is ten requests.

Using a WebSocket in the browser

const socket = new WebSocket("wss://example.com/chat");

socket.addEventListener("open", () => socket.send("hello"));
socket.addEventListener("message", (event) => console.log("got:", event.data));
socket.addEventListener("close", () => console.log("closed"));
socket.addEventListener("error", () => console.log("error"));

The MDN reference lists those four events and two main methods, send() and close(). It also warns about one gap: the WebSocket API has no way to apply backpressure. If messages arrive faster than your code can handle them, they pile up in memory or keep the CPU busy. MDN points to the newer WebSocketStream as an alternative that handles backpressure automatically.

Things HTTP gives you that WebSockets don't

  • Caching. HTTP responses can be cached by browsers and CDNs. WebSocket messages can't.
  • Status codes and semantics. HTTP has methods, status codes and headers that every tool understands (see GET vs POST). Over a WebSocket you design your own message format, error signalling and request IDs.
  • Stateless scaling. Any HTTP request can go to any server behind a load balancer. A WebSocket ties a client to one server process for the life of the connection, so you need sticky routing and a way to broadcast between servers.
  • Reconnection. If a WebSocket drops, your code has to notice, reconnect and catch up on missed messages. The browser's server-sent events API, by contrast, reconnects automatically and sends a Last-Event-ID header so the server can resume.
  • Easy debugging. Every HTTP tool, from curl to browser dev tools, shows requests clearly. WebSocket traffic is visible in dev tools but harder to replay and test.

The middle option: server-sent events

If only the server needs to push data, you may not need a WebSocket at all. Server-sent events (SSE), defined in the WHATWG HTML Standard, keep one HTTP response open and send events as text/event-stream. They work through ordinary HTTP infrastructure and reconnect automatically. This is how LLM APIs stream answers; see how to stream LLM responses.

NeedBest fit
Load data when the user asks for itHTTP
Server pushes updates; client only listens (notifications, live scores, AI token streaming)Server-sent events
Frequent messages in both directions with low delay (chat with typing indicators, games, collaborative editors)WebSocket
Data changes every few minutesHTTP polling is often good enough

Security notes

  • Use wss://. It is WebSocket over TLS, the equivalent of HTTPS, on port 443 by default. RFC 6455 noted that, at the time it was written in 2011, connections on port 443 were significantly more likely to succeed than on port 80.
  • Check the Origin header during the handshake. RFC 6455 says a server meant only for certain sites should verify that the origin is one it expects and reply 403 Forbidden otherwise; the header exists so that malicious JavaScript running in a trusted browser can't fake a handshake to your server.
  • Authenticate the connection at the handshake and validate every incoming message. A long-lived socket is a long-lived input channel.

Frequently asked questions

Is WebSocket faster than HTTP?
For many small messages in both directions, yes: after the handshake, each message carries only 2 to 14 bytes of WebSocket framing instead of a full set of HTTP request headers, and the server can send without waiting to be asked. For loading pages, files or occasional API calls, plain HTTP is just as fast and much simpler.
Does WebSocket use TCP or UDP?
TCP. RFC 6455 describes WebSocket as an independent TCP-based protocol whose only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. It uses port 80 for ws:// and port 443 for wss:// by default.
What is the difference between ws:// and wss://?
ws:// is an unencrypted WebSocket connection, by default on port 80. wss:// runs the WebSocket over TLS, by default on port 443, the same way https:// relates to http://. Use wss:// in production; it is encrypted and more likely to get through proxies and firewalls.
Do I need WebSockets to stream AI chat responses?
Usually not. LLM APIs stream their answers with server-sent events over ordinary HTTP, because the data flows one way, from server to client, after a single request. A WebSocket only pays off when the client also needs to send a continuous stream of messages on the same connection.

Sources