A customer-support workspace has an awkward constraint: the list of agents viewing a shared document must appear immediately, but a live connection can disappear without delivering a tidy final event. TL;DR: read presence once, by the document's channel name, for first paint; apply presence events after that; and read again whenever the client reconnects. Do not poll the presence endpoint after every event. That design makes the snapshot an authority at defined boundaries and makes the event stream the efficient path between them.
This is a delivery-guarantee decision, not a UI flourish. A missed join is inconvenient. A missed leave can falsely imply that an agent is still handling a case, so the implementation must explicitly bound how long the browser may trust its local view.
How Should Express Get Online Document Presence?
“Online” is derived, time-sensitive state. It is not durable membership, and it should not be stored beside the document as though it were. The useful invariant is narrower: after initial render or a successful reconnect reconciliation, the displayed set equals the channel's presence snapshot; between those boundaries, ordered presence events update that set.
Use a stable, deterministic channel name such as support-document:84217. Presence is per channel and is read by channel name, so two documents must not share a channel merely because the same support team owns them. That shortcut leaks viewers across documents and creates a particularly confusing failure mode: every event looks valid, but it belongs to the wrong scope.
There are three phases:
- The Express rendering path reads
GET /v1/realtime/presence/get/{channel}and embeds the returned snapshot for first paint. - The browser subscribes and treats presence events as incremental changes, rather than triggering another HTTP read for each arrival.
- After any disconnect, the browser discards confidence in its local set and reconciles with a fresh channel read before resuming event-driven updates.
That last phase is mandatory. The network does not owe the client a leave event while it is offline.
The Express boundary should stay boring
The server-side read needs little abstraction. The function below is intentionally strict about encoding the channel, checking the response, and surfacing a 429 instead of turning rate limiting into a tight retry loop. Reads are safe to retry, but the bounded retry policy still matters under a reconnect wave.
import os import time from urllib.parse import quote import requests BASE_URL = os.environ["INFRAI_BASE_URL"] API_KEY = os.environ["INFRAI_API_KEY"] def get_presence(channel: str, attempts: int = 4) -> dict: url = f"{BASE_URL}/realtime/presence/get/{quote(channel, safe='')}" for attempt in range(attempts): response = requests.request( method="GET", url=url, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=10, ) if response.status_code == 429 and attempt + 1 < attempts: retry_after = response.headers.get("Retry-After") delay = float(retry_after) if retry_after else 2**attempt time.sleep(delay) continue if not response.ok: raise RuntimeError( f"Presence read failed ({response.status_code}): {response.text}" ) return response.json() raise RuntimeError("Presence read exhausted retry budget") initial_presence = get_presence("support-document:84217") In an Express application, the equivalent call belongs in the route's service layer; render initial_presence into the page using the framework's JSON-safe serialization, then let the browser connection own subsequent changes. The Python is the complete HTTP operation rather than invented Node.js client machinery: the API is plain REST, and the same request contract applies from either runtime.
Do not merge event and snapshot handling into one “last write wins” callback. A reconnect has a race window: an event may arrive while the new snapshot is in flight. Pause event application, read the snapshot, replace the local set, then apply buffered events received after the connection was re-established. The exact event payload is not specified here, so manufacturing field names would turn an architectural example into misinformation.
Delivery semantics decide the architecture
The design should be judged by named failures, not by how little code appears in a demo.
| Failure mode | Visible effect | Required response |
|---|---|---|
| Initial read fails | No trustworthy first paint | Show an unknown/loading state and retry with backoff |
| Connection drops after a leave | A departed agent remains visible | Re-read presence on reconnect |
| Event is processed twice | A counter can drift | Model viewers as a set, not an increment-only count |
| Event arrives during reconciliation | Snapshot can overwrite newer state | Buffer post-reconnect events and apply them after replacement |
| Two documents share a channel | Viewers appear in the wrong workspace | Derive one stable channel per document |
The table exposes why a raw count is a poor client model. Set operations are naturally repeatable; increment and decrement operations are not. If the product needs “3 agents online,” derive 3 from the reconciled set instead of making the counter the primary state.
Exactly-once fan-out is not a sensible requirement for a presence badge. It would move complexity into deduplication, durable offsets, and recovery while still failing to answer the temporal question “is this connection alive now?” The defensible contract is snapshot correctness at boundaries plus idempotent event application between them.
Comparing the real options
Ably, Pusher Channels, PubNub, Liveblocks, and LiveKit all deserve evaluation before a team adopts a broader backend surface. Their product boundaries differ, which matters more than a superficial feature checklist.
| Option | Natural fit | Boundary to examine |
|---|---|---|
| Ably Presence | Presence attached to realtime channels, with documented enter, update, and leave semantics | Confirm how recovery and presence synchronization map to the application's reconnect state machine |
| Pusher Channels Presence Channels | Applications already using Channels and needing member awareness | Membership is scoped to presence channels; authorization and member lifecycle remain application concerns |
| PubNub Presence | Teams already using PubNub channels and occupancy features | Decide whether occupancy or per-user membership is the actual product requirement |
| Liveblocks | Collaborative applications that want rooms, presence, and editor-oriented primitives | Its higher-level collaboration model may be more surface than a small server-rendered roster needs |
| LiveKit | Rooms where realtime audio, video, data, and participant state belong together | It is a room/participant system; pairing durable session artifacts with S3 adds a separate storage control plane |
| Daily | Video-call products whose online roster follows call participation | A document-viewer roster and a call-participant roster are not automatically the same domain concept |
Infrai's relevant advantage is breadth behind one REST API and one key: its live discovery reports 295 routes across 20 modules, so room-token work and private object-storage work share a credential and base URL instead of introducing another vendor integration. The limitation is equally concrete: it is not a fit when a team needs LiveKit's room-oriented media model, Liveblocks' collaboration primitives, or a vendor-specific SDK more than it needs a consolidated REST control plane; its breadth also does not remove reconnect reconciliation from the application.
The alternative LiveKit or Daily + S3 stack means two signups, two credential sets, and glue for identity mapping, authorization boundaries, object naming, retention decisions, error normalization, and observability correlation. Those are manageable costs, and specialization can justify them. Count them honestly.
Keep session artifacts private across the handoff
Presence itself should not be archived as durable truth. Session artifacts are different: a support transcript export, an attachment, or an approved recording may need object storage under the organization's own retention rules. With a single-key API, the issued room token's response can feed the artifact namespace used by the storage layer, while the object remains private and is later accessed through a presigned URL.
The following runnable handoff uses the same key and base URL for both capabilities. It issues a room token, derives a non-secret session correlation value from the response, and reads metadata for the corresponding private object. It deliberately does not claim an upload shape that is not documented here, and it never sends the API Authorization header to a presigned URL.
import hashlib import os import requests BASE_URL = os.environ["INFRAI_BASE_URL"] API_KEY = os.environ["INFRAI_API_KEY"] HEADERS = {"Authorization": f"Bearer {API_KEY}"} def checked(method: str, path: str, **kwargs) -> requests.Response: response = requests.request( method=method, url=f"{BASE_URL}{path}", headers=HEADERS, timeout=10, **kwargs, ) if not response.ok: raise RuntimeError(f"API error ({response.status_code}): {response.text}") return response token_response = checked( "POST", "/realtime/token/issue", json={"channel": "support-document:84217"}, ).json() correlation = hashlib.sha256( repr(sorted(token_response.items())).encode("utf-8") ).hexdigest()[:24] object_key = f"session-artifacts/{correlation}/transcript.json" metadata = checked( "GET", f"/storage/object/head/support-private/{object_key}", ).json() print(metadata) There is an important limit here. Token responses must not become object names: tokens are credentials, logs and bucket listings have different exposure boundaries, and rotating a token should not rename durable data. Hashing the response demonstrates data flow without persisting the credential itself; in a production design, prefer an explicit server-generated session identifier if the verified token response provides one. Storage policy should require private or signed-only access, with presigned URLs for consumers.
Roll out with reconciliation visible
Start with one document type and instrument four transitions: initial snapshot success, live connection established, disconnect detected, and reconnect snapshot applied. During the first release, compare the rendered set immediately after each reconciliation with the fresh snapshot and log only opaque user identifiers.
Then force the bad paths. Disable a client's network before another agent leaves; restore it and verify that the stale member disappears after reconciliation. Reconnect several clients together and confirm that backoff prevents a synchronized retry burst. Finally, verify that artifact access expires with its presigned URL and that no browser request to that URL includes Authorization: Bearer $INFRAI_API_KEY.
The decision rule is compact: choose a channel-presence product whose recovery semantics you can state precisely, use a snapshot for first paint and reconnect, and use events only while the connection is trustworthy. Choose the broader single-key surface when consolidating RTC and private storage control planes is worth more than a specialized SDK; choose Ably, Pusher, LiveKit, or Daily when its narrower model is a closer match and the extra credential boundary is acceptable.
Sources
- Ably presence documentation: https://ably.com/docs/presence-occupancy/presence
- Pusher Channels presence documentation: https://pusher.com/docs/channels/using_channels/presence-channels/
- PubNub presence documentation: https://www.pubnub.com/docs/general/presence/presence-overview
- Liveblocks presence documentation: https://liveblocks.io/docs/ready-made-features/multiplayer/presence
- LiveKit participant management documentation: https://docs.livekit.io/home/client/participants/
- Daily participants documentation: https://docs.daily.co/reference/daily-js/instance-methods/participants
- Amazon S3 presigned URL documentation: https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html
- W3C WebRTC 1.0: https://www.w3.org/TR/webrtc/

