Realtime collaboration series · Part 1 of 5
Changes take seconds to show up
- Overview
- 1. Changes take seconds to show up
- 2. Edits get lost, doubled or out of order
- 3. Two people change the same thing
- 4. You can’t tell who else is here
- 5. Cursors lag behind while you pan
You rename a board. Your teammate, on the same board, still sees the old name until they refresh, or until their app gets around to asking again. In a live meeting, those few seconds are enough to talk past each other.
1The problem: the browser has to ask
On the web, the browser normally starts every conversation. The server cannot tell Bob about Alice’s change; it has to wait for Bob’s app to ask. So collaborative apps without a live connection poll: every few seconds they ask “anything new?”.
Polling has two costs that pull against each other. A long interval makes changes late. A short interval floods the server with questions whose answer is almost always “no”: 1,000 open boards polling every second is 1,000 requests a second, even when nobody is typing.
2The solution: keep a line open and push
A WebSocket starts as a normal HTTP request, then “upgrades” into a connection that stays open in both directions. Once it is open, the server can send whenever something happens, and the browser can send without the cost of a new request each time.
Rooms: who should hear about a change?
An open line per user is not enough on its own. When Alice edits board 42, only the people looking at board 42 should hear about it. So the server groups connections into a room per document. A change goes to the room: the sender gets a short confirmation, everyone else gets the change.
When one server is not enough
With several servers, Alice and Bob may land on different machines, and the room splits in two:
One test for every fix: at the same moment, Alice makes a card blue and Bob makes it orange. Do both screens end the same? It depends on who decides which edit came first.
A · Relay: nobody decides
Servers forward edits to each other through pub/sub.
Good for chat and cursors, because nothing collides there. Two chat messages both appear, and a newer cursor position replaces the older one anyway, so the order doesn’t matter.
Not enough for edits, because two edits to the same card do collide. Each server applies them in the order it happened to hear them, so screens end up different, and nothing ever fixes it.
B · Shared log: Redis decides
Servers append edits to one log per board (a Redis Stream) and read it back in order.
Good: any server can take any user, and a crashed server loses nothing, because the order and the history live in Redis. Catching up after a reconnect is just “read the log from where I left off”.
Cost: every edit makes an extra trip to Redis before anyone sees it. And checking a rule like “this card was deleted, reject the move” needs the card’s current state. A read-through cache fixes the loading part: look up only that card, and read it from the database if it’s missing. The catch is timing: another server may delete the card between your check and your append, so the check and the append must happen as one step, for example in a single Redis script. Rules that span many cards, like “don’t put a group inside itself”, still need more of the board.
C · Gateway + worker: your worker decides
A realtime server really does two jobs: it holds connections to browsers, and it runs the board (keeps it in memory and applies edits one at a time). Option C splits those jobs into two kinds of servers:
- Gateways only hold connections. Any user can use any gateway, and a gateway knows nothing about boards.
- Workers only run boards. A worker is an ordinary server process that owns some boards, say 42 and 77. It never talks to a browser. A small lookup table says which worker owns which board.
Think of a restaurant: any waiter takes your order, but every pizza goes to the one pizza chef. When Alice edits board 42, her gateway asks “who runs board 42?”, forwards the edit to that worker, and sends the result back.
If worker A crashes, the directory hands board 42 to worker B, which loads it from the database. Gateways keep their connections, so users only see a short pause. If a gateway crashes, its users reconnect to another gateway, and no board moves.
Good: users can connect to any gateway, and adding gateways never moves a board. The worker keeps the whole board in memory, so it can check rules instantly before accepting an edit.
Cost: you build and run a second kind of service, plus a router that knows which worker has which board and moves the board when a worker dies.
D · One owner: the server you’re on decides
Everyone on a board is sent to the same server.
How do you send everyone on a board to the same server? Normal “sticky sessions” don’t help: they keep one user on one server with a cookie, but Alice and Bob still get different servers. You need to stick by board. There are two common ways.
Way 1 · Route by board id in the load balancer. The browser connects to /ws?board=42, and the load balancer hashes the board id to pick a server (for example nginx hash $arg_board consistent).
Way 2 · Claim the board with a lock. The load balancer sends people anywhere, and the servers sort it out between themselves with a short-lived lock in Redis (SET board:42:owner server-2 NX PX 30000).
Good: no extra hop. The server that receives the edit already holds the board and every socket, so it orders, checks and broadcasts in one place.
Cost: the load balancer must send each user to the board’s owner. Deploys, crashes and one very busy board all need special handling, because a board can’t simply move to another server.
| Who decides | Connect to | Pick it when | |
|---|---|---|---|
| A · Relay | nobody | any server | order doesn’t matter |
| B · Shared log | Redis | any server | you want stateless servers |
| C · Gateway + worker | a worker per board | any gateway | you need board rules and room to grow |
| D · One owner | the owner server | the owner only | you want the simplest setup |
3Example code
A minimal room server in Node.js with the ws package, and the browser side. It leaves out authentication, reconnecting and ordering, which the next article adds.
import { WebSocketServer, WebSocket } from 'ws'
// One room per board: every socket that has the board open.
const rooms = new Map<string, Set<WebSocket>>()
const wss = new WebSocketServer({ port: 8080 })
wss.on('connection', (socket, req) => {
// ws://host:8080/?board=42 → join room "42"
const boardId = new URL(req.url!, 'http://x').searchParams.get('board')
if (!boardId) return socket.close(4000, 'board required')
// (A real server checks the user's token and board access here.)
const room = rooms.get(boardId) ?? new Set<WebSocket>()
rooms.set(boardId, room)
room.add(socket)
socket.on('message', (raw) => {
const edit = JSON.parse(raw.toString())
// ...validate and save the edit here...
// 1. confirm to the sender
socket.send(JSON.stringify({ type: 'ok', id: edit.id }))
// 2. fan out to everyone else in the room
for (const peer of room) {
if (peer !== socket && peer.readyState === WebSocket.OPEN) {
peer.send(JSON.stringify({ type: 'edit', edit }))
}
}
})
socket.on('close', () => {
room.delete(socket)
if (room.size === 0) rooms.delete(boardId) // free empty rooms
})
})
client.ts
const socket = new WebSocket(`wss://example.com/?board=${boardId}`)
socket.onmessage = (event) => {
const msg = JSON.parse(event.data)
if (msg.type === 'edit') applyRemoteEdit(msg.edit) // someone else's change
if (msg.type === 'ok') markSaved(msg.id) // our change is stored
}
function sendEdit(edit: { id: string; changes: object }) {
applyLocally(edit) // show it right away
socket.send(JSON.stringify(edit)) // and tell the room
}
Note the two kinds of reply: ok back to the sender, edit to everyone else. The sender already shows its own change, so it only needs to know the change was stored.
4In practice: a design tool
In a collaborative design tool, each open board holds one WebSocket, and each board is a room. A few details matter once real users arrive:
- Check access during the handshake. The token is verified and board permission checked before the connection is accepted, so no message handler has to ask “is this person allowed here?”.
- Choose where order lives early. Any of the four shapes above works for a design tool. Moving from one to another later touches deployment, reconnect logic and conflict handling, so it is worth deciding before the first real users arrive.
- Rooms can be filtered. People presenting a board and people editing it can share a room but get different messages.
- Keep the socket for small messages. Big payloads, such as a generated screen, go over normal HTTP. A large message on the socket delays every cursor and edit queued behind it.
5Pros and cons
Pros
- Changes arrive in tens of milliseconds, not seconds
- No wasted “anything new?” requests
- One connection carries edits, cursors and notifications
- Supported in every modern browser
Cons
- Servers must hold an open connection per user, all day
- Load balancers, proxies and timeouts need WebSocket-aware setup
- Connections drop silently; you must detect and reconnect (article 2)
- Rooms live in memory, so scaling needs a relay or an owner per room
6Alternatives
| Option | How it works | Good for |
|---|---|---|
| Polling | Ask every N seconds | Dashboards that can be a little stale; very simple setups |
| Long polling | Ask, and the server holds the request open until there is news | Push-like behaviour where WebSockets are blocked |
| Server-Sent Events | One-way stream from server to browser over HTTP, with automatic reconnect | Feeds, notifications, streaming AI answers. Sends from the browser still need normal requests |
| WebSocket | One open two-way connection | Collaborative editing, chat, live cursors |
| WebRTC data channel | Browser-to-browser connection, after a server introduces them | Low-latency peer-to-peer games and calls; harder to keep one source of truth |
7Conclusion
Next: an open line still drops, reorders and repeats messages when the network wobbles. Part 2 is about making every edit arrive exactly once, in order.