Traditional HTTP follows a request-response model. The client sends a request and the server returns a response.
Real-time applications require a different model because the server may need to send information to clients without waiting for another request.
WebSockets provide persistent, bidirectional communication between a client and server.
A WebSocket connection begins with an HTTP upgrade request.
After the connection is established, both sides can send messages independently.
This makes WebSockets useful for:
Socket.io provides abstractions around real-time communication and includes features such as rooms, events, reconnection behavior, and fallbacks.
A server can emit an event to a specific room rather than broadcasting it to every connected client.
Rooms are useful for grouping users.
A chat application can place participants into a room representing a conversation.
When a message arrives, the server can broadcast it only to users belonging to that conversation.
Authentication should happen during connection establishment or before allowing access to protected rooms.
The server should never assume that a connected client is authorized to access arbitrary data.
Authorization must be checked independently.
Networks are unreliable.
Clients can disappear without cleanly closing a connection.
Real-time systems should therefore handle:
For important data, the server should not rely solely on the WebSocket connection. Persistent state should remain in a database or durable message system.
A single WebSocket server is straightforward.
Multiple instances introduce another challenge: clients connected to different instances need to receive the same events.
A shared messaging system such as Redis can be used to distribute events between instances.
Real-time systems therefore require both connection management and reliable state management.