Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Socket.IO Practice and Interview Questions

Practice Socket.IO with hands-on exercises (presence, retry wrappers, event routing) and review the questions interviewers ask, with concise model answers.

You have covered connections, rooms, middleware, scaling, reliability, integration, testing and deployment. This final lesson is for consolidating it. First come exercises with runnable solutions (plain Node.js stand-ins for the parts that need Socket.IO, since the library is not installed in this site's runner), then a set of interview-style questions with model answers, and finally a list of the mistakes that cause most real-world bugs.

Try each exercise yourself before you open the solution: change the script, break it, make it pass.

Exercise 1: Presence across tabs

Task. A user can open several tabs, so one user means many sockets. Build a presence tracker with connect(userId, socketId), disconnect(socketId) and isOnline(userId). A user is online while at least one socket is connected. Emit online only when the first socket arrives and offline only when the last one leaves.

Hints. Keep a Map from user to a Set of socket ids, and a second map from socket id to user. This is the logic behind a user:<id> room pattern (scaling).

Node.js Solution 1: presence with several sockets per user

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Extension: with several servers this state lives in each process. Store the sets in Redis (with a TTL refreshed by the heartbeat) so a crashed server's users eventually time out.

Exercise 2: A retry wrapper with backoff for acks

Task. Write emitWithRetry(send, { retries, timeoutMs }) that calls send(callback), treats a missing ack within the timeout as a failure and retries with exponential backoff, rejecting after the last attempt. The request carries an id so the server can deduplicate (delivery guarantees).

Node.js Solution 2: retry with timeout and idempotency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the request id stays the same across attempts. That is what lets a server that already processed the first attempt (but whose ack was lost) ignore the second.

Exercise 3: An event router with middleware

Task. Implement socket.use-style per-event middleware: a router where use(fn) registers functions (event, args, next), run in order before the handler. Add a logger and an authorization check that rejects admin:* events for non-admins.

Node.js Solution 3: per-event middleware chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise ideas without solutions

  1. Add a read-receipts feature: when a user views a room, the server tells the others "ana has read up to message 42", but only advances forward.
  2. Implement message editing with versions: ignore an edit that arrives with an older version number.
  3. Write the Redis-free cluster version of the chat from the project, using @socket.io/sticky and the cluster adapter.
  4. Write a load script that opens 1,000 clients and measures the median time from emit to broadcast receipt.
  5. Add connection state recovery and write a test that kills the connection and checks that nothing is missed.

Interview questions with model answers

What is the difference between Socket.IO and WebSocket? WebSocket is a protocol, a persistent two-way connection. Socket.IO is a library with its own protocol on top of WebSocket (and HTTP long-polling as fallback). It adds named events, acknowledgements, rooms and namespaces, automatic reconnection, heartbeat, and broadcasting. A plain WebSocket client cannot talk to a Socket.IO server.

How does the connection start? The client opens with HTTP long-polling, receives a handshake with a session id and the heartbeat settings, then tries to upgrade to WebSocket. If the upgrade works the polling stops. Setting transports: ["websocket"] skips polling.

What are rooms and namespaces? A namespace is a separate communication channel on one connection (/admin) with its own handlers, middleware and rooms. A room is a server-side group of sockets inside a namespace, used for targeted broadcasts. Clients cannot join rooms themselves; the server decides.

How do io.emit, socket.emit, socket.broadcast.emit and io.to(room).emit differ? socket.emit goes to one socket. io.emit goes to all sockets in the namespace. socket.broadcast.emit goes to all except the sender. io.to(room).emit goes to the room, and socket.to(room).emit goes to the room except the sender.

How do you scale Socket.IO to multiple servers? Sticky sessions for the polling handshake (or WebSocket-only clients) plus an adapter (Redis, Postgres, cluster, and others) so broadcasts cross servers. Keep shared state out of process memory. See scaling.

What delivery guarantee does Socket.IO give? In-order on one connection, at most once by default. Acknowledgements let you confirm receipt, retries gives at-least-once (requiring idempotent handlers), and connection state recovery replays missed room broadcasts for short outages.

How do you authenticate a connection? Pass credentials in the handshake auth object (not the URL), verify them in io.use middleware, store the identity in socket.data, reject with an error otherwise, and authorize each action afterwards. Check the Origin header to defend against cross-site hijacking.

What happens to rooms when a client reconnects? It is a new socket with a new id in no rooms, unless connection state recovery restored it. Clients should re-join on connect.

How do you send a message to a specific user across devices and servers? Join every socket to a room user:<id> on connection, then io.to("user:" + id).emit(...). With an adapter that works across servers.

Why can a Socket.IO server stop responding under load? A slow synchronous handler blocks the single thread for all connections (event loop lag), unbounded per-socket memory (listeners, buffers), unbounded broadcasts without throttling, or a file-descriptor limit.

What does the heartbeat do? The server pings every pingInterval; the client must pong within pingTimeout. It detects silently dead connections and keeps proxies from closing idle ones (reconnection).

Mistakes that cause most bugs

  • Creating the socket inside a component, or adding listeners without removing them.
  • app.listen() instead of the HTTP server given to Socket.IO.
  • Missing Upgrade/Connection headers or short timeouts in the proxy.
  • Multiple servers without sticky sessions or without an adapter.
  • Trusting client-supplied identity, room names or payload shapes.
  • Rendering messages with innerHTML.
  • Emitting from a handler to io when socket.broadcast was meant (the sender sees its own message twice).
  • Assuming messages sent during a disconnect arrive later.
  • Storing "online users" in a variable on one server.
  • Using sleeps instead of waiting for events in tests (testing).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user has three tabs open. When should the user be reported offline?

    Presence is per user, not per socket, so track the set of sockets and report offline when it becomes empty.
  2. 2. Why must the retry wrapper reuse the same request id on every attempt?

    If an earlier attempt succeeded but its ack was lost, the server uses the id to skip the repeated work.
  3. 3. Which statement about WebSocket and Socket.IO is correct?

    Socket.IO is not just a WebSocket wrapper. It has its own protocol, so clients and servers must both use it.
  4. 4. Which call reaches every socket in a room except the sender?

    Calling to() on a socket excludes that socket from the broadcast.
  5. 5. What is the most reliable way to deliver a message to all of one user's devices on any server?

    A user room works across devices, and an adapter extends it across servers.

Summary

  • Presence, retry wrappers and event middleware are small patterns you will meet in almost every real app.
  • Be able to explain Socket.IO versus WebSocket, rooms versus namespaces, the four emit shapes, scaling and delivery guarantees.
  • Most production bugs come from lifecycle mistakes (listeners, rooms after reconnect), missing proxy settings, and trusting client input.
  • Keep practicing: build the extension ideas, test them, and deploy one.

Next: Back to the Socket.IO track