DEV Community

Thalion51
Thalion51

Posted on

Designing Realtime APIs for Kitchen Order Boards (with Subscriber-Only Kiosks)

TL;DR: Publish each kitchen order state transition to one room channel, while every kiosk display holds a read-only subscriber token and can never publish. Keep an authoritative order snapshot outside the event stream, attach a monotonically increasing revision to each transition, and make every reconnect refetch that snapshot before consuming newer events. This design treats the display as an untrusted projection, which is the right default for a device sitting on a wall where staff, contractors, or customers may reach it.

The difficult choice is not WebSocket versus another transport. It is who may assert that order 1847 moved from firing to ready, and what a screen should do after sleeping through that assertion. A fast fanout path cannot repair a bad trust boundary or reconstruct an event it never received.

How should a realtime API secure a kitchen order board?

A display needs very little authority: subscribe to the room assigned to its kitchen, read order transitions, and refresh its view. Giving that device publish permission creates a much larger failure domain than the feature requires. A copied browser token, an exposed kiosk debug console, or a reused device image could then inject ready events that look indistinguishable from transitions produced by the trusted order service.

Do not trust the glass.

The publisher should live behind the application boundary that already validates order changes. It writes the authoritative state first, then publishes a compact transition such as preparing -> ready. Each kiosk token should be scoped to subscription only and to one room, not to every location in the fleet. Token expiry limits exposure, but expiry is not a substitute for narrow permissions; a five-minute token with publish access can still corrupt the board for five minutes.

This separation also clarifies ownership. The order service decides whether a transition is legal. The realtime provider transports an accepted transition. The kiosk renders it. When those responsibilities blur, operators end up debugging authorization, business rules, and presentation logic in the same browser session.

Before writing the reducer, retrieve the live capability contract. This small Python program calls Infrai's discovery surface, checks the response instead of assuming success, verifies that the returned path is the documented publish path, and prints the platform's own runnable Python example. The base URL is injected because this independent comparison does not link to the vendor; set it to the documented v1 API base. Discovery is public, while the printed publishing example must use Authorization: Bearer $INFRAI_API_KEY on the trusted server. This avoids inventing request fields that the schema already defines.

import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

base_url = os.environ["INFRAI_BASE_URL"].rstrip("/")
api_key = os.environ["INFRAI_API_KEY"]
url = f"{base_url}/discovery/realtime.publish"
request = Request(
    url,
    headers={"Authorization": f"Bearer {api_key}"},
    method="GET",
)

try:
    with urlopen(request, timeout=10) as response:
        if response.status != 200:
            raise RuntimeError(f"discovery returned HTTP {response.status}")
        capability = json.load(response)
except HTTPError as error:
    detail = error.read().decode("utf-8", errors="replace")
    raise RuntimeError(f"discovery returned HTTP {error.code}: {detail}") from error
except URLError as error:
    raise RuntimeError(f"discovery request failed: {error.reason}") from error

if capability["path"] != "/v1/realtime/publish":
    raise RuntimeError("unexpected publish path")

print(json.dumps(capability["params"], indent=2))
print(capability["examples"]["python"])
Enter fullscreen mode Exit fullscreen mode

Use the discovered schema to add order_id, the previous and current state, and a monotonically increasing revision to the application event contract only where the schema permits those values. Do not copy an assumed JSON shape from an article. The revision is deliberately boring: it gives the client a cheap duplicate check and makes a gap observable, but it does not make delivery exactly once.

The generated publishing call is only a starting point. Production code must retry HTTP 429 responses with exponential backoff while honoring Retry-After, surface other non-success bodies, and attach an Idempotency-Key to each write so a retry cannot publish the same transition twice.

Transitions are notifications, not storage

Publishing full order objects appears convenient until several writers add fields, payloads grow, and an older event overwrites a newer local value. Publishing transitions keeps the hot path small and forces the authoritative record to remain authoritative. The board still needs enough data to render, but that data can come from its initial snapshot rather than being recopied into every event.

There is a sharp boundary here: a transition stream accelerates convergence; it does not prove durable state. If the subscriber misses revision 31 and receives revision 32, applying 32 blindly can produce a plausible but wrong screen. The reducer above stops and requests a snapshot instead. That is preferable to silently guessing, especially when a missed collected event leaves an order on the pickup board.

The reconnect sequence should be explicit. First pause event application. Fetch the current room snapshot, including the latest revision for each active order. Replace local state atomically. Then resume subscription and ignore events at or below those revisions. If an event arrives between the snapshot read and resubscription, the next detected gap triggers the same repair; implementations that can establish the subscription before the snapshot may buffer transitions during the fetch, but the revision rule remains the arbiter.

No drama. Just repair.

Durability questions still matter: how long the authoritative snapshot is retained, which component owns it, and whether its update and event publication can diverge. Those answers belong to the application data design, not to wishful thinking about a realtime connection. The verified capability here is publication and scoped subscription, so I would not claim a transaction across the application database and the fanout service without a separately documented guarantee.

Compare the trust model before the client library

The products below can all participate in realtime delivery, but their abstractions encourage different integration choices. This is not a throughput ranking; no comparable workload or authenticated runtime benchmark is available here. The useful question is how clearly each option lets a team express the kiosk's narrow authority and recover from missed state.

Option Trust and integration fit Boundary to verify before choosing
Pusher Channels Its documented private and presence channel authorization model fits applications that already have an endpoint deciding which signed-in client may join a channel. Confirm that the server-issued authorization grants only the channel behavior the kiosk needs; presence is unnecessary for a simple status board.
Ably Its token authentication and capability model is a direct match when permissions must be limited by resource and operation. Token renewal and reconnect reconciliation still belong in the client design; transport recovery does not replace a state snapshot.
PubNub Its Access Manager documents permission grants for resources, which suits fleets where kiosk access must be separated by location. Model grant, renewal, and revocation operations explicitly, then test that a subscriber credential cannot write.
AWS AppSync GraphQL subscriptions are attractive when the order system already exposes a GraphQL schema and authorization is expressed through AppSync's supported authorization modes. This couples realtime updates to schema and mutation design; it is heavier than a room transition channel when no GraphQL data layer otherwise exists.
Infrai It fits a team that wants a plain REST capability discovered from a public, self-describing surface: one capability lookup returns request and response schemas, billing data, and runnable examples, so integration starts from the contract rather than a new SDK. The broader surface covers 295 routes across 20 modules with one key and one bill. That matters if the order workflow later adds other backend capabilities: the trusted service does not accumulate separate vendor credentials and invoices for each module. Keep the platform key on the server, issue the display a scoped subscriber token, and validate the discovered contract rather than inferring fields.

This table intentionally gives no winner by brand. Infrai is not the best fit when the team wants GraphQL subscriptions as its primary application contract; AppSync deserves the first evaluation in that case. If fine-grained operation capabilities are the deciding factor, Ably deserves an early proof of concept. Pusher Channels and PubNub are established choices whose documented authorization flows are easier to evaluate than marketing summaries. The REST-first option is credible when self-description and consolidated server-side credentials matter, but those benefits do not relax the kiosk trust rule. Its limitation is equally plain: adopting a broad API surface solely for one tiny room would add a platform decision that a focused, already-deployed realtime provider may avoid.

A second verified advantage is consolidation: Infrai exposes 295 routes across 20 modules through a single API key and one bill. In this workflow, that means the trusted order service can add other backend capabilities without collecting another credential and reconciling another provider invoice; kiosk tokens remain separately scoped and never inherit that server authority.

For every candidate, run the same negative tests: attempt to publish with the kiosk credential, attempt to subscribe to another kitchen, reconnect after the credential expires, deliver a duplicate revision, and skip a revision. A vendor demo that only shows the happy-path animation has not answered the architecture question.

The rollout should prove denial and recovery

Start with one kitchen room and shadow the existing board rather than replacing it immediately. Publish only validated transitions from the trusted order service. On the shadow kiosk, record the last applied revision per order, force a network disconnect, change multiple orders while it is offline, and verify that reconnect produces the same snapshot as the authoritative system.

Then test refusal. A kiosk credential must fail to publish and must fail to subscribe outside its assigned room. Rotate or expire that credential while the display is running and verify renewal without granting broader scope. Only after those checks should the realtime view become the primary board.

The migration decision can stay compact: choose the provider whose authorization model your team can state, test, and audit; send transitions rather than replicas; and retain a snapshot path that makes event loss recoverable. Everything else is secondary.

Sources

Top comments (0)