Domain rules in Postgres: RLS for auth, RPCs as the API

Reserrva7 min read

On this page · 10 sections

Reserrva has three kinds of client: a Next.js web app, an Expo app for business owners and AI agents that connect through an MCP server. They read the same data and change it through the same functions, although not every client offers every operation. If each one carried its own copy of the rules for booking, cancelling or computing free slots, they would drift apart within weeks.

So the rules live in Postgres. Row level security decides which rows a caller can reach, Postgres functions decide which changes are legal, and the clients validate input, call a function and render the result. Here is how that works and what it costs.

This post is published by Reserrva and describes how Reserrva is built. The button below books a free call with Alejandro Mena, its founder.

Why the rules belong in the database

Our first architecture decision says Postgres owns domain transitions: availability, booking, cancellation, quotes, invitations and membership changes are transactional functions, and web, mobile and agents are adapters. Shared zod schemas check the shape of input. Postgres enforces authorisation, eligibility, prices and concurrency, including for calls that bypass our apps entirely.

That last part matters. A user's session token works against the database API directly, so the only rules that hold for every caller are the ones the database enforces. The clearest example is double booking. It is not prevented by an availability check in TypeScript but by a constraint on the appointments table, simplified here:

alter table appointments add constraint no_double_booking
  exclude using gist (staff_id with =, period with &&)
  where (status in ('pending', 'confirmed'));

Two live appointments for the same professional cannot overlap, whichever code path inserts them. Our smoke test checks this over a privileged database connection too, with a raw insert that skips every function, and expects the constraint to refuse it.

Tell Alejandro about your project

A free 15 or 30 minute video call with Alejandro Mena, developer. You pick the time and no account is needed.

Book a call

RLS decides rows; functions decide transitions

The row level security migration starts with a few principles. The public sees only what a booking page needs. Members see their business. Owners and admins change it, and staff change their own rows. Customers see their own appointments, requests and payments. Money tables are read-only for everyone except the server.

We learned that a row match is not enough. If a member can update a business row, RLS alone lets them update every column of it, including billing fields. So our second decision says each field has its own authority, and changes to booking state, prices or membership go through functions instead of plain updates. Our smoke test checks, for example, that an owner cannot move their own business into a billing-controlled state or flip a billing flag with a direct update.

The functions follow one pattern. They run with the definer's rights, set an empty search path, grant execute only to the roles that need it, and check authorisation inside the function body. When we added AI agents, we did not loosen any policy. We added restrictive policies for tokens issued to an OAuth client on the tables that hold a business's private data, leaving public and customer-scoped reads available, and a guard in each business-side function. Restrictive policies are combined with AND, so they also cover any permissive policy added later. The details are in how we built the MCP server.

Errors are a versioned contract

Functions raise stable codes, not sentences: slot_unavailable, too_late_to_cancel, offer_changed. The public list lives in our database package and has more than a hundred entries. The web and the mobile app map each code to copy in Spanish and English, and never show a raw Postgres error.

A second list holds internal codes that only a background worker reads. A test scans every migration and fails when a function raises a code with no recorded disposition, so a new code cannot ship without someone deciding how it is handled.

Money, time and snapshots

RuleHow it is stored
MoneyInteger cents, with the currency taken from the business
Instantstimestamptz, rendered in the business's time zone on business screens and the device's on customer screens
Opening hours and schedulesLocal time values, interpreted in the business's time zone
Past bookingsService name, price and duration copied onto the appointment at booking

The snapshot rule means a business can raise a price tomorrow without rewriting what a customer paid last month. On the public booking page we go one step further: the page sends back a database-generated fingerprint of the offer that was on screen, and the booking function refuses with offer_changed if the price or duration moved after the customer saw it.

Where the service role is allowed

Browsers and the mobile app use the public key with the user's session. The service role key, which bypasses RLS, is limited to server code with a stated purpose: Stripe webhooks, push notification fan-out, scheduled jobs and signed links for private uploads, among others. Each purpose is named in our project instructions or architecture decisions. The MCP server uses it for one thing, its rate-limit counter. It never ships in a client bundle.

How we test it

pnpm db:smoke is a contract test that runs against a real database. It creates throwaway users and businesses and then acts as each of them by setting the JWT claims and the role inside a transaction, so RLS and auth.uid() behave as they would for a real request. It asserts results and error codes: a customer books a slot, the same slot is refused, the buffer after a service is respected, an agent's booking carries its client id, a customer cannot rename a business.

Next to it sit roughly a hundred narrower contract scripts, and a disposable local stack that replays every migration from scratch. Our engineering standards ask for a fresh replay and real-role tests, positive and negative, for any change to SQL, RLS or functions.

Append-only migrations

A merged migration is never edited. A change is a new file, and the TypeScript types are generated from the migrated database, never written by hand. The repository has well over 150 migrations. In one recent pull request a comment-only edit to a merged migration was flagged in the description as breaking the rule and left for reviewers to judge, which is how the rule is meant to work.

The honest costs

  • SQL is harder to review. Changing one line of a function means a migration that re-creates the whole function, and the diff shows a new file, not the line.
  • Refactoring is slow. Renaming a concept touches functions, policies, generated types and every caller.
  • Migrations are forever. A mistake gets fixed forward, in another file.
  • The local stack is heavy. Replaying everything needs a running Supabase stack, and ours runs on one machine.
  • Coverage has gaps. Our standards still list integration tests through the HTTP API, auth and realtime as work to add.

We accept those costs because the alternative was three versions of the booking rules. How we get the code written and reviewed is in our multi-model coding workflow, and the agent side, as an owner sees it, is in the guide on letting an AI agent book into your agenda.

Frequently asked questions

Can you build an app on Supabase without a separate backend?

For the domain rules, yes: Reserrva keeps them in Postgres functions and RLS. It still runs server code for webhooks, notifications, scheduled jobs and other named purposes that need the service role.

Is row level security enough for authorisation?

Not on its own. RLS decides which rows a caller reaches, but not which columns or state changes are legal, so Reserrva routes those changes through functions that check them.

How does Reserrva prevent double bookings?

With an exclusion constraint on the appointments table, so two live appointments for the same professional cannot overlap whichever code inserts them.

How do clients handle errors from Postgres functions?

Functions raise stable codes from a shared list, and each client maps them to its own copy in Spanish and English. Raw Postgres errors are never shown.

Where this comes from

This post is based on Reserrva's repository: the project instructions, the architecture decisions, the migrations, the database package and the smoke test. Reserrva published it. If you are weighing this architecture for your own product, Alejandro Mena offers free 15- and 30-minute video calls every day from 10:00 to 23:00 CET, booked online without an account.

Start with a call

Thirty minutes, free and with no commitment, to work out what you need and where to start.

Book a call

Commercial relationship: Reserrva publishes this guide, and Alejandro Mena is Reserrva's founder.