Designing with WebSockets
Much of this chapter shows how WebSockets work: the handshake, frames, the sets of connections for each room, closing, pings, and running on several instances. The WebSocket library and the browser do most of that work. As the designer, your job is the decisions.
Whether a feature needs a WebSocket
If a change can show up a minute late, polling is enough. If a change must show up within seconds, but changes are rare and only the server sends them, long polling is enough. A WebSocket pays off when changes are frequent and must show up at once, or when both sides send often.
What goes over the WebSocket
Not everything has to move to the WebSocket. In Courselore, posting stays on the REST API, because it needs a response: a confirmation, an error, and a safe retry. Reading a room’s existing messages also stays on the REST API. New messages and typing events go over the WebSocket.
What a WebSocket design must account for
Choosing WebSockets raises questions that polling never did:
- Does it fit on our servers? Count the open connections and check whether the servers can hold them. Courselore’s 1,200 fit on one server.
- If not, what does the architecture add? Several instances need a channel between them, a new part of the system.
- What happens to messages when a connection drops? A WebSocket can lose them, so something else must hold every message. In Courselore, that is the database, read through the REST API.
- How does a permission change reach an open connection? The server checks permissions only when a connection opens. So removing a member must also update that member’s open connections.