What you'll learn: By the end of this lesson you will be able to explain how pub/sub routes messages by topic and what it does not give you, say why "who is online" cannot be asked of the network and must be inferred, design presence with one record per connection, a time-to-live and a grace period, and keep a client's presence list correct with a snapshot plus versioned diffs even when a diff is lost.
Think of a noticeboard in an office. Anyone can pin a note under a heading, and anyone who is standing at the board when a note goes up reads it: that is pub/sub. A note pinned while you were out of the room is never shown to you. Now think of the sign-in sheet by the door. It tells you who is in the building, but people leave without signing out, so the sheet needs a rule such as "if you have not been seen for an hour you are not here": that is presence.
The running example is a support console for orders: one room per order, a chat in each room, and a green dot beside each teammate who is viewing it. The lab's names and numbers are made up for the lesson.
The core idea
- Pub/sub decouples senders from receivers with named topics. A publisher does not know who is listening, and a subscriber does not know who is speaking. It is a routing rule, not a store: it delivers to whoever is subscribed now.
- Presence is inferred, not observed. A dead connection sends nothing, so "online" is a guess that expires unless it is refreshed by heartbeats.
- A presence list travels as a snapshot plus diffs. Because pub/sub can lose a message, the diffs carry version numbers so a client can tell that it missed one and ask for a fresh snapshot.
Three illustrations run through the lesson: a minimal example (two subscribers and a topic), a realistic example (the support console with several devices per person) and a failure example (a lost diff that leaves one client showing the wrong people).
This lesson builds on the real-time lessons on WebSockets in depth and on heartbeats and delivery guarantees, which cover the connection and the retry rules. The server side of the transports is in WebSockets, SSE and Long Polling.
Pub/sub: routing by topic
Redis describes the pattern as senders (publishers) not being programmed to send messages to specific receivers: published messages are categorized into channels, without knowledge of what subscribers there may be, and subscribers receive only what interests them. In Redis, subscribers get messages in the order they were published, and pattern subscriptions use glob-style patterns such as news.*. Socket.IO's rooms are the same idea for WebSockets: a room is "an arbitrary channel that sockets can join and leave", it exists only on the server, and a socket leaves all its rooms automatically when it disconnects.
A browser does not talk to the bus itself. It holds one WebSocket to a realtime server, and that server holds the subscriptions and forwards.
Figure 1. Where pub/sub sits in a real-time front end
How to read this: the message goes up to a topic and back down to each current subscriber. A client that is not connected and subscribed at that moment is simply not on the list.
What pub/sub does not give you is just as important. Redis states that its Pub/Sub has at-most-once delivery: a message is delivered once if at all, and if a subscriber fails or disconnects it is forever lost; for stronger guarantees it points to Redis Streams, which persist messages. So a late joiner sees no history, and a reconnecting client gets nothing for the time it was away. Two fixes are common: send a snapshot of the current state when a client subscribes, or keep a retained value. MQTT does the second: a server stores the last retained message of a topic and sends it to each new subscriber of a matching topic.
Presence: who is here, as a guess
Presence answers "who is online" for a room or a page. Two design decisions come first.
Connections versus users. One person can be on a laptop and a phone. Phoenix Presence groups entries by key, so a user with id 123 online from two devices has two metadata entries under one key. The lab does the same: the server stores one record per connection and answers per user, and a user is online while at least one connection is alive.
How a connection ends. There are two ways, and only one of them says goodbye:
| Way it ends | What the server sees | How it learns |
|---|---|---|
| Clean leave | A message or a close | At once |
| Silence (crash, lost network, closed lid) | Nothing | Only when heartbeats stop |
For the clean case a page can try to say goodbye when it is hidden. MDN says a visibilitychange to hidden is the last event that is reliably observable by the page, and that unload and beforeunload are often not fired, especially on mobile. navigator.sendBeacon() sends a small asynchronous POST without delaying the unload; its return value says only whether the data was queued. So a goodbye is a hint, and silence is the case you must handle. The MQTT protocol shows the server-driven version: a client may register a Will Message that the server publishes after the connection closes unexpectedly.
The rule for silence is a time-to-live: the client sends a heartbeat (see the lesson on heartbeats), the server records lastSeen, and a sweep removes any connection quiet for longer than the TTL. The TTL must be longer than the heartbeat interval, or a healthy user flickers.
The second rule is a grace period. When a reload makes a user's last connection end and a new one start a moment later, announcing "left" then "joined" makes the dot flicker for everybody in the room. The lab delays the "left" announcement by graceMs and cancels it if the user returns.
Figure 2. The life of one user's presence
How to read this: only two transitions are ever announced, join and leave. Everything else, a second device, a heartbeat, a reload, changes the server's records but not what anyone sees.
Snapshot plus diffs
A new subscriber needs the current list, and then the changes. Phoenix Presence works this way: it can fetch the presences for a topic and handle diffs of join and leave events as they happen, and a diff is a map of joins and leaves. The lab uses the same shape and adds a version number that goes up by exactly one per diff. That is this lab's own design, and it solves a problem pub/sub creates: since a message can be lost, the client checks version == current + 1 and otherwise knows it missed something.
Figure 3. A lost diff is detected by the next one
How to read this: the client never guesses. A repeated version is ignored, the next version is applied, and a skipped version triggers a snapshot.
Two costs to keep in mind. First, fan-out: every join or leave goes to everyone in the room, so a mass reconnect of N users produces up to N diffs to N clients, which is one reason to batch changes into one diff (the lab batches all leaves found in one sweep). Second, presence on several servers needs a rule for who owns each connection's record, which a one-server lab cannot show.
Choosing
Figure 4. Which tool for which feature?
(chat line, toast)"] Q -->|"the latest value,
then changes"| R["Snapshot or retained value,
then stream"] Q -->|"who is connected"| W["Presence: heartbeat, TTL,
grace, versioned diffs"] W --> T["Typing indicator =
presence with a short TTL"]
How to read this: ask what a client that joins late would need. If the answer is nothing, plain pub/sub is enough.
| Choice | Gain | Cost |
|---|---|---|
| Short TTL | Ghosts disappear quickly | A brief network gap marks people offline |
| Grace period | No flicker on reload | A real leave is shown late |
| Versioned diffs | Lost updates are detected | A version counter and a snapshot endpoint |
| Per-connection records | Multiple devices work | More records to keep and sweep |
Build it: a broker, a presence server and a client view
Goal. Run a topic broker (including a client that is offline and one that subscribes late), a presence server with a TTL and a grace period, and a client view that detects a lost diff.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic with a number for the clock: no browser, no sockets, no timers.
cd examples/frontend
pnpm install
cd labs/presence-pubsub
pnpm test # 18 tests
node src/demo.ts
Steps.
- Run the tests, then the demo.
- In section 1, find what
cyreceives: after reconnecting it gets nothing until it subscribes again, because subscriptions do not survive a disconnect. - In section 2, follow
ana: her laptop leaves and her phone reloads, and the observer sees no diff at all. - In section 2, find
ben: his last heartbeat is at 10000 and the leave appears at 50000. - In section 3, find the line where
flakyreports a gap.
Expected output, captured from a real run (Node 26.13.1; section 1):
=== 1. Pub/sub: topics, a wildcard, a late subscriber and a client that is offline
recipients of the 3 publishes: 2, 2, 0
recipients of "second" (cy offline): 1; of "third" (cy back, not resubscribed): 1
ana got: room.1#1:hello
ben got: room.1#1:hello room.2#1:hi room.2#2:second room.2#3:third room.2#4:fourth
cy got: room.2#4:fourth
dee got: (nothing)
Expected output, captured from a real run (Node 26.13.1; sections 2 and 3):
=== 2. Presence: ttl 30000 ms, grace 5000 ms, sweep every 5000 ms; each line is what an observer sees
t=0 ana connects on her laptop
t=0 ana connects on her phone
t=0 diff v1 joins=[ana] leaves=[] applied; online now: ana
t=1000 ben connects
t=1000 diff v2 joins=[ben] leaves=[] applied; online now: ana, ben
t=2000 ana closes the laptop (clean leave)
t=3000 ana's phone page reloads: leave ...
t=4000 ... and connects again 1000 ms later
t=10000 ben's last heartbeat, then his laptop loses power (no leave is ever sent)
t=50000 diff v3 joins=[] leaves=[ben] applied; online now: ana
server ends at version 3; ana has 1 connection
=== 3. Lost and late: a client that misses a diff detects the gap and asks for a snapshot
late joiner starts from snapshot v2: ana, ben
late gets v3 joins=[cy] leaves=[] -> applied
flaky gets v3 joins=[cy] leaves=[] -> applied
late gets v4 joins=[dee] leaves=[] -> applied
late gets v5 joins=[] leaves=[ana] -> applied
flaky gets v5 joins=[] leaves=[ana] -> gap
flaky needs a snapshot: true; shows ana, ben, cy at v3
after the snapshot (v5): flaky shows ben, cy, dee; late shows ben, cy, dee
Read the numbers. Ben's leave arrives at 50000: his last heartbeat was at 10000, the sweep first sees him as expired at 45000 (more than 30000 ms quiet), and the 5000 ms grace period ends at 50000. That is the price of the rule, and the TTL, the grace period and the sweep period all add to it. Ana never goes offline although both of her original connections ended, because a reload inside the grace period cancels the leave.
What the lab does not show. No real network or browser: no WebSocket, no visibilitychange, no sendBeacon, and nothing about several servers. The broker's rules (one delivery per client, prefix patterns ending in .*) and the version numbers are this lab's own design, not the behaviour of any product. The lab also has a gap that the failure below describes.
Break it. In src/presence.ts, delete the line this.pendingLeave.delete(user); in connect. A reload inside the grace period now ends in a "left" diff for a user who is connected, and the test "a reconnect inside the grace period produces no diff at all" fails. Put it back.
In practice: ghost agents in the support console
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The support console shows a green dot beside each agent viewing an order. Customers are told "an agent is looking at your order". Support finds that agents appear online for many minutes after closing their laptops, and that during a deploy the dots flicker for everyone.
Starting architecture
Figure 5. Starting point: presence follows the close event
How to read this: if the close event never comes, the flag never clears. If a reload closes and reopens, both changes are announced.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Clear on visibilitychange only |
Faster goodbye | A beacon on hide | Not delivered if the browser is killed |
| Heartbeat with TTL only | Silent ghosts expire | Delay equal to the TTL | Reload flicker remains |
| Per-connection records, TTL, grace and versioned diffs | Ghosts expire, reloads are invisible, lost diffs are repaired | A sweep, a version counter, a snapshot call | More moving parts |
The decision
| Field | Decision record |
|---|---|
| Context | The online flag depends on a close event that does not always arrive, and reloads announce a leave and a join. |
| Decision | Store one record per connection, refresh it with the heartbeat, expire it after a TTL, delay "left" by a grace period, and publish versioned diffs. Use a goodbye on visibilitychange as a hint only. |
| Consequences, good | No ghosts beyond the TTL plus the grace period, and no flicker on reload. |
| Consequences, bad | A real leave is shown late, and the server holds state that must be swept. |
| Revisit when | The console runs on several realtime servers, or the room grows so large that diffs must be batched or sampled. |
Rollout and verification
- Add the heartbeat first, so records have a
lastSeenbefore anything expires them. - Turn on expiry in shadow mode: log what would be removed and compare it with the old flag.
- Switch the dots to the new list and keep the old flag for one release.
The 2 a.m. failure
The realtime server restarts during a deploy. The new process starts its version counter at 1, but every open console still holds version 40. Each new diff looks like a duplicate and is ignored, and the older snapshot is refused as going backwards, so the dots freeze (illustrative). First three checks: (1) compare the server's version with a stuck client's; (2) check whether the counter survives a restart; (3) check whether a client can accept a snapshot that is lower. Mitigation: make clients reload the page on a restart, or reset the view when told the server restarted. Follow-up: add an epoch (a restart id) next to the version, and let a new epoch replace the view. Exercise 3 asks for this.
Architect's notes
- Name the three timers in the design: heartbeat interval, TTL and grace period, with the worst-case delay they add up to.
- Treat a goodbye as a hint and silence as the rule.
- Never rely on pub/sub for state: send a snapshot on subscribe and use versions to detect loss.
- Keep ephemeral signals ephemeral: a typing indicator is presence with a short TTL, not a stored fact.
Common mistakes
- Presence per connection shown per person, so two devices show two dots.
- Announcing leave and join on every reload, causing flicker.
- A TTL shorter than the heartbeat interval, so healthy users expire.
- Assuming a subscription survives a reconnect.
- Counters that restart with the server, so clients ignore the new diffs.
Key takeaways
- Pub/sub routes by topic and delivers to current subscribers only; Redis calls its delivery at-most-once.
- A late or returning client needs a snapshot (or a retained value); the bus will not replay.
- Presence is inferred from heartbeats and expires by a TTL; a goodbye on
visibilitychangeis only a hint. - A grace period hides reloads; the price is a delayed real leave.
- Versioned diffs let a client detect a lost update and repair it with a snapshot.
Practice exercises
Exercise 1 — Starter (45 min): With ttlMs 30000, graceMs 5000 and a sweep every 5000 ms, work out the best and worst time from a silent crash to the leave diff. Check one case against the lab.
Exercise 2 — Intermediate (2 hours): Add a typing signal to the lab that expires after 3 seconds and is never saved in the snapshot. Write a test that it vanishes without any leave message.
Exercise 3 — Advanced (half day): Add an epoch to snapshots and diffs. A client that sees a new epoch discards its view and takes the new snapshot. Write the test that reproduces the restart failure first, then make it pass.
Related reading
In this course:
- WebSockets, SSE and Long Polling, the transports pub/sub rides on.
- Offline-First Sync and Conflict Resolution, what to do about changes made while away, which presence does not cover.
- Debouncing and Throttling, the timing tools behind heartbeats and typing signals.
Official documentation
- Redis: Pub/sub, channels, patterns, ordering and at-most-once delivery.
- Socket.IO: Rooms, server-side channels that sockets join and leave.
- Phoenix.Presence, keys with several metadata entries and join and leave diffs.
- MQTT Version 5.0, retained messages, Keep Alive and the Will Message.
- MDN: visibilitychange event and Navigator.sendBeacon().