top of page

What is WebSockets?

Oct 26
12 min read

Updated: Oct 27

What is WebSockets?

 

WebSockets allow a client and server to exchange messages in both directions over an established communication channel. Once the connection is open, either side can send data without waiting for a new application request for every update. This makes the WebSocket protocol useful for chat, collaborative tools, live dashboards and other applications that need continuing interaction.

 

A WebSocket connection is a transport for application messages. It is not a message history, a database, an automatic reconnection system or proof that a command completed. The useful engineering question is what the channel carries, how the application handles a slow receiver, and what happens to information when the connection breaks.

 

From a web request to a continuing conversation

 

Ordinary HTTP requests ask a server to perform an operation or return a representation. A polling application repeats requests to discover whether something changed. WebSockets instead establish a channel that can carry client messages and server updates as they become available. Both directions can be active independently; the protocol does not require a request-and-response pairing for each message.

 

In the familiar HTTP/1.1 arrangement, the client sends a GET request asking to upgrade to WebSocket. The request includes Upgrade and Connection fields, the WebSocket version and a randomly generated key. A server agreeing to the switch responds with 101 Switching Protocols and a corresponding acceptance value. After the handshake is validated, the connection carries WebSocket frames.

 

The key-and-accept exchange demonstrates that the endpoint understood the WebSocket handshake. It is not a password exchange or evidence of the user’s identity. Authentication, permission checks and any required application subprotocol are additional responsibilities. A server can reject the opening request before a WebSocket connection exists.

 

The IETF WebSocket specification, RFC 6455 from December 2011, defines the base protocol. Its HTTP/1.1 upgrade is important, but it is not the only standards-defined way to establish WebSockets. RFC 8441 from September 2018 defines Extended CONNECT over an HTTP/2 stream, and RFC 9220 from June 2022 adapts that mechanism for HTTP/3.

 

Bootstrap

What to recognise

HTTP/1.1

An Upgrade request and a successful 101 response switch the connection to WebSocket framing.

HTTP/2

Extended CONNECT establishes a tunnel on one HTTP/2 stream when supported. It does not use the HTTP/1.1 Upgrade headers or 101 response.

HTTP/3

The corresponding Extended CONNECT mechanism uses an HTTP/3 stream. WebSocket messages do not thereby become unreliable UDP datagrams.

 

These alternatives require suitable support along the actual path. A browser, reverse proxy and server cannot be assumed to negotiate every option merely because an RFC exists. Our HTTP guide explains the distinction between common application semantics and the different transport arrangements used by its versions.

 

What travels over the open channel?

 

WebSocket data messages are text or binary. Text messages use UTF-8; binary messages carry bytes whose meaning is defined by the application. A JSON document is one possible text payload, not a format imposed by WebSocket itself. A server and client must agree on the content they exchange.

 

The protocol wraps data in frames. A frame includes information such as its type, whether it finishes a message, and its payload length. A message can fit into one frame or be split into several fragments. The receiver reassembles the message according to the protocol. Network packets, WebSocket frames and application messages are therefore different boundaries.

 

For example, an application might send the text part-two as two fragments, part and -two. That remains one text message after reassembly. Splitting it does not turn it into two independent application commands. Conversely, receiving several messages in quick succession does not turn them into one message merely because network buffers delivered their bytes together.

 

In the original TCP arrangement, reliable ordered transport underpins the connection. Where WebSockets use an HTTP/2 or HTTP/3 stream, that stream carries the framed data reliably. This does not provide an application history across a broken connection. It also does not mean a slow operation on the server has finished simply because the network delivered its input.

 

Masking is different from encryption

 

For the base framing defined in RFC 6455, clients mask frames sent to servers using a fresh four-byte masking key; servers do not mask frames sent to clients. Masking changes the wire representation to protect against particular intermediary attacks. It does not keep message contents secret, because the key travels with the frame.

 

Use a secure wss connection where confidentiality and integrity are required. TLS protects communication between its endpoints, which may include a terminating reverse proxy. The HTTPS guide explains why transport encryption does not establish that every downstream system is trustworthy or that the application authorises every operation correctly.

 

A local check: messages, fragments and frame sizes

 

We checked the basic behaviour with a small Python server and client on 26 October 2026. The environment used Python 3.12.14 and the installed websockets 16.0 library, over an HTTP/1.1 WebSocket connection bound only to the local loopback address. Compression was disabled. The listener used a temporary port and was closed and checked after the test.

 

The server sent server-first before receiving any application message from the client. The client then exchanged a text message, a three-byte binary message and a fragmented text message. A protocol Ping received its matching Pong, and both endpoints reported normal closure with code 1000. These observations distinguish actual local behaviour from a diagram of how a connection should work.

 

Local check

Observed result

Opening handshake

The client received HTTP status 101.

Server-initiated update

The client received server-first before sending its own application data.

Text and binary

hello returned as text; bytes 00 01 ff returned as binary.

Fragmentation

Sending part and -two as fragments produced one received text message: part-two.

Protocol liveness and closure

A matching Pong arrived; client and server then closed normally with code 1000.

 

This was a functional loopback check, not a browser API test, broadband measurement or production reliability assessment. It did not test TLS, a WAN path, a reverse proxy, HTTP/2, HTTP/3, authentication, reconnection, replay or sustained load. The Python library’s ability to send a protocol Ping should not be attributed to browser JavaScript.

 

How much framing does a small message add?

 

We separately checked serialized frame lengths against the RFC’s field layout. With compression and extensions absent, a single 20-byte payload needs a two-byte base header. A client frame also carries its four-byte masking key, producing 26 bytes in total. The corresponding unmasked server frame is 22 bytes.

 

At a 126-byte payload, an extended length field adds another two bytes: 134 bytes for a masked client frame or 130 for an unmasked server frame. The boundary matters because the short length encoding covers payloads only up to 125 bytes. We also checked the length transition at 65,536 bytes against the eight-byte extended length field.

 

These are WebSocket frame sizes from local serialization, not captured Ethernet packets or total internet usage. TCP/IP, TLS, HTTP/2 or HTTP/3 encapsulation where applicable, handshakes, acknowledgements, retransmissions and application metadata add other costs. Fragmenting a message adds framing for each fragment. A claim that every WebSocket message always has only two bytes of overhead would therefore be misleading.

 

What the browser WebSocket API does and does not do

 

The standard browser interface creates a WebSocket from a URL and, optionally, a set of application subprotocol names. It exposes open, message, error and close events, plus methods for sending data and closing the connection. Its readyState progresses through CONNECTING, OPEN, CLOSING and CLOSED. The constructor is not a general-purpose raw socket interface or an arbitrary request-header editor.

 

The WHATWG WebSockets Standard, last updated on 19 October 2026 when reviewed for this article, specifies this browser behaviour. Calling send queues data for transmission; it does not wait for an application receipt. The bufferedAmount property describes queued outbound application bytes that have not yet been transmitted to the network. A value of zero does not prove that the server processed the message.

 

Receiving messages introduces a separate capacity problem. The classic browser WebSocket API does not provide an automatic application-level backpressure mechanism that makes an overloaded consumer safely keep up. The underlying network can have flow control while the application still accumulates work faster than it handles it. Watching an outbound buffer also does not directly measure the queue of incoming events waiting for application processing.

 

Applications can limit update rates, combine replaceable state updates, pause work through a defined application protocol, or use bounded queues and clear overload behaviour. These choices depend on the data: discarding an old cursor position may be acceptable, while discarding a financial instruction is not. Alternative APIs and libraries have different flow-control features and support requirements; do not assume they behave like the classic interface.

 

Ping, Pong and application acknowledgements

 

WebSocket defines Ping, Pong and Close control frames. Control frames have payloads no longer than 125 bytes and cannot be fragmented. They can appear between fragments of a larger data message, allowing connection control to be handled without waiting for that entire message to finish.

 

A Ping can solicit a Pong from the peer’s protocol implementation. This is useful for liveness checks, but a responsive protocol stack does not prove that a database is healthy or that a previous business command committed. An application requiring that evidence needs a response with the relevant meaning and a way to correlate it with the command.

 

The browser WebSocket API does not expose protocol Ping and Pong directly to JavaScript. An application sending JSON containing a field named ping is sending an ordinary data message. Its meaning and any reply must be implemented by the application on both ends. That is distinct from the protocol-level Ping used in our Python check.

 

Choose heartbeat timing with the actual application and intermediaries in mind. Very short timeouts can misclassify temporary scheduling or network delays as failures; very long ones delay detection. Neither repeated Pongs nor an apparently open connection substitutes for checking the operation that the user is waiting to complete.

 

When the connection breaks, what must be recovered?

 

The standard browser API reports closure; it does not itself restore a complete application session and missed history. An application or higher-level library needs an appropriate reconnection policy. RFC 6455 recommends increasing retry delays and a random initial delay after abnormal closure to avoid many clients overwhelming a recovering service.

 

Reconnection Handling covers the broader recovery process. For a WebSocket application, separate opening a new channel from restoring permissions, subscriptions and data. A connection indicator can turn green before the application is caught up. The interface should reflect that distinction when stale data or uncertain commands matter.

 

Consider an explicitly fictional update stream. A client has applied update 42, disconnects, and misses updates 43 and 44. If the server retains those records and supports resuming from a cursor, the client can request the updates after 42, apply 43 and 44, then continue with 45. Those sequence numbers and the resume request belong to the application protocol, not native WebSocket fields.

 

If the required history has expired, the application needs a supported snapshot or resynchronisation process instead. A cursor is useful only when the corresponding data remains available and the relationship between applying an update and recording its position is well defined. Blindly reconnecting to live messages can leave a permanently incomplete view.

 

Commands need another check. If a connection disappears after a server changes data but before its reply arrives, the client cannot infer that the command failed. Idempotency and operation identifiers can help control repeats under a service’s documented contract. The transport’s ordered messages do not make a reconnect-and-retry sequence an atomic business operation.

 

Close codes provide context rather than a complete diagnosis. Code 1000 indicates normal closure. Code 1006 is a reserved local indication of abnormal closure, such as not receiving a Close frame; it must not be sent as a status code in a Close frame. Seeing 1006 does not identify the failing router, server or application by itself.

 

What is WebSockets infographic explaining the mechanism, key stages and practical limits.

 

An original polling comparison: remove one source of waiting

 

Suppose an application checks for updates every two seconds, and an event is equally likely to occur at any point between checks. Ignoring network and processing time, the event waits between almost zero and almost two seconds for the next check, with an average extra wait of one second. An open push channel can remove that periodic polling wait.

 

For another view of the same illustration, 100 continuously connected clients polling once every two seconds generate 3,000 polling requests per minute. That is 100 multiplied by 30 checks each. It is not a comparison with long polling, and it says nothing about response sizes or how many updates actually occur.

 

WebSockets can avoid repeated empty checks, but they retain connection state and require operational capacity for open channels. They also carry useful updates, control traffic and any application acknowledgements. Fewer requests do not automatically mean lower total cost, and removing polling delay does not remove WAN latency, server queues, browser scheduling or rendering time.

 

For UK home workers, Latency under load can explain why a live application feels delayed during a large upload even though its messages are small. WebSockets cannot create extra broadband capacity or make a congested Wi-Fi link stop queuing. Diagnose the constrained stage rather than treating the protocol name as a speed guarantee.

 

Proxies, security and long-lived connections

 

A reverse proxy must support the way the connection is established and forwarded. The NGINX WebSocket proxying guide explains that HTTP/1.1 Upgrade and Connection fields are hop-by-hop and need appropriate forwarding to the upstream server. A normal web page loading successfully does not establish that its separate WebSocket endpoint is configured correctly.

 

That guide also documents a default timeout of 60 seconds without data from the proxied server, configurable with proxy_read_timeout. This is an NGINX behaviour, not a universal WebSocket lifetime. Check the actual proxy, load balancer and firewall settings, including which direction or event resets each timeout. A regular idle disconnect can be an important clue rather than proof of poor broadband.

 

  • Use appropriate TLS protection and validate certificates and hostnames. Do not disable validation to conceal a connection error.

  • Check browser Origin values against the intended sites, while authenticating users and authorising application operations separately. Non-browser clients can forge Origin.

  • Account for applicable browser cookie policies when a handshake uses an existing login. Origin checks matter because a cross-site page may attempt to open a connection using ambient credentials.

  • Validate message schemas and enforce suitable size, rate, queue and connection limits. Recheck permissions where the application requires it.

  • Treat compression as a negotiated feature with CPU, memory and security trade-offs. RFC 7692 notes risks when history-based compression is combined with secure transport; it is not automatically a free optimisation.

 

Do not assume that ordinary CORS response headers replace WebSocket Origin validation. The server needs the checks appropriate to its handshake and application. A permitted origin is still only part of the decision about who may connect and which actions they may perform.

 

A VPN change, sleeping laptop, Wi-Fi interruption or server restart can all disrupt a long-lived connection. Record timing and close information without logging credentials or private payloads. Comparing a wired connection with Wi-Fi can help locate a problem, but changing access paths also changes other variables and should be treated as evidence rather than a definitive diagnosis.

 

WebSocket, server-sent events or occasional requests?

 

Requirement

Useful starting point

Occasional fetch or command

An ordinary HTTP request and response can be simpler to operate.

Primarily server-to-browser text updates

Server-sent events through EventSource provide a UTF-8 event stream; client commands can use separate requests.

Continuing two-way text or binary messages

WebSocket supplies the bidirectional message channel; application reliability and flow policy still need design.

A framework with extra event features

Check the framework’s own protocol, compatibility and delivery/recovery contract, not just its choice of transport.

 

The HTML standard gives EventSource its own reconnect behaviour and Last-Event-ID mechanism. Those features do not by themselves make the server retain every historical event indefinitely. Select a mechanism by the direction of communication, data format and recovery contract, rather than assuming that every live update needs WebSockets.

 

Socket.IO is a useful example of a different layer: its own documentation states that it adds protocol metadata and is not interchangeable with a plain WebSocket client or server. Features such as framework-managed reconnection should not be credited to the base WebSocket API. Likewise, carrying another application protocol over WebSocket does not erase that protocol’s own rules.

 

A practical diagnostic sequence

 

  1. Identify the actual endpoint and affected scope. Establish whether only the live-update feature fails or whether ordinary requests and unrelated services also fail.

  2. Check name resolution, TLS and the opening handshake. For an HTTP/1.1 path, inspect the expected upgrade; for another bootstrap, check the supported Extended CONNECT path instead of insisting on 101.

  3. Inspect application authentication, permissions, selected subprotocol and message format. A connected channel with rejected commands is a different fault from a failed handshake.

  4. Compare message arrival, processing time and outbound bufferedAmount where available. Look for a slow handler, an excessive update rate or an overloaded server.

  5. Correlate closure timing with heartbeats, proxy idle timeouts, sleep, network changes and load. Preserve the actual close code and relevant server-side logs.

  6. After reconnection, verify the supported state-restoration process and reconcile uncertain commands before declaring the application ready.

 

Developer tools can show the connection and message activity, while application logs supply processing and acknowledgement evidence. These observations answer different questions. A successful message send, a matching Pong and a completed user operation should not be reported as if they were the same test.

 

Frequently asked questions

 

Are WebSockets the same as HTTP?

 

No. WebSocket defines a framed bidirectional message channel. HTTP is used in establishing it, with different bootstrap mechanisms for HTTP/1.1, HTTP/2 and HTTP/3. Subsequent WebSocket data messages are not ordinary HTTP requests and responses.

 

Does masking make WebSocket traffic private?

 

No. Masking is a framing protection and its key accompanies the data. Use a suitably protected wss connection for transport confidentiality and integrity, together with proper authentication and authorisation.

 

Do WebSockets automatically replay missed messages?

 

No. The application or framework must provide supported history, resumption or snapshot recovery. Opening a new connection alone does not recover updates missed while the old channel was unavailable.

 

Will WebSockets make a slow broadband connection fast?

 

They can avoid periodic polling waits and support prompt two-way updates. They do not remove path latency, congestion, server processing or browser workload, and they do not increase the access line’s capacity.

 

What to remember

 

WebSockets provide a continuing conversation with explicit message boundaries. A reliable application then adds the right security, capacity limits, operation acknowledgements and recovery contract. Follow the whole path from an update being created to the user seeing the correct state, especially after a disconnection.

 
 
UK Techie Broadband Providers
bottom of page