WebSocket Interview Questions: Handshakes, Scaling, Reconnection, and Delivery Guarantees

Practice WebSocket interview questions on handshakes, scaling, heartbeats, backpressure, reconnection, ordering, and delivery guarantees.

Author: PracHub

Published: 8/14/2026

WebSocket Interview Questions: Handshakes, Scaling, Reconnection, and Delivery Guarantees

August 14, 2026

Quick Overview

Prepare for WebSocket interviews with 20 senior-level questions covering the HTTP upgrade handshake, authentication, frames, heartbeats, backpressure, horizontal scaling, gateway routing, graceful draining, reconnection, ordering, replay, deduplication, and delivery guarantees. Includes a production recovery scenario and a practical answer framework for backend and full-stack engineers.

Backend EngineerFree

Opening one WebSocket is easy. Recovering a million connections after a regional outage without causing a second outage is the real interview question.

This guide covers the WebSocket interview questions backend and full-stack engineers are most likely to face, from the HTTP opening handshake to heartbeats, backpressure, horizontal scaling, reconnection, ordering, and delivery guarantees. The goal is to help you explain not only how a connection works, but how a real-time product behaves when clients slow down or networks fail.

Use PracHub to practice real interview questions with written solutions, then narrow your preparation with company-specific interview prep. Start with a realistic prompt, find the gap in your answer, and review only the protocol or system-design concept you actually need.

WebSocket interview questions on handshakes scaling reconnection and delivery guarantees

A senior WebSocket answer follows the connection from upgrade through routing, recovery, and application-level delivery.

Quick Verdict: What a Strong WebSocket Answer Includes

A good answer does not end with "WebSockets are full duplex." It explains which guarantees come from the protocol, which belong to TCP, and which must be built by the application.

#Senior answer should connect
1Handshake: HTTP upgrade, origin, authentication, subprotocols, and proxies
2Connection: frames, heartbeats, close semantics, buffers, and slow consumers
3Scale: gateways, routing, shared state, fanout, draining, and reconnect load
4Delivery: sequence numbers, acknowledgements, replay, deduplication, and idempotency

WebSocket Handshake and Protocol Questions

1. What happens during the WebSocket opening handshake?

With classic HTTP/1.1 WebSockets, the client sends a GET request with Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key, and version 13. A successful server responds with 101 Switching Protocols and a calculated Sec-WebSocket-Accept value.

After that response, the connection stops carrying ordinary HTTP request-response messages and begins carrying WebSocket frames in both directions. In production, the reverse proxy must understand the upgrade; for example, NGINX documents that hop-by-hop Upgrade and Connection headers need explicit proxy handling.

2. What does Sec-WebSocket-Key prove?

The server appends a fixed GUID to the client's random key, hashes the result with SHA-1, Base64-encodes it, and returns it as Sec-WebSocket-Accept. This proves that the server received a WebSocket handshake and understood the protocol.

It does not authenticate the user or encrypt the connection. User identity needs a separate authentication design, and confidentiality comes from TLS with wss://.

3. Why are browser-to-server frames masked?

RFC 6455 requires every client-to-server frame to carry a masking key. The purpose is to stop malicious browser content from putting attacker-controlled byte patterns on the wire that vulnerable intermediaries might misinterpret as another protocol.

Masking is not secrecy. Servers can unmask the data, and traffic still needs TLS to protect it from network observers or modification. Server-to-client frames are not masked.

4. What are text, binary, and control frames?

Text frames carry UTF-8 data, binary frames carry application-defined bytes, and control frames signal close, ping, or pong. One logical message can be split across several frames, while control frames may appear between its fragments so a large message does not block a ping or close indefinitely.

A strong answer separates a message from a frame. Application code usually reasons about complete messages; framing is the protocol's transport structure.

5. Do WebSockets work over HTTP/2?

Yes, when the client and server support RFC 8441. Instead of the HTTP/1.1 GET upgrade, HTTP/2 uses Extended CONNECT with :protocol set to websocket after the peer advertises support.

Do not assume every proxy or deployment path supports that mechanism. In an interview, state the classic HTTP/1.1 handshake first, then mention Extended CONNECT as the HTTP/2 path.

Authentication and Connection Lifecycle Questions

6. How should a browser WebSocket connection be authenticated?

Authenticate during the handshake where possible, then authorize subscriptions and commands after the connection opens. Secure cookies work naturally for same-site browser sessions; short-lived signed connection tokens are another pattern when the architecture requires them.

The standard browser WebSocket() constructor accepts a URL and optional subprotocols, not arbitrary request headers. Whichever approach you choose, validate the browser's Origin, avoid long-lived credentials in URLs or logs, and never treat connection authentication as permission to every channel.

7. What happens when a token expires on a long-lived connection?

Define this before launch. The server can require reauthentication in an application message, close the connection with an application-specific code so the client obtains a new token, or bind authorization to a shorter-lived subscription lease.

The important boundary is that revocation and role changes must take effect without waiting forever for the socket to disappear. Recheck authorization for sensitive operations, not only once at connection time.

8. What is the difference between Ping/Pong and an application heartbeat?

Protocol Ping asks the peer to return a Pong and can detect an unresponsive connection. An application heartbeat can additionally carry domain state such as the last processed sequence, session lease, or client readiness.

These signals answer different questions. A Pong proves the peer's WebSocket stack responded; it does not prove the business event loop is healthy or that the latest message was processed.

9. How should close codes be handled?

A clean shutdown exchanges Close frames before the TCP connection ends. Code 1000 means normal closure, 1001 means an endpoint is going away, and 1006 is a reserved value used locally to represent an abnormal close without a received Close frame; an endpoint must not send 1006 in a Close frame.

Map close reasons to client behavior. A normal logout should not reconnect, an expired credential may require refresh, and an abnormal network failure should use delayed retry rather than an immediate loop.

Backpressure and Slow-Consumer Questions

10. Does WebSocket.send() mean the message was delivered?

No. In the browser API, send() is asynchronous and returns after placing data in an internal buffer. bufferedAmount reports bytes queued but not yet transmitted to the network.

Even reaching the network is not the same as application processing. If the sender needs that guarantee, the application must define an acknowledgement and decide how long to retain, retry, or reconcile the event.

11. How do you handle a slow consumer?

Give each connection a bounded outbound queue and monitor queue age or size. Once it crosses a threshold, the policy depends on the data: coalesce replaceable presence updates, drop explicitly lossy telemetry, or disconnect and require a durable stream to resume.

Never allow one slow client to grow memory without limit. Also avoid blocking a shared event loop while waiting for that client, because one connection can then degrade thousands of healthy ones.

12. Should you compress or batch WebSocket messages?

Batching reduces per-message overhead but adds latency and makes failure recovery coarser. Compression can help repetitive text payloads, yet costs CPU and memory, may add latency for small messages, and needs careful security review when secrets and attacker-controlled content share a compression context.

Measure with the actual payload distribution. For rapid counters, coalescing may beat compressing every update; for a large collaborative document delta, binary encoding and negotiated compression may be worthwhile.

Scaling WebSockets Across Servers

13. How do you scale WebSocket gateways horizontally?

Place multiple connection gateways behind a WebSocket-aware load balancer. Each gateway owns its active sockets, while durable business state and event history live outside the gateway in databases, logs, or streams.

Publish events through a shared routing or pub/sub layer so the service that creates an event does not need to know which gateway holds the recipient. Track active connections, queue pressure, fanout latency, reconnect rate, and connections per instance.

14. How does the system find a user's connection?

Maintain a registry from user, room, or topic to one or more gateway instances, then let the owning gateway map that target to local sockets. Presence changes should have leases or heartbeats so a crashed gateway does not leave permanent stale entries.

For very large fanout, avoid a central lookup for every event. Partition topics consistently, cache local subscriptions, and batch delivery to each gateway while preserving the sequence information clients need.

15. Are sticky sessions required?

An established TCP connection is already attached to one gateway, so every frame on that connection reaches the same instance. Sticky load balancing mainly affects which gateway receives a new or reconnected client.

You do not need sticky sessions if gateways keep only disposable connection state and shared systems can restore subscriptions or route events. If correctness depends on process memory that another gateway cannot reconstruct, stickiness is hiding an availability problem.

16. How do you deploy without causing a reconnect storm?

Stop accepting new connections, keep the instance ready while existing sockets drain, and close remaining clients gradually with a reason they understand. Clients should reconnect with jitter, respect retry guidance, and avoid all retrying at the same fixed interval.

Capacity planning must include overlap: old gateways may still hold connections while new gateways accept reconnects. A rollout is not complete when the process stops; it is complete when connection load and subscriptions have moved safely.

Reconnection and Delivery Guarantee Questions

17. What is a safe reconnection strategy?

Classify the close first, then use exponential backoff with random jitter for retryable failures. RFC 6455 gives a random 0-to-5-second delay as a reasonable initial example and recommends increasingly longer delays after repeated failures.

Cap the delay and retry count according to the product, pause when the device is offline, and reset the backoff only after the connection has been stable. Immediate retries from every client can behave like a denial-of-service attack against a recovering service.

18. How can a client resume missed events?

Give events stable IDs or monotonically increasing sequence numbers within a defined scope. The client records the last event it has applied and sends that cursor after reconnect; the server replays the missing range from durable history or returns a fresh snapshot when the gap is no longer available.

Define the boundary precisely. A sequence may be per room, per user, or per partition, but calling it "global" without a scalable ordering mechanism creates an impossible promise.

19. What delivery guarantees does WebSocket provide?

WebSocket provides ordered message fragments within one connection, over TCP. It does not define durable storage, application acknowledgements, replay after disconnect, or exactly-once processing.

At-most-once means you do not retry after ambiguity and may lose events. At-least-once adds acknowledgement and retry but can create duplicates. Choose the guarantee per event type rather than claiming one policy for chat messages, cursor positions, payments, and notifications.

20. How do you build ordered or exactly-once user-visible effects?

Attach a message ID and scoped sequence, persist the event before acknowledging when durability is required, and let the receiver deduplicate before applying side effects. On reconnect, replay from the last acknowledged sequence and repair gaps before accepting later state as complete.

"Exactly once" is usually an application-level effect, not a transport property. Idempotency keys, unique database constraints, transactional writes, and durable deduplication make repeated delivery produce one business outcome.

WebSocket event workflow from connection and authentication to routing delivery and resume

Trace one event through connection, authorization, routing, delivery, and replay after a disconnect.

Worked Scenario: A Chat Gateway Region Restarts

Suppose a regional gateway pool restarts while thousands of users are in active rooms. Messages are written to a durable log with room-scoped sequence numbers before gateways fan them out. Each client tracks the highest contiguous sequence it has applied.

Clients detect the abnormal close and reconnect with jittered exponential backoff. A load balancer may place them on different gateways, which restore authorization and subscriptions from shared state rather than relying on the old process.

Each client sends its last acknowledged sequence. The new gateway replays the missing range, the client deduplicates by event ID, and a snapshot replaces replay if the gap has expired. Presence updates can be coalesced, but durable chat messages cannot be silently dropped.

This answer is stronger than "use Redis Pub/Sub." It defines the source of truth, ordering scope, reconnection load, replay boundary, slow-consumer policy, and observable failure signals.

What Interviewers Are Actually Scoring

Junior answers name the handshake and full-duplex connection. Mid-level answers cover heartbeats, load balancers, and pub/sub. Senior answers define state ownership and failure semantics.

Interviewers listen for the moment you separate transport order from durable delivery. They also want to hear what happens to one slow client, how authorization changes during a long session, and how the system recovers without synchronized reconnects.

For broader architecture practice, use PracHub's system design questions. Real-time interviews also test incident ownership and communication, so include behavioral and leadership practice in your final preparation loop.

A Five-Step Framework for Any WebSocket Design Question

1. Open the channel. Explain the handshake, TLS, origin validation, authentication, subprotocol, and proxy behavior.

2. Bound connection state. Define heartbeats, token refresh, buffers, slow-consumer policy, close codes, and resource limits.

3. Route at scale. Show gateway ownership, shared subscription state, event fanout, partitioning, and graceful draining.

4. Recover the stream. Use jittered backoff, a resume cursor, replay or snapshot, gap handling, and deduplication.

5. State the guarantee. Name the ordering scope, acknowledgement point, durability boundary, and whether effects are at-most-once, at-least-once, or idempotent.

Frequently Asked Questions

WebSocket vs SSE: which should I choose?

Choose WebSocket when both client and server need frequent messages on one long-lived channel. Server-Sent Events are one-way from server to browser and can be simpler for feeds, status updates, or token streaming when client commands can remain ordinary HTTP requests.

Does WebSocket guarantee message order?

It preserves frame and message order within one connection. That does not create a global order across multiple publishers, partitions, gateways, or a disconnect followed by replay. Define an application sequence if that wider order matters.

Does WebSocket reconnect automatically?

The standard browser WebSocket API does not provide automatic reconnect. Your application or chosen library must classify closure, wait with backoff and jitter, reauthenticate, restore subscriptions, and reconcile missed events.

Do WebSockets require sticky sessions?

No. A live connection already remains on one gateway, while a reconnect can safely land elsewhere if the new gateway can restore authorized subscription state and resume delivery. Stickiness is an optimization or migration aid, not a substitute for recoverable state.

Can WebSocket guarantee exactly-once delivery?

No. WebSocket itself has no durable acknowledgement or deduplication protocol. You can approximate exactly-once business effects with stable IDs, idempotent handlers, transactional state changes, unique constraints, and replay-aware clients.

Final Takeaway

The best WebSocket interview answers follow one connection all the way through failure. Explain how it opens, where its state lives, how pressure is bounded, what happens after disconnect, and which component owns each delivery promise.

Practice that reasoning against realistic prompts in PracHub's interview question library, then repeat the design aloud until every retry, acknowledgement, and recovery step has a clear owner.

Official Sources

RFC 6455: The WebSocket Protocol defines the HTTP/1.1 handshake, framing, masking, Ping/Pong, closing handshake, status codes, ordering, TLS guidance, and reconnect backoff. RFC 8441 defines bootstrapping WebSockets over HTTP/2 with Extended CONNECT.

MDN WebSocket API, the WebSocket constructor reference, bufferedAmount reference, and client application guide support the browser API, buffering, lifecycle, and sending behavior discussed here.

NGINX WebSocket proxying documents reverse-proxy upgrade handling. MDN's Server-Sent Events guide supports the WebSocket-versus-SSE distinction.


Comments (0)