- Real-time
- SSE
- Android
Real-time kitchens: server-sent events, push alerts and flaky restaurant Wi‑Fi
An online order that nobody notices is worse than no order at all: the guest has paid and is waiting. So when an order lands, Fravolo has to tell the right people at once — the counter, the kitchen display, the captain’s phone — and keep telling them until someone accepts it. All of that has to work over restaurant Wi-Fi, on phones that sleep and in browser tabs that get frozen.
Two channels for two jobs
There are two different problems here. Screens that are open — the orders page, the kitchen board, the captain’s phone — need a live feed of every change. Devices that are asleep or in a pocket need to be woken up, loudly, for the few events that matter. We use a different tool for each:
- Server-sent events (SSE) for open screens. One long-lived HTTP response per tab, text over the wire, automatic reconnection built into every browser. We do not need the client to talk back on the same channel, so WebSockets would add a protocol and buy us nothing.
- Push for sleeping devices: Firebase Cloud Messaging to our Android app, and standard Web Push to browsers that have opted in.
One bus, keyed by outlet
Every order and kitchen-ticket change is published to an in-process bus keyed by restaurant and outlet. The vocabulary is small: order.new, order.changed, order.late, kot.changed, kot.ready, table.order, printer.stuck, day.summary, plus WhatsApp inbox and link events and a test event. Payloads are flat string maps — deliberately, because the same payload is reused as an FCM data message, which only carries strings.
Event ids are a zero-padded millisecond timestamp plus a few random bytes. That makes them unique and sortable as plain strings, so “give me everything after id X” is a string comparison and nothing more.
With a single API instance, the bus delivers in-process. When Redis is configured, a publish is remembered locally and sent to a per-outlet pub/sub channel, and each instance subscribes to an outlet only while it has a local listener for it. If the Redis publish fails, the event is still delivered locally. A publisher never waits on a listener: each subscriber has a small buffer, and a listener too slow to drain it misses events rather than stalling the order that produced them.
// deliver hands an event to every local subscriber of the outlet.
// It never blocks: a slow listener drops events, the order goes on.
func (b *Bus) deliver(key string, ev Event) {
b.mu.Lock()
defer b.mu.Unlock()
b.rememberLocked(key, ev) // keep the recent tail for replay
for ch := range b.subs[key] {
select {
case ch <- ev:
default:
}
}
}The stream, and what happens when it breaks
The SSE handler writes a retry hint first, then any backlog the client missed, then live events. A comment line goes out every twenty seconds so proxies and phone radios do not decide the connection is idle. Each stream also ends itself after fifty minutes; the browser reconnects, which keeps long-lived connections from collecting stale state and spreads load after a deploy.
write("retry: 3000\n\n")
for _, ev := range bus.Since(key, lastID) { // replay what was missed
writeEvent(ev)
}
beat := time.NewTicker(20 * time.Second)
done := time.After(50 * time.Minute)
for {
select {
case ev := <-ch:
writeEvent(ev) // id:, event:, data:
case <-beat.C:
write(": ping\n\n")
case <-done:
return // the browser reconnects and resumes from the last id
}
}Replay is what makes a reconnect cheap. The bus keeps the last 64 events for each outlet. A reconnecting client sends the id of the last event it saw — the standard SSE mechanism, or a parameter when we reopen the stream ourselves — and gets the gap first, then the live feed.
The client: one stream per tab
In the console, every component that wants live updates calls a useLive hook, but they all share one EventSource per tab. It opens with the first subscriber and closes with the last. The hook tracks the last event id itself, which matters because of three failure modes a browser does not handle for you:
- An HTTP error stops the browser’s own retries. If the stream gets a 401 because a session is mid-refresh,
EventSourcecloses for good. We detect the closed state and reopen with exponential backoff, from a few seconds up to a ceiling. - Background tabs get frozen. When a kitchen tablet’s screen comes back on, a
visibilitychangehandler reopens the stream immediately instead of waiting for the next retry. - Replay has a horizon. Sixty-four events cover a blip, not a long outage. So the kitchen board and the captain’s phone also poll — quickly while the stream is down, slowly while it is up — and because the polling effect depends on the stream state, every reconnect triggers a fresh load.
es.onopen = () => {
backoff = 3000; // a good connection resets the backoff
setConnected(true);
};
es.onerror = () => {
setConnected(false);
// EventSource retries a dropped connection itself, but gives up on an
// HTTP error. Then we reopen, with a doubling, capped backoff.
if (es?.readyState === EventSource.CLOSED && retry == null) {
es = null;
retry = window.setTimeout(() => { retry = null; open(); }, backoff);
backoff = Math.min(backoff * 2, 30_000);
}
};
function onVisible() {
// A frozen tab came back with a dead stream: reopen now, don't wait.
if (document.visibilityState !== 'visible' || listeners.size === 0) return;
if (es && es.readyState === EventSource.CLOSED) { es = null; open(); }
}Push: waking the right people
Push is routed by role. A new online order goes to the roles that can accept it — owner, manager, cashier — with a short time-to-live, because a five-minute-old “new order!” is noise. A ready dish goes to captains and the counter. A table’s QR order goes to the floor. A late order goes to owners and managers, and a stuck printer to everyone who can walk over to it. A guest’s WhatsApp message goes to the owner. Devices are checked against current staff at send time, so someone who has left stops getting alerts even if their phone still holds a token.
Pushes never block an order. The device lookup runs in its own goroutine with a timeout, and each device is sent to in its own goroutine with its own timeout. Providers that say a device is gone get it deleted; a device that keeps failing is eventually removed too.
Web Push is implemented directly on the standard: message encryption and the application-server signature with Go’s crypto packages and a small JWT library, no push SDK. It is not much code, and it is code we can read. Subscriptions are accepted only for the known browser push services, and the sender never follows a redirect.
Ringing, not buzzing
A buzz in an apron pocket is easy to miss during a rush. On Android, a new-order push posts a full-screen notification and starts a short foreground service that loops an alarm-class sound with vibration until someone acts or it times out. In the browser, the service worker shows a notification that stays until it is dealt with, tagged by order so a repeat replaces the first instead of stacking up.
Both open the same full-screen accept card. Accepting sets a preparation time, which becomes the promised time that later drives the “late” alert. When the order leaves the new state — accepted on another device, or cancelled — an order.changed push silences the ringer everywhere and replaces the notification with a quiet one saying it was taken or cancelled.
Ring again, then escalate
The one-minute job loop looks for confirmed online orders that nobody has accepted. After about a minute it rings the same people again. After about three minutes it escalates to owners and managers, ignoring their notification preferences. Each step is recorded on the order with a conditional update, so a re-ring is never repeated — and the same marks would keep a second API instance from repeating it, should we ever run one. Like every job in that loop, it runs on its own goroutine, under a deadline, with panic recovery.
The other direction: one tap, one write
Live updates are half the story. The counter, the captain and the kitchen also write, over the same unreliable network, and a busy cashier taps twice. Three small rules keep that honest. The POS itself does not use the stream: it polls the floor on a timer, skips a poll while a write is in flight, and refreshes when the tab becomes visible again.
- One write at a time. Every write goes through a guard held in a React ref, which is checked and set synchronously. A busy flag in state is read from the render that created the click handler, so a fast second tap can see “not busy”; a ref cannot be stale.
- One key per intent. Each write carries an idempotency key. An identical write whose answer never came — a network error or a server error — reuses its key, so the server replays the first answer instead of acting twice; a definite answer retires the key. The settle sheet holds one intent from the moment it opens, so every attempt to settle that bill shares a key even if the cashier changes the tender in between.
- No stale polls. Every read is stamped when it starts. A newer read, or any write, makes older stamps stale, and a stale answer is dropped instead of painting the old floor back over a change the cashier just made.
const refresh = useCallback(async () => {
const stamp = reads.begin();
const floor = await posApi<Floor>('/floor');
// A newer refresh or a write started meanwhile: this floor is stale.
if (!reads.isLatest(stamp)) return;
setFloor(floor);
}, [reads]);
async function run<T>(fn: () => Promise<T>) {
return guard(async () => { // a second tap while this runs is dropped
reads.bump(); // any poll already on its way is now stale
try { return await fn(); }
finally { void refresh(); }
});
}On the server, the idempotency middleware marks a key as pending before the handler runs, so a duplicate that arrives while the first is still working is told so instead of running again. The settle itself also claims the ticket with a conditional update. Each layer would stop most double charges on its own; together they make the case we care about — a tap, a timeout, a retry — boring.
Trade-offs
- Replay is per instance and in memory. A reconnect that lands on a different instance, or after a long gap, cannot be served from the buffer. Polling covers it today. A durable stream (Redis Streams, for instance) would make replay exact across instances; we would reach for it when we run more than one API in production.
- Pub/sub is fire-and-forget. That is the right trade for UI hints that are always backed by a fetch. It would be the wrong one if events were the source of truth — so they are not; the database is.
- Slow consumers lose events silently. We prefer that to an order request waiting on a stuck tab. A counter of dropped events would make it visible; it is on the list.
- Android is not uniform. Some phones refuse to start a foreground service from the background, and some vendors’ battery savers kill apps aggressively. Those devices may ring once instead of looping, and owners have to exempt the app from battery optimisation.
- Timing is coarse. Re-ring and escalation run on a one-minute tick, so “about a minute” really means one to two. For a kitchen that is fine; we would not build a trading system this way.