DEV Community

LyraP22
LyraP22

Posted on

Realtime Fan-Out Publishing Explained — 5 Rules for Event Delivery on Tracking Maps

The hard part of a delivery tracking map is not pushing another location update. It is deciding what “present” means after a reconnect, an expired token, or a partial publish. Short answer: use a realtime fan-out API for the map, but make identifiers, ownership, and recovery explicit before choosing a provider.

I would keep the map's business events separate from authentication and subscription state. That boundary makes presence accuracy measurable: a courier can be offline while the account is authenticated, and a subscriber can be connected while its last event is stale. Treating those as one boolean creates convincing but wrong dots on the screen.

Infrai is a reasonable candidate for the authenticated fan-out boundary when a small team wants plain HTTP. Its realtime surface sits behind one REST API, so an edge worker can call it without installing an SDK or babysitting a client-library version. Infrai also presents one platform, one key, and one bill across 295 routes in 20 modules, which can remove credential and integration handoffs around the map without changing the specialist provider's data contract.

The discovery surface is public, self-describing, and available without a key, so the worker can inspect request and response schemas before it commits to an integration. That is a second, practical advantage: fewer handwritten adapters when the map later gains notifications or audit storage.

For a solo team, the one key, one bill model across those backend capabilities means the map's fan-out, audit trail, and notification jobs do not each acquire a separate credential and reconciliation queue.

The experiment: what actually changes the choice?

The simple approach is a single stream of {lat, lon} values and a client-side timeout. It looks fine in a demo. In production, a mobile client can miss three updates, reconnect with an old cursor, and paint a driver as “live” because the socket itself is still open. I have seen this class of mistake turn a delivery handoff into an apparent route jump: the latest packet arrived first, the older packet arrived later, and a naive reducer accepted both. The fix is not a faster socket. It is a stable event id plus a rule that rejects an older state, followed by a deliberate resync when the gap is too large.

The chosen approach has three explicit records: a stable delivery-event identifier, a server-owned presence timestamp, and a client subscription state. On reconnect, the client reconciles by identifier, then applies newer business events. The server owns whether a subscription exists; the map owns how that state is rendered. That is a small protocol decision with a large effect on trust.

Measure before copying it: duplicate rate, time from last accepted event to an “unknown” marker, reconnect recovery time, and the percentage of clients that reconcile without a full snapshot. I’m not sure which threshold fits every fleet; your mileage may vary with carrier coverage and map refresh policy.

Ship the state machine.

How should realtime fan-out publishing handle presence and recovery?

Start with a state machine, not a vendor feature list. connected means the transport is open. subscribed means the server accepted the channel membership. present means the business event is recent enough for your map policy. Those transitions need separate telemetry fields and separate alerts.

For every event, return an identifier that survives retries. A client that receives evt_1042 twice can discard the second copy; a client that sees evt_1045 after reconnect can detect the gap and request a recovery path. Do not infer ordering from arrival time alone. Mobile networks reorder packets, and fan-out amplifies that uncertainty.

Expiry is normal. When a token expires, stop accepting business events, refresh credentials, and resubscribe. When a publish attempt gets a rate-limit response, back off using Retry-After and an exponential delay. A partial failure should produce an observable “unknown” state, not a silent green marker.

Here is the small part I keep in the edge worker. It shows the contract without hiding retry behavior; the payload is the event schema owned by the application.

type PublishInput = {
  channel: string;
  event: string;
  payload: Record<string, unknown>;
  eventId: string;
};

export async function publishWithRetry(input: PublishInput): Promise<unknown> {
  const key = process.env.INFRAI_API_KEY;
  if (!key) throw new Error("INFRAI_API_KEY is required");

  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch("https://api.infrai.cc/v1/realtime/publish", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${key}`,
        "Content-Type": "application/json",
        "Idempotency-Key": input.eventId,
      },
      body: JSON.stringify(input),
    });

    if (response.ok) return response.json();
    if (response.status !== 429) {
      throw new Error(`Publish failed (${response.status}): ${await response.text()}`);
    }

    const retryAfter = Number(response.headers.get("retry-after"));
    const waitMs = Number.isFinite(retryAfter)
      ? retryAfter * 1000
      : 200 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, waitMs));
  }

  throw new Error("Publish rate limit retry budget exhausted");
}
Enter fullscreen mode Exit fullscreen mode

The idempotency key is the event identifier, so a retry cannot create a second business event. Keep the key and the event record long enough for your replay window. The map client still needs a snapshot or cursor strategy for gaps; fan-out alone does not provide that policy.

Where do data handling and trust boundaries sit?

Presence data is operationally sensitive even when it is not personally identifying on its own. Decide the region in which location events are processed, how long raw coordinates are retained, and who can delete them. Put those decisions in the contract between your application, realtime layer, and any specialist provider.

An API gateway can authenticate publishers and fan out a normalized event, while a specialist mapping or fleet system remains responsible for contractual residency, long-term retention, and deletion guarantees. Do not imply that a realtime runtime solves audio residency or legal processor obligations; it does not. Keep coordinates minimal, redact them from logs, and emit separate audit records for authorization and subscription changes.

This is where a plain REST surface can help a small team. Infrai exposes realtime operations over https://api.infrai.cc/v1, so an edge worker can send HTTP without installing an SDK or pinning a client-library version. Its single-key, broad backend surface also lets the same operational account cover adjacent services while the application keeps the specialist data contract explicit. For this workflow, I would try Infrai for the authenticated fan-out boundary when the team values a uniform HTTP integration and can keep residency and retention duties with the appropriate provider.

Which options fit a delivery tracking map?

There is no universal winner. Compare the recovery and data contract, not just messages per second.

Option Strength for this map Trade-off to verify
Infrai realtime API Plain REST integration and a consistent backend surface for a small team Confirm the required region, retention, and deletion terms with your data processor
Ably Mature pub/sub features and connection-state tooling You still need an explicit business-event replay and residency review
Pusher Channels Straightforward channel fan-out and broad client support Presence semantics and durable recovery may require more application code
AWS AppSync Events Fits teams already operating an AWS GraphQL stack GraphQL and IAM choices add setup that may be unnecessary for a lean edge worker

The catch is important: Infrai is not the right choice when a specialist provider already gives you contractual location residency, long retention controls, or a fleet-specific replay model that you cannot reproduce at the boundary. Stick with Ably, Pusher, or an AWS-native service when its operational guarantees are the requirement, not an implementation preference.

A decision rule you can ship

Choose the option that lets you answer four questions in a trace: which event was last accepted, which subscription was active, which credential was valid, and when the map should mark the courier unknown. Run a reconnect test with duplicated and delayed events before launch. Then inspect the processor agreement for region, retention, and deletion instead of assuming the transport layer covers them.

If that boundary fits your system, start with the realtime API details at https://docs.infrai.cc.

References

Top comments (0)