Episode 3 — NodeJS MongoDB Backend Architecture / 3.15 — Realtime Communication WebSockets
3.15 — Exercise Questions: Realtime Communication & WebSockets
35+ hands-on exercises covering WebSocket fundamentals, Socket.io setup, rooms, namespaces, and middleware.
Section A: WebSocket Fundamentals (Questions 1-8)
Q1. Explain in your own words the difference between half-duplex and full-duplex communication. Give a real-world analogy for each.
Q2. Draw the WebSocket handshake sequence. What HTTP status code does the server respond with? What headers must be present in the client's request and the server's response?
Q3. A colleague suggests using WebSocket for a blog's comment section where users post comments every few minutes. Do you agree? Justify your answer with at least 3 reasons.
Q4. What is the difference between ws:// and wss://? Why should you never use ws:// in production? What specific attacks does wss:// prevent?
Q5. List the WebSocket close codes for: normal closure, going away, protocol error, and abnormal closure. When would each occur in practice?
Q6. Write the native browser WebSocket code (without Socket.io) to:
- Connect to
wss://api.example.com/ws - Log when the connection opens
- Parse incoming JSON messages
- Send a JSON message
{ type: "ping" } - Handle errors and disconnection
- Implement manual reconnection with exponential backoff
Q7. Create a comparison table with at least 6 criteria comparing HTTP/2 Server Push, SSE, and WebSocket. Include a "best for" row.
Q8. Your WebSocket server works locally but fails in production behind an Nginx reverse proxy. What Nginx configuration directives do you need to add? Write the configuration block.
Section B: Polling and Alternatives (Questions 9-14)
Q9. Implement a short polling system where the client polls /api/notifications every 5 seconds and only displays new notifications (based on a since timestamp). Write both client and server code.
Q10. Convert the short polling solution from Q9 into a long polling solution. What changes are needed on the server? What timeout value would you use and why?
Q11. Implement a Server-Sent Events (SSE) endpoint that sends a random stock price update every 2 seconds. Include the proper headers and data format. Write the client code using EventSource.
Q12. Calculate the bandwidth usage for the following scenario: 1000 users need updates every second. Compare the bytes transferred per minute for:
- Short polling (assume 800 bytes per HTTP request/response including headers)
- Long polling (assume 800 bytes per exchange, average 1 new update per second)
- WebSocket (assume 10 bytes per frame after connection established)
Q13. Explain why Socket.io is NOT interoperable with raw WebSocket servers. What protocol layer does Socket.io add on top of WebSocket?
Q14. You are building a dashboard that shows server CPU and memory usage. The data updates every 10 seconds. Which real-time approach (short polling, long polling, SSE, or WebSocket) would you choose? Write a brief justification.
Section C: Socket.io Setup and Basics (Questions 15-22)
Q15. Set up a basic Socket.io server with Express from scratch. Your server should:
- Serve static files from a
publicdirectory - Have a REST endpoint
GET /api/statusthat returns{ status: 'online' } - Log when users connect and disconnect (including the socket ID)
- Configure CORS for
http://localhost:5173
Q16. What is wrong with this code? Identify and fix the bug:
const express = require('express');
const { Server } = require('socket.io');
const app = express();
const io = new Server(app);
app.listen(3000, () => {
console.log('Server running');
});
Q17. Build a "live user count" feature. Display the current number of connected users and update it in real-time for all clients when someone connects or disconnects.
Q18. Implement acknowledgements (callbacks) for a "save-task" event. The client sends { title, description }, the server validates the data and responds with either { status: 'ok', taskId } or { status: 'error', message }.
Q19. Write a typing indicator feature where:
- Client emits
typingwhen the user types - Client emits
stop-typingafter 2 seconds of inactivity - Server broadcasts the typing status to other users
- Multiple users can be typing simultaneously (show "Alice, Bob are typing...")
Q20. Explain the difference between these three emission methods:
socket.emit('event', data);
io.emit('event', data);
socket.broadcast.emit('event', data);
For each, state who receives the event (sender, all clients, all except sender).
Q21. Write a React component that connects to a Socket.io server, handles connection/disconnection states, and properly cleans up listeners on unmount. Handle the React Strict Mode double-mount issue.
Q22. Build a "live reactions" feature for a presentation app. When a user clicks a reaction button (thumbs-up, heart, clapping), all other users see the reaction appear briefly on their screen with a floating animation effect.
Section D: Rooms and Namespaces (Questions 23-30)
Q23. Implement a private messaging system where:
- Each user joins a personal room
user:<userId> - A user can send a direct message to another user by their userId
- The sender also sees their own message in their chat window
- Handle the case where the recipient is offline
Q24. Build a "game lobby" system:
- Users can create a game room (max 4 players)
- Users can list available rooms and see player count
- Users can join a room (if not full)
- When all 4 players join, emit a
game-startevent to that room only - When a player disconnects, notify remaining players
Q25. Write code to get the number of connected users in a specific room. Then write code to get a list of all rooms on the server (excluding personal rooms named after socket IDs).
Q26. Explain the difference between namespaces and rooms using a real-world building analogy. When would you create a new namespace vs. a new room?
Q27. Design a namespace architecture for an e-commerce platform with:
- Customer-facing real-time features (order tracking, support chat)
- Seller dashboard (inventory updates, new order alerts)
- Admin panel (system monitoring, user management) Write the server-side setup code.
Q28. Implement dynamic rooms where:
- When a user opens a product page, they join
product:<productId> - They see how many other users are viewing the same product ("5 people viewing this")
- When stock changes, all viewers get a real-time update
- When the user navigates away, they automatically leave the room
Q29. A socket is in rooms ["general", "tech", "user:abc123"]. Write code to:
- Send a message only to "general"
- Send a message to "general" and "tech" but not "user:abc123"
- Send to all rooms the socket is in, except the socket itself
- Remove the socket from all custom rooms (but not its personal room)
Q30. What happens when you emit to a room that doesn't exist? What happens to a room when the last member leaves? Write code to verify your answers.
Section E: Middleware and Advanced (Questions 31-38)
Q31. Write a complete authentication middleware that:
- Extracts JWT from
socket.handshake.auth.token - Verifies the token and handles expired/invalid tokens differently
- Fetches user data from a mock database
- Attaches the user object to
socket.user - Sends descriptive error messages back to the client
Q32. Write a logging middleware that records:
- Connection timestamp
- Client IP address
- User agent
- Auth status (authenticated or anonymous)
- Disconnection reason and connection duration
Q33. Implement connection-level rate limiting:
- Maximum 5 connections per IP address
- Track connection counts and clean up on disconnect
- Return a meaningful error when the limit is exceeded
Q34. Implement event-level rate limiting:
- Maximum 30 messages per minute per user
- When rate limited, respond with how many seconds until they can send again
- Use a sliding window approach
Q35. Write per-namespace middleware:
/public— no authentication required/chat— requires valid JWT/admin— requires valid JWT ANDrole: 'admin'/support— requires valid JWT AND eitherrole: 'admin'ORrole: 'support'
Q36. Build a complete "real-time collaborative document" system:
- Users join a document room when they open a document
- Show who else is editing (with cursor positions)
- Broadcast text changes to all editors
- Handle conflicts when two users edit the same line
- Clean up when users leave
Q37. You discover that your Socket.io server occasionally crashes with "Max listeners exceeded" warnings. What is causing this? How do you diagnose and fix it?
Q38. Design an error-handling strategy for Socket.io that:
- Catches errors in all event handlers
- Logs errors with context (userId, event name, payload)
- Sends user-friendly error messages back to the client
- Does not crash the server on unhandled errors
Write a wrapper utility function similar to Express's
asyncHandler.