← Blog
By Raman Halder··7 min read

Realtime Cafe Ordering: Putting the Rules in Postgres

How Vivere Bay Cafe's ordering system keeps one bill per table correct with Supabase: Postgres functions for every write, idempotent orders, and a live board that catches up after a tablet sleeps.


Key takeaways: When several phones change the same bill, putting every write in a Postgres function gives you one place to enforce the rules, inside the transaction that does the write. A key generated on the phone makes retries on a bad connection safe. Treat realtime events as a reason to reload, and reload on reconnect and when the screen wakes. Column grants keep phone numbers private, and Supabase Realtime respects them too. Test the races against a real database.

The Shape of It

We built a web proof of concept of an ordering system for Vivere Bay Cafe, which you can open in any browser. Guests scan a QR code on their table, order in rounds and pay when they leave. Staff run a live board. The owner has an admin console. The rules post covers how it behaves from the cafe's side, and this one is about how it's put together. It hasn't been through a real service yet, so there's a short section at the end on what we're waiting to find out.

It's one Next.js 16 App Router app, with route groups for the guest, staff and admin apps. Supabase provides Postgres, auth and Realtime. Guests are signed in as Supabase anonymous users as soon as they open a table link, so every phone has a user id and nobody creates an account. Staff sign in with their name and a PIN, and the owner signs in with email.

The Browser Can Read but Not Write

Row-level security lets a guest read their own table's tab, rounds and items, and lets staff read everything. Nobody can insert or update tabs, rounds, round items or payments from the browser. Every change goes through a Postgres function declared `security definer`, which checks who's calling, applies the rule, and writes.

There are about a dozen: `place_round`, `request_bill`, `advance_round`, `confirm_payment`, `cancel_round`, `close_tab_unpaid`, the membership functions, and a few more. When a rule fails, the function raises a short text code such as `bill_requested` or `item_unavailable:Almond croissant`. The app has one table that turns each code into the sentence a guest or server reads:

const MESSAGES: Record<string, string> = {
  bill_requested: "Your bill has been requested. Ask your server if you'd like to add something.",
  item_unavailable: "%s just sold out.",
  tab_not_payable: "This bill is already closed.",
  amount_mismatch: "The bill changed. Check the new total before confirming.",
  // ...
};

The reason for doing it this way is that the guest app, the staff app and the admin console all change the same rows, sometimes in the same second. If the rules lived in server actions, each action would repeat them, and nothing would stop a later code path that forgot one. In Postgres they live in one place and run inside the transaction that makes the change.

It has costs. PL/pgSQL is harder for most developers to read than TypeScript, and changing a rule means writing a migration that replaces the function rather than editing a file. We took that trade because the number of rules is small and a wrong bill is an expensive mistake for a cafe.

One Open Tab per Table

The rule itself is a partial unique index:

create unique index tabs_one_live_per_table on tabs (table_id)
  where status in ('open', 'bill_requested');

On its own, the index would make the second of two simultaneous first orders fail with a constraint error, and that guest would see something unhelpful. So `place_round` first takes a transaction-level advisory lock on the table. Two phones placing a first order at the same moment queue up. The first opens the tab, and the second finds it and becomes round 2.

perform pg_advisory_xact_lock(hashtext(v_table::text));
select id, status into v_tab, v_status from tabs where id = active_tab_id(v_table);
if v_status = 'bill_requested' then raise exception 'bill_requested'; end if;
if v_tab is null then insert into tabs (table_id) values (v_table) returning id into v_tab; end if;

The same function reads prices from the menu and copies them onto each line. The phone sends item ids and quantities and never a price. Money is stored as whole numbers in the currency's smallest unit, and tax is only ever worked out in one function, `tab_bill`. The guest's checkout, the staff payment card and the dashboard all get their totals from it.

Retries on a Bad Connection

When the guest opens their order sheet, the phone makes a UUID. `place_round` checks it before anything else, and the column it's stored in is unique:

select id into v_round from rounds
  where idempotency_key = p_idempotency_key and placed_by = auth.uid();
if v_round is not null then return v_round; end if;

A guest on weak signal can tap Place order, see nothing happen, tap again, and the kitchen still gets one round. Opening the sheet again makes a fresh key, so a second order placed on purpose goes through as a new round.

Two Staff, One Ticket

On the staff side the races are two servers tapping the same ticket, or two servers confirming the same bill.

`advance_round` takes the status the server's screen was showing. If the round has already moved on, it refuses, and the server sees "This order has already moved on. Refresh to see the latest." Without that, two taps on Start preparing would push a ticket from New straight to Ready.

`confirm_payment` locks the tab row with `select ... for update`, checks the tab can still be paid and that the amount matches the current total, then records the payment and closes the tab. A second confirm waits for the lock, finds the tab already paid, and fails with `tab_not_payable`. A database test fires two confirms at once and checks that exactly one payment exists afterwards.

Realtime as a Doorbell

Supabase Realtime sends row changes over a websocket. The obvious approach is to apply each change to the screen's state. We don't. An event only tells the screen to reload what it's showing, with a 150ms debounce so a round with five items causes one reload and not six.

const refresh = useCallback(() => {
  clearTimeout(timer.current);
  timer.current = setTimeout(() => loadRef.current().then(setData).catch(() => {}), 150);
}, []);

channel.subscribe((status) => {
  if (status === "SUBSCRIBED") refresh();
});

const onVisible = () => document.visibilityState === "visible" && refresh();
document.addEventListener("visibilitychange", onVisible);

Events that happen while a device is disconnected aren't replayed to it. A tablet at the pass that sleeps for ten minutes would wake up showing the board from ten minutes ago. Reloading whenever the channel subscribes, which includes every reconnect, and whenever the screen becomes visible covers that case. Since every update is a full reload, there's never half-applied state to reconcile. A cafe's open tickets are a small query, so reloading is cheap.

Two Playwright tests hold this to account. One expects a new round on the staff board within two seconds of a guest placing it. The other takes the staff browser offline, places an order from a guest phone, brings the staff browser back, and expects the ticket to appear.

Keeping Phone Numbers Private

Guests can read their own tab, and the tab row holds the phone number given at checkout. Column-level grants hide it: clients can select every column of `tabs` except the phone number and guest name. Staff read the number through a function that checks they're staff.

Realtime applies the same column privileges to the payloads it sends. We checked that against the hosted project rather than trusting it, and the publication also lists only the safe columns of the members table, in case that behaviour ever changes.

The New-Order Chime

Browsers won't play sound until someone interacts with the page. Staff unlock audio as a side effect of typing their PIN, and after that a new round or bill request plays a two-note chime built with the Web Audio API and vibrates the device where that's supported. There's no audio file to load or cache.

Tests Against the Database

There are 135 tests in three layers. 56 unit tests cover money formatting, phone number handling, the cart and individual components. 40 database tests run against a real Supabase Postgres and call the functions as different people: a guest, a second guest at the same table, staff, and the admin. The races and permissions are tested there, with cases like "a guest cannot read another table's tab" and "concurrent confirm_payment records one payment". 39 Playwright tests drive a guest phone and a staff tablet as separate browser contexts through the whole loop: order, serve, request the bill, confirm, paid.

What We're Waiting to Learn

None of this has met a lunch rush yet. We want to see how the board holds up on the cafe's own Wi-Fi with a full room, whether reloading on every event stays quick when twenty tables are open, and which of the rules in the rules post staff end up working around. We'll update this post once there's something real to report.

The membership post covers the plans the owner added, which are built on the same functions. If you're building something with shared state like this, tell us about it.