Blogs

Realtime collaboration series · Part 1 of 5

Changes take seconds to show up

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?”.

Screens · animated
Alice’s screenBob’s screenTitle: DraftPlansaved ✓Title: DraftPlannext check in 3 s…next check in 2 s…next check in 1 s…checking…updated, 4 seconds lateAlice renames the boardBob’s app only asks for news every few secondsBob finally sees it, seconds late
Polling makes every change late by up to one interval. Shorter intervals help, but never remove the wait.

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.

Compare · animated
Polling: “anything new?”Push: one open connectionBrowserServerBrowserServernew?nonew?nonew?yes: Plannew?nochange!most answers are “no”, and newswaits for the next questionopen connectionchange!Plannothing is sent until somethinghappens, then it arrives at once
Same change, two models. Polling learns about it on the next question; push delivers it the moment it happens.
Key ideaPush instead of ask. Realtime starts when the server can speak first. Everything else in this series is built on that open line.

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.

Map · animated
AliceBobChiserverroom “board-42”Alice · Bob · Chiroom “board-7”Dan · EveDanEvehear nothingeditokediteditAlice sends an edit to her board’s roomThe room sends it to everyone else in it
A room is just the set of connections for one document. Other rooms are not disturbed.

When one server is not enough

With several servers, Alice and Bob may land on different machines, and the room splits in two:

Problem · animated
AliceBobserver 1server 2room board-42: Aliceroom board-42: Bobedit✕server 1 doesn’t know Bob exists
Each server only knows its own sockets. The edit stops at server 1.

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.

Test · animated
Alice’s screenBob’s screenserver 1server 2pub/sub channelpasses messages onblueorangeblueorangeorangeblueeach server: “latest I heard wins”✕ screens disagree
Each server hears the edits in a different order, so the screens disagree.

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.

Test · animated
Alice’s screenBob’s screenserver 1server 2Redis Stream board:42decides: XADD gives #1, #2blueorangeblueorangeorder: #1 blue → #2 orange#1 blue, #2 orange#1 blue, #2 orangeorangeorange✓ both see orange
Redis numbers the edits #1, #2. Every server applies them in that 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.

Architecture · animated
Aliceboard 42Bobboard 42Chiboard 77load balancer · sends each browser to any gatewaygateway 1holds sockets: Alice, Chigateway 2holds sockets: Bob▲ connection layer · statelessdirectoryboard 42 → worker Aboard 77 → worker B▼ board layer · one worker per boardworker Aboards 42 and 13, kept in memoryworker Bboard 77 in memorydatabase · saved copy of every board#57 appliededit: bluewho runs 42?worker Aedit: bluesave#57 blue#57 blue#57#57Chi: other board,gets nothing1 · Alice’s edit reaches whichever gateway holds her socket2 · The gateway asks the directory: who runs board 42?3 · It forwards the edit to worker A4 · Worker A applies it to board 42 in memory (#57) and saves it5 · Worker A sends the result to every gateway with board-42 users6 · Gateways push it to Alice and Bob
Two layers. The top layer only moves messages, so any gateway can serve anyone. The bottom layer owns the boards, so each board has exactly one place where its edits are ordered.

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.

Test · animated
Alice’s screenBob’s screengateway 1gateway 2board-42 workerdecides: applies in arrival orderblueorangeblueorangeorder: #1 blue → #2 orangeorangeorangeorangeorange✓ both see orange
The worker applies both edits in arrival order and sends the result back.

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.

Test · animated
Alice’s screenBob’s screenserver 1server 2owns board-42: decides“not mine, go to server 2”blueorangeorder: #1 blue → #2 orangeorangeorange✓ both see orange
Both edits reach one machine, which applies them in arrival order.

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).

Setup · animated
AliceBobload balancerhash(board id) picks the serverserver 1server 2server 3?board=4242 → server 2Alice?board=42Bobsame board → same server, every timeAlice connects with ?board=42Bob connects with the same board idThe hash sends both to server 2
No server code needed. But when a server is added or removed, some boards move to a new server and their users must reconnect.

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).

Setup · animated
AliceBobload balancer · any serverserver 1server 2Redis lockboard 42 → nobodyboard 42 → server 2 (expires in 30 s)open board 42claim 42OK, yoursopen board 42claim 42taken: server 2go to server 2AliceAlice + Bobrenew1 · Bob opens board 42 and lands on server 22 · Server 2 claims board 42 in Redis3 · Alice opens board 42 and lands on server 14 · Server 1 tries to claim it: already taken by server 25 · Server 1 tells Alice: go to server 26 · Alice reconnects to server 2: the room is whole7 · Server 2 keeps renewing; if it dies, the lock expires
The first server to see a board owns it. Others redirect. Because the lock expires unless renewed, a crashed owner frees its boards within seconds.

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 decidesConnect toPick it when
A · Relaynobodyany serverorder doesn’t matter
B · Shared logRedisany serveryou want stateless servers
C · Gateway + workera worker per boardany gatewayyou need board rules and room to grow
D · One ownerthe owner serverthe owner onlyyou want the simplest setup
Key ideaPick who decides the order first. The rest of the architecture follows. CRDTs (part 3) remove the need for a decider entirely.

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.

server.ts
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

OptionHow it worksGood for
PollingAsk every N secondsDashboards that can be a little stale; very simple setups
Long pollingAsk, and the server holds the request open until there is newsPush-like behaviour where WebSockets are blocked
Server-Sent EventsOne-way stream from server to browser over HTTP, with automatic reconnectFeeds, notifications, streaming AI answers. Sends from the browser still need normal requests
WebSocketOne open two-way connectionCollaborative editing, chat, live cursors
WebRTC data channelBrowser-to-browser connection, after a server introduces themLow-latency peer-to-peer games and calls; harder to keep one source of truth

7Conclusion

Key ideaRealtime starts with a line that stays open, and a room that decides who hears what. Use polling or Server-Sent Events when only the server talks or delay is fine. Use WebSockets and rooms when people edit together.

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.