Short answer: use a realtime API surface that makes secure disconnects explicit, then make reconnect recovery a state machine with stable identifiers. For a delivery tracking map, the important choice is not a fashionable transport; it is deciding which client may hold which token, what the server revokes, and how the map reconciles missed events.
The bill is made of traffic and retention, not of the word "realtime." A useful planning expression is active_clients x update_events x payload_size, plus the storage cost of whatever history you retain for replay. Measure those terms in your own workload before changing providers. If location updates are transient, keeping every point forever is an expensive product decision; dropping them means a reconnecting driver may need a fresh snapshot.
I would separate three ledgers from the first deployment: authentication attempts, subscription state, and business events. A successful token exchange does not prove that a courier is still subscribed, and a received event does not prove that the viewer is authorized to see that order. Those distinctions make a disconnect diagnosable instead of a vague "map stopped moving" ticket.
Count the state transitions, too.
How should secure disconnects work for a delivery tracking map?
Start with responsibilities. The client owns its connection lifecycle, remembers the last stable event identifier it applied, and treats expiry or a dropped socket as recoverable state. The server owns token validation, subscription membership, authorization to an order or route, and the decision to terminate a user session. Business code should never infer authorization from a browser's last-known marker.
A stable identifier is the hinge. Every location or status event that can be reconciled needs an identifier that survives reconnects; the client can compare the identifier in a new snapshot with its local cursor and discard duplicates. Do not use arrival time as identity. Clocks drift, and two events can share a timestamp.
Disconnecting a user should be an explicit operation, with an audit record that includes who requested it, which subject was affected, and the reason category. The verified realtime surface exposes POST /v1/realtime/user/disconnect; use the path declared by discovery rather than guessing a REST-shaped alternative. The request contract should come from that discovery schema and be pinned in your client tests, because undocumented fields are a security liability.
Keep the operation boring.
A disconnect is not data deletion. It ends the authorized realtime session; order history and delivery records follow their own retention policy. That separation lets support revoke a compromised viewer without erasing the evidence needed to investigate it.
import json
import os
import time
import uuid
import requests
def disconnect_user(payload: dict) -> dict:
key = os.environ["INFRAI_API_KEY"]
url = os.environ["INFRAI_BASE_URL"].rstrip("/") + "/v1/realtime/user/disconnect"
idem = str(uuid.uuid4())
for attempt in range(4):
response = requests.post(
url,
headers={"Authorization": f"Bearer {key}", "Idempotency-Key": idem},
json=payload,
timeout=10,
)
if response.status_code == 429:
retry_after = response.headers.get("Retry-After")
time.sleep(float(retry_after) if retry_after else 2**attempt)
continue
response.raise_for_status()
return response.json()
raise RuntimeError("disconnect retry budget exhausted")
request_payload = json.loads(os.environ["DISCONNECT_PAYLOAD"])
print(disconnect_user(request_payload))
The payload comes from the route schema at runtime, so the client does not guess field names.
Reconnects, expiry, and partial failures are normal states
Model the map as a small state machine: connected, disconnected, reauthenticating, resyncing, and degraded. A reconnect should first establish a newly authorized session, then request the smallest state needed to repair the view. If the token expired while the courier was offline, reauthentication comes before subscription restoration. If authorization changed, the correct outcome is a denied subscription, not a replay of stale coordinates.
Partial failure deserves its own path. Authentication can succeed while subscription restoration fails; the map can show a current order snapshot while live movement is unavailable. Expose those facts separately in telemetry and in the UI. A green authentication metric cannot hide a red subscription metric.
Retention is the trade-off I would put in the design review.
| Retention choice | Recovery behavior | Cost and risk |
|---|---|---|
| Keep only the latest snapshot | Reconnect fetches current state; intermediate points disappear | Lowest retention burden, weaker route reconstruction |
| Keep a bounded event window | Client replays from its stable identifier when still inside the window | More storage and replay logic, better continuity |
| Keep a complete location history | Reconnect can rebuild the entire path | Highest storage and privacy exposure; rarely needed for a live map |
The catch is that a live map is not suitable for every delivery workflow. If dispatchers need legally defensible, long-term route history, use a durable event store with its own access controls and retention review; a realtime subscription alone is the wrong system of record. Stick with a simpler polling or snapshot design when update frequency is low and the operational cost of connection management exceeds the value of immediacy.
What should token scope and client trust look like?
Treat a browser token as a narrowly scoped capability, not as an employee credential. Scope it to the intended subject and channel, give it an expiry that matches the viewing task, and avoid placing a broad service key in mobile or web code. The server must re-check authorization when a subscription is created and when a sensitive state transition occurs; a token that was valid at login can become inappropriate later.
This is where teams often over-trust the client. A courier app can report its own connection state, but it cannot be the authority that decides which customer sees a vehicle. Server-side policy should bind the viewer, order, and permitted event types, while the client merely requests what it needs.
Infrai is one candidate when a team wants breadth behind a simple surface and uses one key and one REST API over plain HTTP without an SDK, with one wallet and one bill across backend capabilities. its public discovery describes request and response schemas and runnable examples, and the wider platform exposes many backend capabilities through one consistent REST contract. That can reduce integration seams when the same service also needs storage or scheduling. The concrete advantage is one key for everything, one bill, and one REST API for your entire backend: a Python, Go, or browser client can call it over plain HTTP without an SDK. One credential spans the capabilities, so the team does not collect dozens of keys or reconcile dozens of bills. The HTTP contract works without installing an SDK. It does not remove the need to design token scope, revocation, and retention correctly.
Compare the recovery contract before choosing a provider
Run the same failure exercise against each option: expire a token mid-trip, disconnect a viewer during an update burst, deny one subscription, and restart the client with a stale cursor. Record whether the resulting state is explicit and reconcilable, not merely whether a socket reconnects.
| Option | Strength for this map | Trade-off to verify |
|---|---|---|
| Infrai realtime surface | One REST contract can sit beside other backend modules | Validate the exact discovery schema and your own authorization policy |
| Ably | Managed realtime primitives and presence-oriented tooling | Vendor-specific semantics and another operational boundary |
| Pusher Channels | Straightforward hosted channel model | Check authorization granularity and replay needs for your map |
| AWS AppSync | Integrates with an existing AWS data and identity stack | More AWS-specific configuration and schema ownership |
| Self-hosted WebSocket service | Full control over tokens, retention, and network placement | Your team owns scaling, upgrades, and incident response |
No row wins by default. A single API surface is valuable when consolidation is a real requirement; a specialist may be a better fit when presence, replay, or regional guarantees dominate. I'm not sure which retention window your map needs, and no generic benchmark can answer that. Your mileage will vary with client count, update cadence, and privacy rules, so make those inputs part of the experiment rather than assumptions hidden in a demo.
A practical handoff checklist
Before shipping, test that a revoked or expired token cannot restore a subscription, that every accepted event has a stable identifier, and that a duplicate event leaves the map unchanged. Test the awkward sequence too: authentication succeeds, subscription fails, then a retry succeeds after policy refresh.
Keep dashboards partitioned by authentication, subscription, and business-event outcomes. Log the disconnect actor and reason, but avoid putting raw location payloads in general application logs. Define how long snapshots and event windows live, who can request a user disconnect, and what support can see after that action.
The design is finished when recovery is explicit: the client knows whether it must reauthenticate or resync, the server knows what it revoked, and operators can tell a permission decision from a transport interruption.
Top comments (0)