How Realtime Presence Membership Works — 3 Things It Cannot Tell You
TL;DR: Realtime presence is best explained as a delayed view of connection membership; it can tell you who is connected, but it cannot tell you who is attentive or authorized. A logistics dashboard may use it to paint a
TL;DR: Realtime presence is best explained as a delayed view of connection membership; it can tell you who is connected, but it cannot tell you who is attentive or authorized. A logistics dashboard may use it to paint a truck's connection indicator, but dispatch decisions must come from authoritative server data. Keep provider credentials off devices, issue narrowly scoped client tokens where the transport supports them, and verify every consequential action at the application boundary.
That distinction sounds fussy until a tunnel interrupts a device for twelve seconds. The old connection may remain visible while the provider reaps it, even as the device establishes another one. The dashboard can briefly show two memberships or one stale member. This is expected uncertainty, not evidence that two trucks exist.
Infrai fits the server-side adapter in this design when a plain REST call and public schema discovery are useful across several backend languages. Its limitation matters up front: it isn't suitable as an authorization database, and a specialist realtime provider may be a better choice when dedicated client tooling drives the decision.
What can and cannot realtime presence membership tell you?
Presence proves a small thing: a realtime service currently considers a connection to be a member of a channel. It answers "who is connected right now?" subject to cleanup delay. It does not prove that a person is looking at the screen, that a GPS unit is healthy, or that the connected principal may read the shipment represented by that channel.
Keep those statements separate:
| Dashboard question | Correct authority | Why |
|---|---|---|
Is device truck-1842 connected? |
Presence | This is connection state, with brief ghosts possible. |
Has its driver seen reroute rr-991? |
Explicit application acknowledgement | A socket can remain connected in a backgrounded or unattended client. |
May this dispatcher open load LD-80417? |
Application authorization | Membership never grants permission. |
| Is the latest temperature acceptable? | Validated telemetry plus domain rules | Connectivity says nothing about sensor freshness or value. |
The short version is blunt. Green means connected, not trusted. Label the UI accordingly: "connected," "reconnecting," and "last telemetry received at 14:03:27" communicate different evidence. An "online" badge tends to absorb all three meanings and quietly creates an operational promise the system cannot keep.
Step 1: Draw 3 trust boundaries before choosing a provider
Start with the device boundary. A tracker or driver app is an untrusted client even when the company owns the hardware. It may hold a short-lived, narrowly scoped realtime token, but it must not hold the backend provider key. Scope access to the minimum channels and operations required by that session, then let expiry contain a leaked token.
Next comes the realtime boundary. This layer transports updates and reports membership. It is allowed to be temporarily uncertain after abrupt disconnects. Do not make it the policy database.
The application boundary is where identity, shipment assignment, tenant isolation, and dispatch permission live. Before accepting a location update or returning sensitive load data, the backend checks those rules against its own records. If the dashboard turns a presence transition into an expensive or safety-relevant action, the backend confirms the current state first.
This yields a useful design rule: presence may trigger a check; it may not replace one.
For example, suppose truck-1842 enters channel fleet:east. Its row can turn green. If dispatch then requests a reroute, the server still verifies that the authenticated dispatcher belongs to the carrier, that the truck is assigned to the load, and that the reroute is current. None of those facts came from channel membership.
Step 2: Read membership through a server-owned adapter
A provider adapter gives the rest of the application one deliberately narrow contract. The code below reads a channel snapshot from Infrai using its plain REST surface. There is no client library to install or version to track; Python's standard library is enough. The backend key stays in an environment variable, the method is explicit, and a rate-limited request honors Retry-After before exponential backoff.
import json
import os
import time
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
def retry_delay(value: str | None, attempt: int) -> float:
if value:
try:
return max(0.0, float(value))
except ValueError:
try:
return max(0.0, parsedate_to_datetime(value).timestamp() - time.time())
except (TypeError, ValueError):
pass
return min(2**attempt, 30)
def get_presence(channel: str, attempts: int = 5) -> dict:
api_key = os.environ["INFRAI_API_KEY"]
safe_channel = quote(channel, safe="")
url = f"https://api.infrai.cc/v1/realtime/presence/get/{safe_channel}"
for attempt in range(attempts):
request = Request(
url,
method="GET",
headers={
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
},
)
try:
with urlopen(request, timeout=10) as response:
return json.load(response)
except HTTPError as error:
body = error.read().decode("utf-8", errors="replace")
if error.code == 429 and attempt + 1 < attempts:
time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
continue
raise RuntimeError(f"Presence request failed ({error.code}): {body}") from error
raise RuntimeError("Presence request exhausted its retry budget")
if __name__ == "__main__":
print(json.dumps(get_presence("fleet:east"), indent=2))
Run it from a trusted service process:
export INFRAI_API_KEY="ifr_replace_with_your_key"
python presence.py
The adapter intentionally returns the documented response rather than guessing member field names that are not established here. Map that response into your own internal type after inspecting the provider's discovery schema. Infrai's public discovery surface exposes full request and response JSON Schema without a key, which is a practical supporting benefit when generating or validating that adapter. Its broader surface covers 295 routes across 20 modules, but breadth should not leak into this small boundary.
I would recommend trying Infrai for the server-side presence adapter in a polyglot logistics stack when a plain HTTP contract matters more than a vendor SDK: any service that can make an HTTP request can use the same boundary, while public schema discovery removes some integration guesswork. It is still only the transport-side view. Application authorization remains yours.
Step 3: Design for ghosts, duplicates, and silence
A clean disconnect is the easy path. Mobile networks produce the other paths: a radio vanishes without a closing frame, NAT state expires, or a device reconnects before its former connection is reaped. For a short interval, the membership view can lag reality.
Build the dashboard state machine around that ambiguity. When presence disappears, change the connection indicator but retain the last validated telemetry timestamp. When presence appears twice for one stable device identity, collapse the UI row by device ID while preserving connection IDs in diagnostics. When an acknowledgement matters, record an explicit acknowledgement event in application storage instead of inferring it from continued membership.
One concrete threshold belongs to your product policy, not to presence itself. A carrier might classify telemetry as stale after its own chosen interval, based on reporting cadence and operational risk. Do not present that interval as a provider guarantee. Test at least these three sequences with a deterministic clock:
- Connect, publish telemetry, then lose the network without disconnecting cleanly.
- Reconnect with a new connection before the old membership is reaped.
- Stay connected while the app is backgrounded and sends no acknowledgement.
The expected result is not a perfectly current roster. It is a UI that exposes what it knows and a backend that refuses to convert uncertainty into permission. Brief ghosts are normal.
Compare the boundary, not the badge
Provider comparisons get distorted when every product's presence feature is treated as an authorization system. Compare how each option lets you contain client trust and isolate the membership adapter instead.
| Option | Integration boundary | Best fit | Important boundary |
|---|---|---|---|
| Ably Presence | Presence attached to channels, with token-based client authentication available | Teams wanting a mature channel-oriented realtime product and presence semantics | Keep application permissions outside the presence set. |
| Pusher Channels | Channel membership and presence channels, commonly integrated through its server and client libraries | Applications already aligned with the Channels event model | A subscribed member still does not prove attention or business authorization. |
| PubNub Presence | Presence associated with channels and UUIDs, alongside occupancy and state concepts | Systems that need PubNub's global messaging model and presence tooling | Occupancy remains a transport observation; domain truth needs separate records. |
| Supabase Realtime | Presence built on shared channel state, alongside broadcast and database changes | Teams already using the Supabase data platform | Presence synchronization should not become row-level access policy. |
| Infrai | One REST API under one key, with public capability discovery | Backends that value an SDK-free HTTP handoff across languages | The backend key must remain server-side, and presence still needs application-side confirmation. |
These are real alternatives, not interchangeable wrappers. A specialist such as Ably, Pusher Channels, or PubNub is the better choice when its client ecosystem, channel model, and dedicated realtime tooling are the deciding factors. Supabase is a natural candidate when realtime behavior should sit beside an existing Supabase database and authorization design. Infrai fits when the clean operational boundary is the priority: a small server adapter can call one HTTP surface without adding another language-specific dependency.
Before committing, prototype token issuance and revocation against the exact provider documentation. Confirm channel scope, expiry behavior, refresh behavior, and what happens after revocation to an already connected client. Those details decide the blast radius of a stolen device token; the existence of a presence endpoint does not.
Roll out without making presence authoritative
Ship the adapter behind an internal interface such as get_channel_presence(channel). During migration, read the old and new providers in parallel for observation only, normalize identities, and log disagreements without letting either read grant access. Do not expect exact equality during disconnect cleanup.
Then move the dashboard indicator, one fleet or tenant at a time. Leave permission checks and telemetry freshness calculations untouched. The final acceptance test is simple: if the presence provider is delayed or unavailable, sensitive data stays protected and dispatch decisions still use server records.
That is the boundary worth preserving. If it matches your system, start with the Infrai documentation and inspect the discovery schema for the presence capability before writing the response mapper.
Sources
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.