Skip to content

    Frontend System Design

    Presence and Pub/Sub

    How pub/sub routes messages by topic and how presence, the green dot, is built on it: heartbeats, TTL, grace periods and versioned diffs, with a lab.

    By Published 12 min read

    • frontend-system-design
    • real-time
    • pub-sub
    • presence
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: WebSockets in Depth

    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

    1. 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.
    2. Presence is inferred, not observed. A dead connection sends nothing, so "online" is a guess that expires unless it is refreshed by heartbeats.
    3. 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

    Pub/sub fan-out: a publisher's message reaches every subscribed browser through the realtime serverAgent A to Realtime server (publish); Realtime server to Topic fan-out (topic); Realtime server to Agent B (push); Topic fan-out to Agent C (nothing sent)Agent A: publishes a chat lineAgent Apublishes a chatlineAgent B: subscribed to the roomAgent Bsubscribed to theroomRealtime server: one socket eachRealtimeserverone socket eachTopic fan-out: room.order-17Topic fan-outroom.order-17Agent C: offline: misses itAgent Coffline: missesitpublishtopicpushnothing sent

    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

    stateDiagram-v2 accTitle: States of one user's presence accDescr: A user is online while at least one connection is alive. When the last connection ends, by a clean leave or by missing heartbeats past the time to live, the user enters a grace period and is still shown online. If a connection returns during the grace period the user stays online and nobody sees a change. If the grace period ends the user is announced as gone. [*] --> Online: first connection Online --> Online: another connection or a heartbeat Online --> Grace: last connection ends Grace --> Online: connection returns Grace --> Offline: grace period over, announce leave Offline --> Online: new connection, announce join

    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

    sequenceDiagram accTitle: Detecting a lost presence diff accDescr: A client subscribes and receives a snapshot at version 2, then diff 3. Its connection drops and diff 4 is published while it is away. It reconnects and resubscribes, and diff 5 arrives. Version 5 is not version 3 plus one, so the client marks a gap, asks for a snapshot, and replaces its list with the snapshot at version 5. participant C as Client participant S as Presence server C->>S: subscribe S-->>C: snapshot (version 2) S-->>C: diff 3 Note over C: connection drops S--xC: diff 4 (lost) Note over C: reconnects, resubscribes S-->>C: diff 5 C->>C: 5 is not 3 + 1: gap C->>S: ask for a snapshot S-->>C: snapshot (version 5)

    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?

    flowchart TD accTitle: Choosing between plain pub/sub, a retained value and presence accDescr: If the data is an event nobody needs later, such as a chat line, use plain pub/sub. If new subscribers need the latest value, send a snapshot or a retained value, then stream. If the question is who is connected right now, use presence with heartbeats, a time to live, a grace period and versioned diffs. A typing indicator is presence with a very short time to live. Q{"What does the client need?"} -->|"an event, now"| P["Plain pub/sub
    (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.

    1. Run the tests, then the demo.
    2. In section 1, find what cy receives: after reconnecting it gets nothing until it subscribes again, because subscriptions do not survive a disconnect.
    3. In section 2, follow ana: her laptop leaves and her phone reloads, and the observer sees no diff at all.
    4. In section 2, find ben: his last heartbeat is at 10000 and the leave appears at 50000.
    5. In section 3, find the line where flaky reports 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

    NOTE

    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

    Starting architecture: a dot is set on connect and cleared only when a close event arrivesConsole page to Realtime server (connect, close); Realtime server to Room topic (flag changes)Console page: connects, says nothing moreConsole pageconnects, saysnothing moreRealtime server: online flagsRealtimeserveronline flagsRoom topic: join, leave eventsRoom topicjoin, leaveeventsconnect, closeflag changes

    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

    1. Add the heartbeat first, so records have a lastSeen before anything expires them.
    2. Turn on expiry in shadow mode: log what would be removed and compare it with the old flag.
    3. 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 visibilitychange is 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.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments