Blogs

Realtime collaboration series · Part 4 of 5

You can’t tell who else is here

A card slides across the board while you are looking at it. You did not touch it. Was it a bug, or a teammate? Without seeing who else is here, a shared document feels haunted.

1The problem: other people are invisible

Parts 1 to 3 made edits arrive quickly, reliably and fairly. But an edit is the result of what someone did. Before it, there was a person looking at that part of the board, moving toward the card, about to drag it. That context is called presence: who is here, where they are looking, and whether they are still around.

Screens · animated
Without presenceWith presenceBob’s screenBob’s screenABAlice?“Did I do that?”Alice is rearranging
The same edit, with and without presence. A visible cursor turns a surprise into something you can follow.

Presence looks like more data of the same kind, but it is different in almost every way:

EditsPresence
How oftenA few per second at mostEvery mouse move: 60+ per second per person
If one is lostMust be resentIgnore it; the next one replaces it
StoredYes, foreverNever; it means nothing after you leave
OrderEvery one, in orderOnly the newest matters

Sending cursors through the reliable edit channel from part 2 would be wasteful and slow: ten people moving their mouse would push hundreds of tiny, numbered, acknowledged messages a second, and edits would queue up behind them.

2The solution: a separate, lossy lane

Presence gets its own kind of message with the opposite rules: send the latest, at a limited rate, and forget it.

  • Throttle. Keep only the newest position and send it at most every 50 to 100 ms.
  • Smooth on the receiver. Animate each cursor toward the newest point, so 15 updates a second still look fluid.
  • Use document coordinates. Send where the cursor is on the board, not on the screen, because everyone has a different zoom and scroll.
  • Stay quiet when alone. If nobody else is in the room, send nothing.
Throttle · animated
Alice’s screenBob’s screenx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yAlicemouse moves 60+ times a second~10–20 / sglides between the points it gets
Fewer than one in four positions is sent. Smoothing on the receiver hides the gaps.
Key ideaPresence is a stream of “now”, not a history. Losing an update is fine, storing one is pointless, and only the newest value is worth sending.

Idle, away and gone

A cursor parked in the same spot for twenty minutes is misleading. And a person whose Wi-Fi blinks for two seconds should not disappear and reappear. Two timers fix both:

  • Idle after a few minutes without input. The avatar fades; the cursor can hide.
  • Grace period on disconnect. The server waits around 30 seconds before telling others that someone left. A reload or a short network drop never shows up as “left, joined”.
Screens · animated
Board · who is hereAAidleAleaving…BCCreloadingCAliceChiEveryone is activeNo input for a while: Alice turns idleChi reloads the page: a short grace period, no flickerAlice closes the tab: removed once the grace period ends
Idle tells you who is really paying attention. The grace period keeps the avatar bar calm.

Follow mode

Once viewports are part of presence, one more feature is nearly free: click a teammate’s avatar and your screen follows theirs. It is the same throttled stream, carrying x, y and zoom instead of a cursor position, and it is perfect for walkthroughs and reviews.

Screens · animated
Alice’s screenBob’s screen · Following AliceA1A2A3B1B2B3C1C2C3D1D2D3E1E2E3F1F2F3A1A2A3B1B2B3C1C2C3D1D2D3E1E2E3F1F2F3viewport: x, y, zoomviewview
Following is just applying someone else’s viewport to your own screen, a moment later.

3Example code

The sending side throttles, detects idle and never queues; the receiving side glides. The server keeps presence in memory and delays the “left” message.

presence.ts
type Presence = { x: number; y: number; idle: boolean }

const SEND_EVERY = 50          // ms: at most ~20 updates a second
const IDLE_AFTER = 5 * 60_000  // ms without input → idle

let latest: Presence | null = null    // only the newest value matters
let lastInput = Date.now()
let idle = false

window.addEventListener('pointermove', (e) => {
  lastInput = Date.now()
  idle = false
  const p = screenToBoard(e.clientX, e.clientY)  // board coordinates, not pixels
  latest = { x: p.x, y: p.y, idle }
})

setInterval(() => {
  if (!idle && Date.now() - lastInput > IDLE_AFTER) {
    idle = true
    latest = { ...(latest ?? { x: 0, y: 0 }), idle }
  }
  if (!latest || othersInRoom() === 0) return   // nobody to tell
  socket.send(JSON.stringify({ type: 'presence', ...latest }))
  latest = null                                  // never queue or resend
}, SEND_EVERY)

// Receiving side: glide toward the newest point instead of jumping.
function drawCursor(c: { shown: Presence; target: Presence }) {
  c.shown.x += (c.target.x - c.shown.x) * 0.3
  c.shown.y += (c.target.y - c.shown.y) * 0.3
  requestAnimationFrame(() => drawCursor(c))
}
server.ts
const GRACE = 30_000
const leaving = new Map<string, ReturnType<typeof setTimeout>>()

function onPresence(room: Room, userId: string, p: Presence) {
  room.presence.set(userId, p)          // memory only: never written to the DB
  room.broadcastExcept(userId, { type: 'presence', userId, ...p })
}

function onJoin(room: Room, userId: string) {
  clearTimeout(leaving.get(userId))     // came back in time: no "left" event
  leaving.delete(userId)
}

function onDisconnect(room: Room, userId: string) {
  leaving.set(userId, setTimeout(() => {
    room.presence.delete(userId)
    room.broadcast({ type: 'left', userId })
  }, GRACE))
}

Note what is missing compared to part 2: no sequence numbers, no outbox, no acknowledgements. That is on purpose. Every one of those would make presence slower without making it more correct.

4In practice: a design tool

  • Presence is more than a cursor. The current selection, the page someone is on, and whether they are dragging are all useful, and all follow the same lossy rules.
  • Make idle time a setting. Five minutes suits a design review; a long workshop may want longer. Idle users can still be followed, which helps when someone presents while not touching the mouse.
  • Guard follow loops. If Alice follows Bob and Bob follows Alice, both screens chase each other forever. A simple rule breaks the loop: when someone starts following you, you stop following them.
  • Cap what you draw. With dozens of viewers, show the people who are editing and summarise the rest as “+12”.

5Pros and cons

Pros

  • People see who is doing what, so edits stop being surprises
  • Cheap: throttled, never stored, nothing sent when alone
  • Enables follow mode and “who is looking at this?” for almost no extra work
  • Does not slow down real edits

Cons

  • Cursors are slightly behind real time by design
  • Timers (idle, grace) need tuning and can feel wrong if set badly
  • Many viewers still multiply traffic; large rooms need limits
  • Some people find visible cursors distracting, so offer a way to hide them

6Alternatives

OptionHow it worksGood for
Avatars onlyShow who has the document open, no cursorsDocuments where people rarely edit at the same moment
Presence through the edit channelTreat cursors like editsVery small rooms, early prototypes; does not scale
Ready-made presenceYjs “awareness”, Phoenix Presence, hosted realtime servicesTeams that do not want to run their own presence logic
Peer-to-peer (WebRTC)Cursors go browser to browserLow latency in small groups; harder to secure and to scale

7Conclusion

Key ideaTreat presence as a lossy stream of the present moment. Throttle it, smooth it, never store it, and give it timers for idle and leaving. Then follow mode comes almost for free.

Next: presence works, but when you pan or zoom, teammates’ cursors trail behind the board for a frame. Part 5 is about keeping overlays in step with the canvas.