WebSockets & Server-Sent Events interview questions

32 questions from the WebSockets & Server-Sent Events course, each with the correct answer and an explanation. Try to answer before you open the answer.

Real-time on the Web: the Mental Model

1. Why can a plain HTTP/1.1 server not send a new chat message to a browser on its own?

  1. Because HTTP responses cannot contain JSON
  2. Because the server can only respond to a request the client has already sent
  3. Because browsers block all incoming TCP packets
  4. Because HTTP/1.1 has no Content-Type header
Show answer

Answer: Because the server can only respond to a request the client has already sent

HTTP is request/response: the server can only answer an open request. Push techniques work by keeping a request or connection open so the server has something to write into.

Lesson: Why Plain HTTP Is Not Enough

2. Compared with short polling every 5 seconds, what does long polling mainly improve?

  1. It encrypts the messages
  2. It removes the need for a server
  3. It lets the browser send binary frames
  4. It reduces latency and the number of empty responses
Show answer

Answer: It reduces latency and the number of empty responses

The server holds the request until there is news, so updates arrive almost immediately and empty responses only happen on timeouts.

Lesson: Short Polling and Long Polling

3. An app streams an LLM's answer to the browser; the user only sends a prompt once per turn. Which transport fits best?

  1. Server-Sent Events (or a streamed fetch response)
  2. A WebSocket with a custom binary protocol
  3. Short polling every 100 ms
  4. WebTransport datagrams
Show answer

Answer: Server-Sent Events (or a streamed fetch response)

Data flows one way, server to client, after a single request. A streamed HTTP response with SSE framing is simpler and is what most LLM APIs use.

Lesson: Choosing a Transport

Server-Sent Events Foundations

4. A server writes `data: hi\n` and then waits. Why does the browser's handler not run yet?

  1. SSE only supports JSON payloads
  2. The browser needs an `event:` line first
  3. The event is not dispatched until a blank line ends it
  4. `data:` must be followed by two spaces
Show answer

Answer: The event is not dispatched until a blank line ends it

A blank line terminates and dispatches an event. Until then the browser keeps buffering data lines.

Lesson: The text/event-stream Format

5. The server sends `event: status` events, but `source.onmessage` never fires. What is the fix?

  1. Add `source.addEventListener('status', handler)`
  2. Send the events as binary
  3. Set `readyState` to 1 manually
  4. Use `withCredentials: false`
Show answer

Answer: Add `source.addEventListener('status', handler)`

`onmessage` only receives events with no `event:` field (type `message`). Named events need a listener registered under that name.

Lesson: The EventSource API in the Browser

6. A Node.js SSE handler starts a `setInterval` per client. What must happen when `req` emits `close`?

  1. Nothing, Node.js stops timers automatically
  2. Send a `retry: 0` field
  3. Call `res.writeHead(204)`
  4. Clear the interval and release anything else started for that client
Show answer

Answer: Clear the interval and release anything else started for that client

The server only learns about the disconnect through the close event. Timers and subscriptions keep running unless the handler stops them, which leaks memory and CPU.

Lesson: Writing an SSE Endpoint

SSE in Production

7. Why are random UUIDs a poor choice for SSE event ids when you need resumption?

  1. They are too long for the `id:` field
  2. The server cannot tell which events came after a given UUID without extra ordering data
  3. Browsers reject ids containing hyphens
  4. UUIDs disable automatic reconnection
Show answer

Answer: The server cannot tell which events came after a given UUID without extra ordering data

Resumption means "send everything after X". That needs an ordering; a UUID alone does not say what came before or after it.

Lesson: Reconnection and Last-Event-ID

8. A user opens the dashboard in eight tabs over HTTP/1.1 and later tabs stop loading. What is the likely cause?

  1. The per-origin connection limit is used up by open EventSource streams
  2. SSE only allows one listener per user
  3. The server ran out of event ids
  4. HTTP/1.1 does not support text/event-stream
Show answer

Answer: The per-origin connection limit is used up by open EventSource streams

Browsers cap HTTP/1.1 connections per origin at around six. Each EventSource holds one, so extra tabs queue. HTTP/2 or one shared stream fixes it.

Lesson: Proxies, Buffering and Connection Limits

9. Why do LLM chat clients usually read streams with fetch instead of EventSource?

  1. fetch is the only API that supports UTF-8
  2. EventSource cannot parse JSON
  3. They need a POST body and custom headers such as Authorization
  4. EventSource cannot stream more than 100 events
Show answer

Answer: They need a POST body and custom headers such as Authorization

EventSource is GET-only and cannot set custom headers. fetch can send a POST with an API key and still read the response as a stream.

Lesson: Streaming with fetch: LLM-style Responses

The WebSocket Protocol

10. Which HTTP status code does a server return to accept a WebSocket upgrade?

  1. 200 OK
  2. 204 No Content
  3. 302 Found
  4. 101 Switching Protocols
Show answer

Answer: 101 Switching Protocols

101 tells the client the connection is switching from HTTP to the protocol named in the Upgrade header.

Lesson: The Opening Handshake

11. Which statement about masking is correct?

  1. Server-to-client frames must be masked
  2. Masking encrypts the payload so `ws://` is safe
  3. Client-to-server frames must be masked with a 4-byte key
  4. Masking is optional and off by default in browsers
Show answer

Answer: Client-to-server frames must be masked with a 4-byte key

RFC 6455 requires clients to mask every frame they send and servers not to mask theirs. It protects intermediaries, not confidentiality.

Lesson: Frames, Opcodes and Masking

12. Your client logs close code 1006. What does that mean?

  1. The server sent a close frame with code 1006
  2. The connection ended without a close frame being received
  3. The message was too large
  4. The server is going away for a restart
Show answer

Answer: The connection ended without a close frame being received

1006 is reserved for local use: the connection closed abnormally, without the closing handshake. It is never sent in a close frame.

Lesson: Control Frames and the Closing Handshake

WebSocket Clients and Servers

13. What does `console.log(ws.readyState)` print on the line straight after `new WebSocket(url)`?

  1. 0, because the handshake has only started
  2. 1, because the constructor waits for the handshake
  3. 3, because no server has answered
  4. It throws until the socket opens
Show answer

Answer: 0, because the handshake has only started

The constructor is non-blocking. The socket stays CONNECTING (0) until the 101 response is processed by the event loop.

Lesson: The Browser WebSocket API

14. In ws, why does the message handler often call `data.toString()`?

  1. Because ws only supports binary frames
  2. Because messages arrive as Buffer objects, even for text frames
  3. To decompress the payload
  4. To unmask the frame
Show answer

Answer: Because messages arrive as Buffer objects, even for text frames

ws delivers payloads as Buffers and passes an `isBinary` flag. Text must be decoded, for example with `toString()` or a template literal.

Lesson: A WebSocket Server in Node.js with ws

15. Inside an asyncio WebSocket handler, a developer calls `time.sleep(2)`. What happens?

  1. Only that client waits 2 seconds
  2. The library automatically moves it to a thread
  3. Every connection served by that event loop is frozen for 2 seconds
  4. The connection is closed with code 1011
Show answer

Answer: Every connection served by that event loop is frozen for 2 seconds

`time.sleep` blocks the single event loop thread, so no other coroutine can run. Use `await asyncio.sleep(2)` instead.

Lesson: WebSockets in Python with asyncio

Designing Real-time Features

16. Why does a request sent over a WebSocket usually carry an `id` field?

  1. The WebSocket protocol rejects messages without ids
  2. Browsers use it to order frames
  3. It is required for masking
  4. So the client can match the server's reply to the request that caused it
Show answer

Answer: So the client can match the server's reply to the request that caused it

Messages on a socket are not paired like HTTP request/response. An id echoed back as `replyTo` lets the client resolve the correct pending request.

Lesson: Designing Your Message Protocol

17. In the in-memory rooms design, what goes wrong if `close` does not remove the socket from its rooms?

  1. Dead sockets accumulate, leaking memory and slowing broadcasts
  2. The client cannot reconnect
  3. The room is automatically deleted
  4. Messages are delivered twice to every client
Show answer

Answer: Dead sockets accumulate, leaking memory and slowing broadcasts

The Set keeps references to closed sockets. Memory grows and every broadcast iterates over clients that can never receive anything.

Lesson: Rooms and Broadcasting

18. Why does the heartbeat code call `ws.terminate()` instead of `ws.close()` on a dead socket?

  1. `close()` is not available on server sockets
  2. `terminate()` sends a nicer close code
  3. The peer is gone, so a close handshake would never complete; terminate destroys the socket immediately
  4. `terminate()` lets the client reconnect faster
Show answer

Answer: The peer is gone, so a close handshake would never complete; terminate destroys the socket immediately

`close()` starts a handshake and waits for the peer's close frame. A vanished peer will never reply, so the socket would linger. `terminate()` frees it at once.

Lesson: Heartbeats and Dead Connections

19. What is the main purpose of adding random jitter to reconnect delays?

  1. To make messages arrive in random order
  2. To spread reconnects out so clients do not all hit a restarted server at once
  3. To encrypt the reconnect request
  4. To make the first retry slower than the last
Show answer

Answer: To spread reconnects out so clients do not all hit a restarted server at once

Without jitter, clients that disconnected together retry together. Randomising each delay smooths the load into a gentle ramp.

Lesson: Reconnecting with Backoff and Resume

Scaling Real-time Systems

20. You add a fourth server behind the load balancer of a busy WebSocket app. Why does it receive almost no traffic at first?

  1. Load balancers cannot route WebSockets to new servers
  2. WebSockets require sticky sessions to be reset manually
  3. The new server must be restarted first
  4. Existing connections stay on their servers; only new or reconnecting clients reach the new one
Show answer

Answer: Existing connections stay on their servers; only new or reconnecting clients reach the new one

Balancing happens at connect time. Long-lived connections do not migrate, so new capacity fills only as clients reconnect.

Lesson: Long-lived Connections and Load Balancers

21. Why is Redis pub/sub alone not enough to guarantee clients receive every chat message?

  1. It is fire-and-forget: subscribers that are disconnected at publish time miss the message
  2. It only supports one channel per server
  3. It cannot carry JSON
  4. It requires sticky sessions
Show answer

Answer: It is fire-and-forget: subscribers that are disconnected at publish time miss the message

Pub/sub has no persistence or replay. Durable storage or a log-based system such as Redis Streams or Kafka is needed for guaranteed delivery.

Lesson: Fan-out Across Servers with Pub/Sub

22. A live cricket page sends ball-by-ball commentary and a rapidly changing win-probability number. Which policy fits the win-probability updates for slow clients?

  1. Queue every update forever
  2. Coalesce and send only the latest value periodically
  3. Disconnect the client after every update
  4. Switch the client to short polling permanently
Show answer

Answer: Coalesce and send only the latest value periodically

Only the newest probability matters, so older values can be dropped or merged. Commentary, by contrast, should be delivered completely.

Lesson: Backpressure and Slow Consumers

23. Which close code should a server send to clients when it is shutting down for a deploy?

  1. 1000 Normal Closure, so clients stop for good
  2. 1006 Abnormal Closure
  3. 1001 Going Away
  4. 1009 Message Too Big
Show answer

Answer: 1001 Going Away

1001 means the endpoint is going away, such as a server restart. 1006 can never be sent in a frame, and many clients treat 1000 as "do not reconnect".

Lesson: Deploys, Restarts and Graceful Shutdown

Security for Real-time Endpoints

24. Why do many apps use a short-lived, single-use ticket in the WebSocket URL instead of the user's long-lived access token?

  1. Browsers block query strings on wss:// URLs
  2. URLs are often logged, so a leaked ticket must expire quickly and be useless after first use
  3. Tickets make frames smaller
  4. The handshake rejects tokens longer than 64 bytes
Show answer

Answer: URLs are often logged, so a leaked ticket must expire quickly and be useless after first use

Query strings show up in proxy and server logs. A ticket that is single-use and expires in seconds limits the damage if it leaks.

Lesson: Authenticating WebSocket Connections

25. Your WebSocket server authenticates with session cookies and has no Origin check. What can a malicious website do?

  1. Nothing, because the same-origin policy blocks cross-site WebSockets
  2. Only read your server's TLS certificate
  3. Open a WebSocket to your server with the victim's cookies and act as the victim
  4. Change the victim's cookies to its own domain
Show answer

Answer: Open a WebSocket to your server with the victim's cookies and act as the victim

Cross-origin WebSocket connections are allowed and carry cookies. Without an Origin check, the attacker's page gets an authenticated two-way channel: CSWSH.

Lesson: Origin Checks and Cross-Site WebSocket Hijacking

26. Which ws option protects the server from a client sending a single 200 MB message?

  1. `perMessageDeflate: true`
  2. `maxPayload` set to a sensible limit
  3. `clientTracking: false`
  4. `noServer: true`
Show answer

Answer: `maxPayload` set to a sensible limit

`maxPayload` caps the size of an incoming message; larger ones close the connection with 1009 instead of being buffered.

Lesson: Validation, Size Limits and Rate Limits

Libraries, Debugging and Testing

27. Why does `new WebSocket('wss://api.example.in/socket.io/')` fail to work with a Socket.IO server?

  1. Socket.IO servers only accept HTTP/2
  2. Browsers block Socket.IO paths
  3. Socket.IO requires binary frames only
  4. Socket.IO uses its own packet protocol and handshake on top of the transport
Show answer

Answer: Socket.IO uses its own packet protocol and handshake on top of the transport

Socket.IO frames its messages in its own format and expects its own connection handshake. Use the official client or a compatible implementation.

Lesson: Socket.IO and Higher-level Libraries

28. Where in Chrome DevTools do you see the individual messages of an open WebSocket?

  1. Network panel, filter to WebSocket traffic, select the connection, Messages tab
  2. Application panel, Cookies section
  3. Console panel, by typing `ws.messages`
  4. Sources panel, under Event Listener Breakpoints only
Show answer

Answer: Network panel, filter to WebSocket traffic, select the connection, Messages tab

The Network panel lists the WebSocket request; its Messages tab shows each frame sent and received with timestamps.

Lesson: Debugging with DevTools, curl and websocat

29. Why do WebSocket tests often create the server with `port: 0`?

  1. Port 0 disables TLS for tests
  2. Port 0 makes the server reject real clients
  3. The OS assigns a free port, so parallel tests do not clash
  4. Port 0 enables automatic reconnection
Show answer

Answer: The OS assigns a free port, so parallel tests do not clash

Binding to port 0 asks the operating system for any free port; the test reads the real port from `address().port`.

Lesson: Testing Real-time Code

Revision and Interview Prep

30. Which pair is correctly matched?

  1. Opcode 0x9: pong
  2. Close code 1006: sent by the server during deploys
  3. `Last-Event-ID`: header sent by a reconnecting EventSource
  4. `Sec-WebSocket-Accept`: encrypts the session key
Show answer

Answer: `Last-Event-ID`: header sent by a reconnecting EventSource

EventSource sends `Last-Event-ID` when it reconnects. 0x9 is ping (0xA is pong), 1006 is never sent on the wire, and the accept header is a handshake check, not encryption.

Lesson: Cheat Sheet

31. In a multi-server chat design, why should a message be written to the database before it is published to Redis pub/sub?

  1. Redis pub/sub can only publish ids that exist in a database
  2. So that clients who are offline or reconnecting can still fetch the message later
  3. Because publishing is slower than writing
  4. To avoid needing a WebSocket at all
Show answer

Answer: So that clients who are offline or reconnecting can still fetch the message later

Pub/sub only reaches currently connected subscribers. Persisting first means the message survives disconnects and can be replayed or fetched.

Lesson: Common Interview and Exam Questions

32. A trading dashboard pushes 40 price updates per second. Memory on the server climbs whenever users on weak mobile networks connect. What is the best first fix?

  1. Switch every client to long polling
  2. Increase the server's RAM
  3. Turn on perMessageDeflate for all sockets
  4. Check `bufferedAmount` and coalesce updates, sending only the latest prices periodically
Show answer

Answer: Check `bufferedAmount` and coalesce updates, sending only the latest prices periodically

This is backpressure from slow consumers. Coalescing latest-value data and skipping sends to sockets with large buffers bounds memory; more RAM only delays the problem.

Lesson: Mixed Self-check

← Back to the course