Software Engineeringunpacked

What is a WebSocket? WebSockets vs Server-Sent Events vs polling, and how they differ from normal HTTP calls

A WebSocket is one long-lived connection between a client and a server where both sides can send messages at any time. A normal HTTP call is the opposite: the client asks, the server answers once, and the exchange is over. Between the two sit polling (ask again and again), long polling (the server holds the question until it has news) and Server-Sent Events (the server streams messages down one open HTTP response). This guide explains each one, how it looks on the wire, and when to pick it.

Video · What Is a WebSocket? WebSockets vs SSE vs Polling vs HTTP Streaming, Explained · 16:22

What is a WebSocket, in one paragraph

Prefer to watch? The 16-minute video walks through every diagram on this page, step by step.

A WebSocket is a single connection that stays open between a client (a browser or an app) and a server, where both sides can send messages at any time. It begins life as an ordinary HTTP request that asks the server to "upgrade". Once the server agrees, HTTP is over and the same TCP connection carries small WebSocket frames in both directions (RFC 6455). That makes it the right tool for chat, multiplayer games and live collaboration, and more machinery than you need for most other features.

To see why it exists, we need to start with the normal call, and with the one problem it cannot solve.

Throughout this guide we will use one running example: a food delivery app. You load the menu, place an order, watch the order status change, follow the driver on a map, and chat with the driver when they cannot find your door.

The normal client-server call (request and response)

A client is the program that asks. A server is the program that answers and holds the data. On the web they talk with HTTP, which runs over TCP (the layers are explained in how the internet works).

A normal call is one request and one response:

GET /orders/42 HTTP/1.1
Host: api.example.com

HTTP/1.1 200 OK
Content-Type: application/json

{"status": "preparing"}

Three rules make this model so easy to work with (RFC 9110):

  1. The client always starts. The server never speaks unless it is asked.
  2. One request, one complete response. Then the exchange is over (the TCP connection may be reused for the next request, but this exchange is done).
  3. Stateless. Each request stands on its own, so any server behind a load balancer can answer it, and responses can be cached.

For most of an app, this is exactly right: loading the menu, placing the order and reading your profile are all normal calls.

The problem: the server cannot call the client

The restaurant accepts order 42. The server knows it immediately. Your phone does not.

The server cannot simply open a connection to your phone: phones and laptops sit behind home routers, NAT and mobile carrier networks that do not accept incoming connections, and a browser tab cannot listen on a port. So under the normal model, news waits on the server until the client asks. Every technique below is a different answer to that one problem.

Short polling: ask on a timer

The simplest answer is polling: the client asks again and again.

client: anything new?
server: no
   (2 seconds later)
client: anything new?
server: no
   (the restaurant accepts the order)
client: anything new?
server: yes, accepted

It is trivial to build and works through every proxy, firewall and CDN. The cost is the problem. With 10,000 users polling every 2 seconds, your servers answer 5,000 requests per second, and almost every answer is "nothing new". And the news is never instant: it can sit on the server for up to one full interval.

Polling has one dial, and both ends hurt. Ask more often and the cost goes up; ask less often and the delay goes up. It is still a sensible choice when updates are rare and a few seconds of delay do not matter, such as checking whether a report has finished generating.

Long polling: let the server hold the question

Long polling keeps the same question but changes when it is answered. The server holds the request open and replies the moment there is news. If nothing happens for a while (often 20 to 60 seconds, so that proxies do not cut the request), it replies "nothing new" anyway. As soon as the client gets any answer, it immediately asks again, so there is almost always one request waiting on the server.

What you get:

What it costs:

Today long polling is mostly a fallback for networks where nothing better gets through. Libraries such as Socket.IO have long used it as their starting transport before upgrading to a WebSocket.

What is a stream?

Before the next two tools, one idea. With a normal response, the server builds the whole answer and sends it in one go: you get nothing until you get everything. With a stream, the answer arrives in pieces, over time, on one connection that stays open. It is the difference between downloading a whole film before watching it and pressing play while it loads.

HTTP already supports this. In HTTP/1.1, a server that does not know the total size sends the body with chunked transfer coding: each chunk starts with its size in hexadecimal, and a chunk of size zero ends the body (RFC 9112, section 7.1).

HTTP/1.1 200 OK
Transfer-Encoding: chunked

17
first piece of the body
16
and another one, later
0

HTTP/2 and HTTP/3 (how the HTTP versions differ) have no chunked coding; they carry every body as a series of DATA frames, which streams naturally. Either way, the client can read each piece as soon as it arrives.

You see this every day: when an AI chat assistant writes its answer word by word, the model is still producing the end while you read the beginning. That is a streamed HTTP response (an API like Claude's also streams, and ends each answer with a stop reason), and the format most AI APIs use for it is the next tool. OpenAI's API, for example, streams with Server-Sent Events when you set stream=true (OpenAI docs).

Server-Sent Events (SSE): the server streams, the client listens

Server-Sent Events is a small standard for a server to push a stream of messages over one HTTP response (WHATWG HTML, section 9.2). The client makes one normal request; the server answers with Content-Type: text/event-stream and keeps the response open, writing one more event whenever something happens.

The SSE format on the wire

It is just text. Each event is a few field: value lines, and a blank line ends the event:

event: status
id: 17
data: {"status":"on_the_way"}

event: driver
id: 18
data: {"meters":300}

: lines starting with a colon are comments, often sent as keep-alives

event is the type, data the message, id a position the client can resume from, and an optional retry tells the browser how many milliseconds to wait before reconnecting.

SSE in the browser: EventSource

Browsers have it built in, no library needed (MDN):

const events = new EventSource("/orders/42/events");
events.addEventListener("status", (e) => {
  showStatus(JSON.parse(e.data));
});

Automatic reconnect with Last-Event-ID

This is the feature people underrate. If the connection drops (a tunnel, a switch from Wi-Fi to mobile data), the browser reconnects by itself after a short wait, and sends the last ID it received in a Last-Event-ID header. A server that keeps recent events can replay exactly what you missed. With polling or WebSockets, you build that yourself.

The limits of SSE

SSE fits whenever the server talks and the client mostly listens: AI answers, live scores, notifications, dashboards, build logs, and the order tracking screen of our delivery app. It also shows up in protocols: an MCP server reached over Streamable HTTP may answer a request with an SSE stream (see what MCP is).

WebSockets: one connection, both directions, any time

A WebSocket is full duplex: once connected, either side can send a message whenever it wants. That is what the chat with the driver needs.

The WebSocket handshake

A WebSocket starts as an HTTP request, which is why it can use the same ports as the web: 80 for ws:// and 443 for wss://, which is encrypted with TLS exactly like HTTPS (TLS and HTTPS explained). The client asks to upgrade (RFC 6455, section 1.3):

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

If the server agrees, it answers with status 101 Switching Protocols:

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

Sec-WebSocket-Accept proves the server understood the request: it is the base64 of the SHA-1 hash of the client's key joined with a fixed GUID from the standard. These two values are the RFC's own example. From this point, HTTP is over on this connection.

WebSocket frames

Messages travel in frames. A frame header is between 2 and 14 bytes: one byte for the FIN flag and the opcode, one to nine bytes for the mask bit and the payload length, and a 4-byte masking key on frames sent by the client (RFC 6455, section 5.2). An HTTP request's headers alone are often hundreds of bytes, so for many small messages the difference adds up.

Frames carry text or binary data, and there are control frames: ping and pong to check that the other side is still there, and close to end the conversation cleanly. Frames from client to server are masked with a random key, so that old proxies on the path cannot be tricked into caching attacker-controlled bytes (section 10.3 of the RFC).

WebSockets in the browser

const ws = new WebSocket("wss://example.com/chat");
ws.onopen = () => ws.send("I'm at the front gate");
ws.onmessage = (e) => showMessage(e.data);

There is no question and answer any more: you send messages, and messages arrive.

What you build yourself with WebSockets

A WebSocket gives you a raw pipe. Many things HTTP and SSE give you for free are now your job:

Scaling long-lived connections

With normal HTTP, any server can answer any request. With WebSockets (and SSE), each connection lives on one specific server for minutes or hours. If you are connected to server A and the driver to server B, a message from the driver has to travel from B to A.

Real systems put a message broker between servers, such as Redis pub/sub, Kafka or NATS: each server publishes what it receives and delivers what concerns its own connections. Your load balancer must also support the upgrade and long idle times (the load balancer section of our networking guide covers layer 4 vs layer 7).

Streaming between services: gRPC

Streams are not only for browsers. Between backend services, gRPC runs on HTTP/2 and has four kinds of methods (grpc.io):

gRPC method Shape Similar to
Unary 1 request, 1 response a normal HTTP call
Server streaming 1 request, many responses SSE
Client streaming many messages, 1 response an upload
Bidirectional streaming both sides stream at once a WebSocket

Webhooks, WebRTC and WebTransport

Three more names that come up in the same conversations:

WebSocket vs SSE vs long polling vs HTTP: side by side

Who talks first Direction Connection Delay Best for
Normal HTTP call client request, then response short none needed most API calls
Short polling client asks on a timer short, repeated up to the interval rare updates
Long polling client server answers when ready held, repeated low fallback
Server-Sent Events server pushes server to client one, long-lived low feeds, notifications, AI answers
WebSocket either side both ways one, long-lived lowest chat, games, collaborative editing

How to choose

Start with one question: does the client need news it did not ask for?

  1. No: use normal HTTP calls. They are the simplest to build, cache, scale and debug, and they are most of any app.
  2. Yes, but rarely, and a few seconds of delay is fine: polling is honestly fine.
  3. The server talks and the client mostly listens: use Server-Sent Events.
  4. Both sides talk a lot, with low delay: use WebSockets, and budget for reconnects, heartbeats and a broker.
  5. Between your own backend services: use gRPC streaming. Between companies' servers: use webhooks.

Our delivery app ends up using four of them, each where it fits:

Feature Approach
Load the menu, place the order Normal HTTP calls
Order status, driver on the map Server-Sent Events
Chat with the driver WebSocket
Payment confirmed to our backend Webhook

Recap

The rule of thumb: pick the simplest one that does the job.

Sources: RFC 6455, The WebSocket Protocol · WHATWG HTML, Server-sent events · MDN, Using server-sent events · MDN, EventSource · MDN, The WebSocket API · RFC 9112, chunked transfer coding · RFC 9110, HTTP semantics · gRPC core concepts · Chrome for Developers, WebSocketStream · MDN, WebTransport API · OpenAI, streaming responses

FAQ

What is a WebSocket in simple terms?

A WebSocket is a connection that stays open after it is created, so the client and the server can both send messages whenever they want, like a phone call instead of an exchange of letters. It starts as an HTTP request that asks to upgrade, and then carries small binary or text frames in both directions.

What is the difference between WebSocket and HTTP?

With HTTP, the client sends a request and the server sends exactly one response, so the server can only speak when asked. A WebSocket upgrades an HTTP connection into a two-way channel that stays open, so the server can push messages at any time and each message costs a frame header of 2 to 14 bytes instead of a full HTTP request.

SSE vs WebSocket: which should I use?

Use Server-Sent Events when the server talks and the client mostly listens: notifications, live scores, dashboards, AI answers streamed word by word. It is plain HTTP, built into browsers as EventSource, and reconnects by itself. Use WebSockets when both sides send often with low delay, such as chat, multiplayer games or collaborative editing.

Is long polling still used?

Yes, mostly as a fallback. Long polling works through almost any proxy or firewall because every exchange is an ordinary HTTP request, but each message costs a full request and response, so SSE or WebSockets are better when the network allows them.

What is a stream in HTTP?

A streamed response sends its body in pieces over time instead of all at once. HTTP/1.1 does it with chunked transfer coding, where each chunk starts with its size in hexadecimal; HTTP/2 and HTTP/3 send the body as a series of DATA frames. The client can read each piece as soon as it arrives.