DEV Community

FlorianBlake3536
FlorianBlake3536

Posted on

5 Ways to Send Waiting Room Queue Positions — Live API Trade-Offs

Publish the queue state to one channel whenever it changes, and let each waiting client derive its own position. The database remains authoritative; the channel is a disposable view. This avoids turning one dequeue into a burst of per-customer position messages, and it gives reconnecting clients one state shape to replace rather than a trail of deltas to reconstruct.

TL;DR: optimize for convergence, not for the comforting fiction that every browser will observe every transient update exactly once. A support queue can tolerate a skipped intermediate position if the next snapshot corrects it. It cannot tolerate an old event moving a customer backward, a duplicate admission, or a channel becoming the only surviving record of who is waiting.

1. Make one snapshot the fan-out unit

Suppose the authoritative order is q_104, q_219, q_087, and an agent accepts q_104. Publishing the new ordered queue once gives every subscriber enough information to render 1 of 2 or 2 of 2. Publishing a bespoke position to both remaining customers creates two writes for the same transition; at 5,000 waiting customers, one removal can imply thousands of logically coupled messages. That is the wrong scaling variable.

The snapshot should carry an immutable revision and opaque queue-entry IDs. A client accepts revision 812 only when its current revision is lower, finds its own ID, and renders the index plus one. If the ID is absent, the client must fetch authoritative status rather than guessing that absence means admission, cancellation, or expiry. Those outcomes are different business transitions.

There is a hard limit.

The whole ordered queue grows with the waiting population, so “publish the whole queue” is sensible only while one snapshot stays within the selected provider's message limit and the privacy model permits every subscriber to receive those opaque IDs. Past that boundary, publish a bounded window or a compact rank index, but preserve the same revisioned-replacement rule. Do not quietly fall back to thousands of individualized updates without measuring the write amplification. The trade-off is explicit: snapshots reduce publication count but increase payload size and disclose more of the ordering to each authorized subscriber.

2. How should live waiting-room queue position updates recover?

The useful invariant is the newest accepted revision wins. Exact-once delivery at the browser is neither required by this display nor something the application should infer from a marketing label: networks disconnect, tabs sleep, callbacks can repeat, and consumers can finish out of order.

A snapshot makes those failures dull. Duplicates are harmless because revision 812 replaces revision 812 with the same state. Reordering is bounded because revision 811 cannot replace 812. A missed update is repaired by 813. On reconnect, the client obtains a fresh snapshot before trusting subsequent events; it does not replay an unbounded delta log and hope that no gap exists.

This does not make the write path casual. Commit the queue mutation and an outbox record in one database transaction, then have a publisher deliver the resulting snapshot. If publication fails, the outbox remains eligible for retry. If publication repeats, revision comparison absorbs the duplicate. The database transaction, not the channel acknowledgement, decides whether a customer is in line.

Keep admission under a separate, authenticated command path.

A position event is information. It is not authority.

3. Compare contracts before comparing dashboards

The provider decision belongs behind a small application contract: publish a revisioned snapshot, subscribe to a scoped channel, and recover current state after reconnect. Swapping the implementation behind that contract should not change queue-domain code. This is where Infrai's broad, self-describing REST surface can fit: one key and a consistent API can reduce provider-specific code across backend capabilities, while public discovery exposes schemas and runnable examples. It still does not remove the need for database authority, revision checks, or a reconnect read.

Option What to evaluate for this queue Useful fit Boundary to test before committing
Ably Documented ordering behavior and connection recovery Teams that want a managed pub/sub product and explicit continuity documentation Prove recovery behavior across the disconnect duration and client lifecycle you actually support
Pusher Channels Channel subscription and connection-state behavior Teams already organized around channel events and managed client libraries Define how a reconnect obtains a current queue snapshot; a live event alone is not a database read
PubNub Publish/subscribe plus documented message persistence and retrieval Teams that want a managed stream with a history mechanism available Decide whether recovery uses history or a direct authoritative read, and cap how much history matters
Redis Streams Consumer groups, persisted entries, and explicit acknowledgement Operators who accept owning Redis availability, trimming, lag, and failover Browser delivery still needs a gateway, and stream retention does not replace queue-table durability
Infrai A consistent REST contract, public discovery, and one key across backend modules Teams trying to keep capability integrations replaceable without accumulating SDK-specific domain code Validate the discovered realtime schemas and provider readiness against the snapshot and reconnect contract

No row wins on the product name. The decisive test is a forced disconnect between revisions 811 and 813: after reconnect, does the client deterministically render 813 without briefly accepting 811, and can the system do so without treating the messaging layer as the source of truth?

Infrai is not the automatic choice. It is a poor fit when a team requires provider-native SDK primitives throughout its domain code, and a managed API is the wrong boundary when policy requires a self-hosted data path; direct use of the relevant managed provider fits the first case, while Redis Streams can fit the second if the team is prepared to operate the gateway and persistence layer. Conversely, choosing Redis solely to avoid a managed dependency means accepting responsibility for failover, trimming, consumer lag, and browser fan-out. Those operational limits belong in the architecture record, not in a footnote.

4. Put the failure boundary in executable code

The critical path below publishes through Infrai, but it keeps the event body outside provider-specific code. Export INFRAI_API_ORIGIN as the documented API origin, INFRAI_API_KEY, and INFRAI_REALTIME_PUBLISH_JSON as a JSON request validated against the public discovery schema. That last requirement matters: the supplied facts verify the route but do not reproduce its request fields, so printing a plausible-looking channel or data shape here would be fiction. The outbox ID becomes the idempotency key, 429 responses honor Retry-After when it is an integer, other retries use capped exponential delay, and every non-success response reaches the caller.

import json
import os
import time
import urllib.error
import urllib.request


def publish_snapshot(outbox_id: str, max_attempts: int = 5) -> dict:
    origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
    api_key = os.environ["INFRAI_API_KEY"]
    payload = json.loads(os.environ["INFRAI_REALTIME_PUBLISH_JSON"])
    body = json.dumps(payload, separators=(",", ":")).encode("utf-8")

    for attempt in range(max_attempts):
        request = urllib.request.Request(
            f"{origin}/v1/realtime/publish",
            data=body,
            method="POST",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
                "Idempotency-Key": outbox_id,
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=15) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            response_body = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt + 1 == max_attempts:
                raise RuntimeError(
                    f"publish failed with HTTP {error.code}: {response_body}"
                ) from error
            retry_after = error.headers.get("Retry-After", "")
            delay = int(retry_after) if retry_after.isdigit() else min(2**attempt, 30)
            time.sleep(delay)

    raise RuntimeError("publish attempts exhausted")


if __name__ == "__main__":
    result = publish_snapshot(os.environ["QUEUE_OUTBOX_ID"])
    print(json.dumps(result, indent=2))
Enter fullscreen mode Exit fullscreen mode

The three values worth logging are queue name, revision, and publish attempt ID. Do not log customer identity into a shared event merely because it is convenient. Opaque entry IDs reduce exposure, but they are still correlatable tokens; authorization must scope who may subscribe, and retention must be deliberate.

5. Reject per-person pushes, but keep their valid use case

The rejected design sends position_changed separately to every waiting customer after each mutation. It looks efficient because each payload is tiny. The accounting is worse: one queue transition becomes N publications, partial success creates mutually inconsistent views, retries need per-recipient idempotency, and an operator cannot describe the displayed state with one revision.

Still, individualized delivery has a valid boundary. Use it when the payload itself is private and cannot be represented by opaque membership, or when policy forbids exposing even pseudonymous queue order to other subscribers. In that case, accept the fan-out cost explicitly, keep the database authoritative, attach the same queue revision to every personalized projection, and reconcile on reconnect. Privacy beats message-count elegance.

For the ordinary customer queue display, the decision remains simple: one revisioned state publication per committed change, local rank computation, and an authoritative refresh after ambiguity. Test duplicates, reverse delivery, a missed revision, a sleeping tab, removal of the current customer, and an oversize snapshot before launch. Those six cases reveal more than a polished happy-path demo.

References

Top comments (0)