Software Engineering

Live Updates Without Polling

13 min read
The CKE Kitchen Settings screen on a tablet, showing opening hours, a Pause new orders switch, and alert options for a beep when an alert opens and a chime for new online orders.

The Screens That Can't Wait

Casual Kitchen Express (CKE) is a food delivery platform I built as a portfolio concept: a customer app, a rider app, and a business app for the kitchen, with an API on Cloudflare Workers. Payments are simulated. Most of it is ordinary request-and-response work. You open a screen, it loads, you tap a button, it saves.

A handful of screens are different. They have to change while you're looking at them, with nobody tapping anything:

  • A new order lands on the kitchen board the moment a customer pays, with a chime.
  • The customer watches their order move from "placed" to "cooking" to "arriving."
  • A ready delivery appears in every online rider's queue, and disappears from all of them the instant one rider accepts it.
  • The rider's marker moves on the customer's map.
  • Dispatch sees an alert when an order has waited too long for a rider.
  • A price change or the new soup of the day shows up on customers' phones without a restart.

In the first post in this series, I explained why CKE couldn't just poll for these: on Workers' free plan, "is there anything new?" every few seconds from every screen would use up the day's request allowance before lunch. This post is about what I built instead, and the small details that make it reliable on patchy mobile networks.

One Hub, Many Listeners

The core idea: every app keeps one WebSocket connection open while it's in use, and the server pushes each change down the connections that should see it. Watching a screen costs no API calls at all.

On Cloudflare, the natural home for those connections is a Durable Object: a small piece of code with its own storage that lives in one place and handles one thing at a time. CKE has one, called LiveHub. Every app's WebSocket ends there.

 Customer app ─┐
 Rider app ────┼── WebSocket ──▶ LiveHub (Durable Object)
 Kitchen app ──┘                      ▲
                                      │ "this order changed"
 Any API request that changes data ───┘

When any API route changes something, say the kitchen marks an order ready, it saves the change to Postgres first, then hands the hub a list of messages to send. The hub delivers them and goes back to sleep.

A single hub works because CKE is one kitchen with a few dozen people connected at most. A platform with many restaurants would split this into one hub per restaurant. The design allows for that, but it didn't need it.

Who Gets What: Tags

Not everyone should see everything. A kitchen worker shouldn't see a customer's phone number. A customer should only see their own order. A rider should only see queue cards they can actually carry.

When an app connects, the Worker checks who's signed in, then hands the connection to the hub with a set of tags describing what that person may see:

const tags = ["all", `user:${actor.id}`];
if (actor.role === "customer") tags.push(`customer:${actor.id}`);
else if (actor.role === "rider") tags.push("riders", `rider:${actor.id}`);
else tags.push(actor.role); // kitchen, dispatch, accounts, or manager

Durable Objects can store tags with each WebSocket and look connections up by tag later, so the hub never needs its own list of who's connected. Each message says which tags it's for, and the hub sends it once to every matching connection:

for (const m of messages) {
  const text = JSON.stringify(m.data);
  const seen = new Set<WebSocket>();
  for (const tag of m.to)
    for (const ws of this.ctx.getWebSockets(tag)) {
      if (seen.has(ws)) continue; // in two groups, still gets it once
      seen.add(ws);
      try {
        ws.send(text);
      } catch {
        // A connection that is closing; the app reconnects and catches up.
      }
    }
}

So one order changing produces several messages, each shaped for its audience:

AudienceTagWhat they receive
Kitchen, dispatch, managers, accountsTheir roleThe order as the board shows it, with no customer phone or address
The customercustomer:<id>Only their own order, in the tracking shape
Online ridersridersA queue card appearing, or disappearing once taken
The rider carrying itrider:<id>Their delivery, or that it's finished
EveryoneallA "catalog" nudge when the menu or a setting changes

The important detail: the message carries the changed record itself, not just "something changed, go and fetch it." If the hub only sent a nudge, every listening app would immediately make an API call to find out what, and I'd have reinvented polling with extra steps.

Why This Fits the Free Plan

Three features of Durable Objects make this cheap enough to run for free.

Hibernation. A hub holding open connections doesn't have to stay running. When nothing is happening, Cloudflare puts it to sleep while keeping the connections open, and wakes it only when there's work. Before building anything, I tested this on a throwaway Worker on the project's own free account: a hibernating WebSocket answered after 12 seconds of silence.

Messages from the server are free. On the free plan, only messages coming from the apps count towards the request allowance. Messages the hub sends out don't. So a busy board receiving hundreds of updates costs almost nothing.

Pings that don't wake anything. Connections need a heartbeat, or phones and networks quietly drop them. The apps send nothing to the hub except a tiny "ping", and the hub registers an automatic reply:

this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));

Cloudflare answers that "pong" itself, without waking the hub. The app knows its connection is alive, and it costs no work at all.

Phones Drop Connections. Plan for It.

A WebSocket on a desk computer stays up for hours. On a phone on a Benin City mobile network, it drops when the rider rides under a bridge, when the signal switches towers, or when the app goes to the background. A live system that only works while the connection holds is a demo, not a product.

So the real design question isn't "how do I send updates?" It's "what happens to the updates an app missed while it was disconnected?" There are two bad answers. The app can reload everything on reconnect, which costs a pile of requests every time a rider hits a dead spot. Or it can carry on showing stale data, and the customer's tracking screen stops moving.

CKE's answer is a change number.

The Change Number

The database has a single counter, a Postgres sequence, shared by every row that apps watch live. Every time an order or alert is created or changed, it takes the next number from the counter:

export const touch = () => ({ version: sql<number>`nextval('change_seq')` });

So every order row carries the number of its most recent change, and the numbers only ever go up. Every live message includes that number. Each app remembers the highest one it has seen.

When an app reconnects, it makes one call:

GET /changes?since=4821

The API returns only the rows whose change number is higher than 4821, filtered to what that person may see, plus the latest number to remember for next time:

const newer = gt(t.order.version, since);
const rows = await db
  .select()
  .from(t.order)
  .where(actor.role === "customer" ? and(newer, eq(t.order.customerId, actor.id)) : newer)
  .orderBy(asc(t.order.version))
  .limit(MAX + 1);
if (rows.length > MAX) return c.json({ orders: [], alerts: [], latest, reload: true });

That last line is a safety valve. If more than 300 things changed while the app was away, a tablet that's been in a drawer since yesterday, for example, the API tells the app to simply reload its screen. Sending 300 small updates one by one would be slower than one fresh load.

Riders are a special case. Their queue and deliveries are always small, so /changes just returns both as they are right now, in the same single call.

On the app side, applying changes is a merge: by order number, with the newest version winning. That means it doesn't matter if a change arrives twice, once over the WebSocket and again in a catch-up. Applying the same version twice leaves the screen exactly the same. When updates can arrive more than once, make applying them safe to repeat. That one rule removes a whole category of "why is this order on the board twice?" bugs.

Reconnecting Without Hammering the Server

When a connection drops, the app tries again: quickly at first, then backing off, up to 30 seconds between attempts.

ws.onclose = () => {
  if (socket.current !== ws) return;
  socket.current = null;
  if (stopped || AppState.currentState !== "active") return;
  // Try again: quickly at first, then at most every 30 seconds.
  const wait = Math.min(30_000, 1000 * 2 ** tries.current++);
  retry.current = setTimeout(open, wait);
};

The waits go 1, 2, 4, 8, 16, then 30 seconds. If the API itself has a bad moment, a fixed short retry would have every app in the building hammering it at once. Backing off spreads the load. When a connection succeeds, the counter resets and the app immediately calls /changes to catch up on whatever it missed.

The AppState check matters too. When an app goes to the background, it closes its connection on purpose. Nobody is looking, so there's nothing to update, and an open socket would keep the phone's radio awake for no reason. When the app comes back to the front, it reconnects and catches up with one call. The hub holds nothing open for a phone sitting in a pocket.

When the App Is Closed: Push, Exactly Once

WebSockets only help while an app is open. A customer who locks their phone after paying still needs to hear "Your order is on its way." For that, CKE uses push notifications through Expo's push service, with Firebase delivering them on Android.

Push brought its own subtle problem. Two changes to the same order can land almost together, for example a status change and the timed alert check, and each one could decide "the status changed, send a notification." The customer gets "Your order is ready" twice. It's harmless, but it looks broken.

The fix is to make claiming the notification one database operation. Each order row remembers the last status a push went out for. Before sending, the API claims the new status with a single conditional update:

const claimed = await db
  .update(t.order)
  .set({ pushedStatus: sql`${t.order.status}` })
  .where(
    and(
      inArray(t.order.id, ids),
      sql`${t.order.pushedStatus} is distinct from ${t.order.status}`,
    ),
  )
  .returning();

Only rows where the pushed status differs from the current status get updated and returned. If two requests race, Postgres lets exactly one of them change the row. The other finds nothing to claim and sends nothing. Each status is announced exactly once, with no locks and no extra table.

Never Lose an Order

There's one ordering rule I didn't want to get wrong: save first, announce second. Every route writes to Postgres before it builds any live messages. If the hub is unreachable, or the kitchen tablet's connection has dropped, the order is still safely in the database, and /changes will deliver it the moment the tablet reconnects.

For a new order, the kitchen also gets a push notification. So even if the board's live connection was down at that exact moment, the tablet still chimes.

The hand-over to the hub also doesn't slow down the person who made the change. The API replies to the request straight away and passes the messages to the hub in the background, using the Worker's waitUntil:

c.executionCtx.waitUntil(
  liveHub(c.env)
    .publish(live)
    .then(
      () => undefined,
      () => undefined, // the live connection is a convenience; /changes catches apps up
    ),
);

That comment captures the whole philosophy. The live connection is a convenience; the database is the truth. If a live message is ever lost, nothing breaks. The next catch-up fixes it.

Timers Without a Cron Job

Dispatch needs alerts: an order waiting too long for a rider, a rider asking for help, a cancellation request. Some of those depend on time passing, not on anything happening. The obvious tool is a scheduled job running every minute, all day. But Neon's free database has a monthly compute allowance and sleeps when idle, and a job checking an empty restaurant at 3 a.m. would wake it for nothing.

Durable Objects have alarms: a single wake-up time each object can set for itself. Before building, I checked those on the free plan too. An alarm set five seconds ahead fired 1 ms late. The hub uses its alarm for the alert check, but only while orders are in progress:

  • When an order changes, the hub sets an alarm for a minute from now, unless one is already set.
  • When the alarm fires, it checks for alerts, sends any it finds, and counts the open orders.
  • If any orders are still open, it sets the next alarm. If none are, it stops.

A quiet restaurant costs nothing. The check comes back the moment the first order of the day arrives.

Testing It End to End

Live systems are hard to test piece by piece, because the bugs live in the gaps between the pieces. So before release, I ran one order all the way through, on real devices, across all three apps: placed and paid in the customer app, acknowledged and cooked on the kitchen board, accepted, picked up, followed live on the map, and delivered with the customer's code in the rider app. Every status change arrived on every screen, and every push notification arrived.

That test also found a real bug. The rider app stopped sending its position once an order was marked "arriving," so the customer's map froze for the last 300 metres, at exactly the moment they were watching most closely. Sending now continues until the last delivery. It was fixed in release 1.0.1, and it's the kind of bug only an end-to-end test on real devices catches.

What I Took Away

Send the data, not a nudge. A message that says "something changed" just makes every client ask what, and that's polling with extra steps. Sending the changed record means watching costs nothing.

Design for the disconnect, not the connection. The interesting part of live updates isn't sending them. It's what happens to the ones that were missed. A single ever-increasing change number turns "reload everything" into one small call.

Make every update safe to apply twice. Messages can arrive over the socket and again in a catch-up. If applying a change twice is harmless, you never have to work out which copy came first.

Let the database settle races. When two riders accept the same order, the API locks the order's row inside a transaction, so the second rider waits, finds it gone, and gets "Another rider took this order." When two requests try to send the same push, one conditional update decides it. In both cases Postgres picks the winner, not the app.

Treat the live channel as a convenience. Save first, announce second, and make sure everything can be recovered from the database. Then a dropped connection is a small delay, never lost data.

Test the free-plan features before you depend on them. Hibernation and alarms both got a quick test on a throwaway Worker before the design relied on them. A quick test is cheap insurance against a design that doesn't work.

This is the last post in this series on CKE. The full project, with screenshots of all three apps and their downloads, is on the Casual Kitchen Express case study.