Wesloo
All topicsTopics

Web technologies

What is WebSocket and how it works?

Short answer

WebSocket is a protocol for bidirectional, low-latency communication over a persistent connection between a client and a server. It begins with an HTTP handshake and then stays open so either side can send messages without creating a new request each time. Use it when an application needs frequent real-time updates; use ordinary HTTP when request-response traffic is enough.

Key points

  • WebSocket keeps one connection open so client and server can send messages in both directions without repeated HTTP requests.
  • It starts with an HTTP handshake, then switches to a persistent WebSocket connection.
  • Use it for frequent real-time updates such as chat, live dashboards, collaborative editing, and multiplayer games.
  • It is less suitable for simple page loads or occasional API calls where request-response HTTP is enough.
  • Production use requires reconnection, authentication, scaling, and monitoring plans.

What is WebSocket and how it works

What is WebSocket and how it works? This protocol lets a client and a server exchange data over a persistent connection. Once connected, each side can send messages on its own, without a new HTTP request for every message. It gives full-duplex communication over one TCP connection, so data can travel both ways at once. It differs from HTTP, which uses request and response messages, yet it is meant to work over HTTP ports 80 and 443 and through many proxies and intermediaries.

The browser exposes this capability through the WebSocket API. A web application creates a connection to a URL, then listens for messages and sends messages through that same connection. Because the connection stays open, the server can push updates to the client as soon as they are available instead of waiting for the client to ask.

How a WebSocket connection starts

A WebSocket connection starts with an HTTP handshake. The client asks to upgrade the connection, and the server confirms the change. After the handshake, both sides can exchange messages over the new connection. It stays open until one side closes it or the network breaks it.

  1. The client sends an HTTP request with an upgrade instruction and a Sec-WebSocket-Key header.
  2. The server validates the request and returns a 101 Switching Protocols response with a Sec-WebSocket-Accept value.
  3. Both sides switch from HTTP framing to WebSocket frames.
  4. Either side can send a close frame, or the connection can be interrupted by a network failure.

The Sec-WebSocket-Key and Sec-WebSocket-Accept values help prevent a caching proxy from replaying an earlier WebSocket conversation. They are not a substitute for authentication, privacy, or integrity. When a proxy is in use, a client may open an HTTP CONNECT tunnel to the destination host and port.

RFC 6455, published in 2011, is the standardized protocol. Some browsers implemented earlier drafts, and several of those drafts were revised or disabled during development for security reasons. Current clients and servers follow the standardized handshake and framing rules.

WebSocket and HTTP compared

FeatureHTTPWebSocket
Communication patternClient request, server responsePersistent bidirectional channel
Who can start a messageClient onlyClient or server
Connection lifetimeOften short or reused per requestStays open until closed
Best fitPages, files, APIs, occasional dataFrequent real-time updates
Overhead per updateHeaders and request setup each timeFrame-based messages after handshake

HTTP is the right choice for loading documents, submitting forms, and calling APIs where each interaction is independent. WebSocket is the better choice when the server must notify the client quickly or when messages flow in both directions many times per second. Polling can simulate updates over HTTP, but it wastes bandwidth and adds delay because the client must keep asking.

Another difference is connection state. HTTP requests are usually independent, which makes them easy to cache, retry, and load balance. WebSocket connections are stateful, so the application must track which user and session belong to each socket and handle reconnects explicitly.

When should you use WebSocket?

Use WebSocket when an application needs frequent, low-latency, two-way communication. Typical cases include chat, live dashboards, collaborative editing, multiplayer games, and trading. In these cases, the server often has new information before the client knows to ask for it, and repeated HTTP requests would add unnecessary overhead.

Do not use WebSocket for every interaction. A simple content page, a file download, or an occasional API call is usually better served by HTTP, caching, and a normal request-response flow. Adding a persistent connection to a low-traffic feature can increase server memory use, complicate deployment, and create failure modes that HTTP avoids.

A practical test is to ask whether the server needs to push data without a client request, whether messages arrive more than once every few seconds, and whether the user experience depends on low delay. If the answer is yes to all three, WebSocket is a strong candidate. If only the server needs to push updates and the client never sends data, Server-Sent Events may be simpler. If the client only needs occasional updates, long polling may be enough.

Using the WebSocket API in a browser

All modern browsers support the WebSocket API. An application creates a WebSocket object with a URL, and optionally with one protocol string or an array of protocol strings. The URL scheme is ws for an unencrypted connection and wss for a connection protected by TLS. If an http or https URL is supplied, the browser transforms it to ws or wss.

After construction, the application handles connection lifecycle events and messages. The onclose handler runs when the connection closes, and similar handlers cover opening, messages, and errors. The protocol property holds the protocol the server accepted, or an empty string when no protocol was requested. The url property contains the URL used to create the connection, after scheme transformation.

Optional protocols are sent in the Sec-WebSocket-Protocol header during the opening handshake. This lets client and server agree on a message format, such as a chat protocol or a game protocol, before application data flows. Frames can carry text or binary payloads, so the chosen protocol should define encoding, message boundaries, and error handling.

Scaling WebSocket applications

Persistent connections change how an application scales. Each open socket consumes server resources, so capacity planning must account for concurrent connections rather than only requests per second. Load balancers may need sticky sessions or a shared pub/sub layer so that a message published on one server reaches a client connected to another.

Operational details matter. Applications need heartbeats or ping frames to detect dead connections, reconnection logic with backoff, and clear rules for authentication and authorization. Messages should be validated on the server, and large or frequent messages should be rate limited. Backpressure handling prevents a slow client from consuming unbounded memory.

Proxies and intermediaries can also affect behavior. Client implementations often detect proxy settings and may use HTTP CONNECT to build a tunnel. Because the protocol is designed to work over ports 80 and 443, it usually passes through corporate and cloud proxies more easily than a custom TCP protocol.

Security considerations

Use wss in production so traffic is encrypted in transit. Validate the Origin header on the server, authenticate users before trusting messages, and authorize each action independently. The handshake key exchange is not a substitute for authentication, privacy, or integrity controls.

Also protect the application layer. Parse and validate every incoming message, enforce size and rate limits, and avoid reflecting untrusted data without escaping. Treat a WebSocket endpoint like any other public API surface, because clients can send arbitrary frames once connected.

Alternatives to WebSocket

WebSocket is not the only real-time transport. Server-Sent Events provide one-way server push over HTTP and are simpler when the client does not need to send frequent messages. Long polling keeps an HTTP request open until data arrives, then repeats, which can work through restrictive proxies but adds latency. MQTT can run over WebSocket in some broker implementations. Some services support several transports, so the choice can depend on the use case.

For AI chat products, teams sometimes compare WebSocket with long polling, gRPC, and Streamable HTTP. The right choice depends on whether the interaction is bidirectional, how much latency matters, and how much connection management the team wants to own.

If you are choosing a backend stack for a WebSocket service, see Choose programming language: a practical guide. For background on how programming languages evolved, see History programming languages: from Ada to Python.

Questions people also ask

What is WebSocket used for?

WebSocket is used for applications that need frequent, low-latency, two-way updates, such as chat, live dashboards, collaborative editing, multiplayer games, and data feeds.

How does a WebSocket connection start?

It starts with an HTTP handshake. The client requests an upgrade, the server accepts it, and the connection then switches to WebSocket frames that stay open until closed or interrupted.

Is WebSocket the same as HTTP?

No. HTTP follows a request-response model, while WebSocket provides a persistent bidirectional channel after an initial HTTP handshake.

When should I not use WebSocket?

Avoid it for simple pages, file downloads, or occasional API calls where independent HTTP requests, caching, and request-response handling are simpler and sufficient.

Are WebSocket connections secure?

They can be. Use wss for TLS encryption, validate the Origin header, authenticate users, and validate every message on the server.

Related pages

  • Client vs Server Rendering: Architecture and Performance

    Client-side rendering generates HTML directly inside the user browser via downloaded JavaScript, whereas server-side rendering compiles the full HTML document on the origin or edge server prior to transmission. This core difference shifts computational burdens between client hardware and cloud infrastructure, altering First Contentful Paint times, search indexing reliability, and hosting costs. Teams select between them based on content volatility, interaction requirements, and performance objectives.

  • How Does Browser Cache Work? A Practical Guide

    A browser cache stores local copies of web resources so repeat visits skip downloads. Servers set freshness with Cache-Control, and browsers validate or evict entries when space runs low.

  • How Do Web Cookies Work? A Practical Guide

    A web cookie is a small piece of data a server sends to a browser, which the browser stores and returns with later requests to the same site. Cookies let stateless HTTP remember logins, preferences, and activity, but they also raise privacy and security concerns.

  • What is a REST API vs API? A Practical Guide

    An API is a contract that lets software systems exchange requests and responses. A REST API is one kind of API that uses HTTP methods and resource-based URLs to manage data, usually with JSON. All REST APIs are APIs, but many APIs use other protocols or styles.

  • What is GraphQL API? A Practical Guide

    A GraphQL API is a query language and runtime for APIs that lets a client request only the fields it needs, including related data, in one operation. It is backed by a strongly typed schema that defines types, fields, and allowed operations. Clients control the shape of the response, while the server resolves data from its sources.

  • What is CORS in IT? Browser security explained

    Cross-Origin Resource Sharing (CORS) is a browser security mechanism that lets a server declare which other origins may read its responses. It extends the same-origin policy so trusted sites can use APIs and resources hosted elsewhere. Without the right headers, a script's cross-origin request fails in the browser.

How this page was prepared

Before writing, the topic was researched in the sources below. The page then passed automatic quality checks.

Report a mistake on this page