Meeting room booking
Two people book the same slot at the same instant: the database lets one commit and answers the other with 409 (23P01), so the UI says "slot taken". A booking and its attendees are one base.transaction(); moving a booking cancels the old one and books the new one, or does neither (.expect and .when). The calendar is a view that shows when a room is taken, never who booked it.
Tested through the SDK with many simultaneous users over several rooms: no overlapping booking was ever stored, and every loser got a clean 409. Without the per-room advisory lock in the schema, the same test also produced deadlocks (40P01) and lock timeouts (55P03): still no overlap, but a less friendly error. One project, one environment: a correctness check, not a performance guarantee. See the Transactions docs.
Meeting rooms
Today. Signed in as ann@acme.com
Room A (8 seats)
Room B (12 seats)
My bookings
- None yet. Pick a free slot.
No double booking is an EXCLUDE constraint. Whoever comes second gets 409 / 23P01. Moving a booking is one transaction: cancel + book, or neither.
'use client'import { useState } from 'react'import { createBrowserClient } from '@potalab/base/next'import { TransactionError } from '@potalab/base'import { useQuery } from '@potalab/base/react'
const createBase = () => createBrowserClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY! })
// Half-open range [start, end): 9:00-10:00 and 10:00-11:00 never conflict.const hh = (h: number) => String(h).padStart(2, '0')const slot = (day: string, from: number, to: number) => `[${day}T${hh(from)}:00:00Z,${day}T${hh(to)}:00:00Z)`
export function Booking({ day }: { day: string }) { const base = createBase() const [message, setMessage] = useState('') const rooms = useQuery(base.from('mrb_rooms').select('id,name,capacity').order('id')) // The shared calendar is a view: everybody sees WHEN a room is taken, only the owner sees who and why. const schedule = useQuery(base.from('mrb_room_schedule').select('id,room_id,during,mine')) const mine = useQuery(base.from('mrb_bookings').select('id,room_id,during,title').eq('status', 'booked')) const refresh = () => Promise.all([schedule.refetch(), mine.refetch()])
async function book(roomId: number, from: number, to: number, attendeeIds: string[] = []) { try { // One request, one Postgres transaction: the booking and its attendees exist together or not at all. await base.transaction( (tx) => { const b = tx.from('mrb_bookings').insert({ room_id: roomId, title: 'Planning', during: slot(day, from, to) }).returning('id') // user_id = auth.uid() for (const user_id of attendeeIds) tx.from('mrb_attendees').insert({ booking_id: b.ref('id'), user_id }) }, { retry: 2 }, // a deadlock or lock timeout rolled everything back: resending is safe ) setMessage('Booked.') } catch (e) { // The EXCLUDE constraint is the rule; the database answers 409 / 23P01 to whoever came second. if (e instanceof TransactionError && e.pgCode === '23P01') setMessage('That slot was just taken. Pick another.') else throw e } await refresh() }
// Move a booking: cancel the old one and book the new one, or do neither. async function move(bookingId: string, roomId: number, from: number, to: number) { try { await base.transaction((tx) => { const old = tx.from('mrb_bookings').update({ status: 'cancelled' }).eq('id', bookingId).eq('status', 'booked').expect({ affected: 1 }) tx.from('mrb_bookings').insert({ room_id: roomId, title: 'Planning', during: slot(day, from, to) }).when(old, { exists: true }) }) setMessage('Moved.') } catch (e) { if (e instanceof TransactionError && e.pgCode === '23P01') setMessage('The new slot is taken. Your booking is unchanged.') else if (e instanceof TransactionError && e.pgCode === 'BT409') setMessage('That booking is no longer active.') else throw e } await refresh() }
async function cancel(bookingId: string) { try { // expect: the booking must exist, be yours (RLS) and still be booked; otherwise nothing happens and you are told. await base.transaction((tx) => { tx.from('mrb_bookings').update({ status: 'cancelled' }).eq('id', bookingId).eq('status', 'booked').expect({ affected: 1 }) }) setMessage('Cancelled.') } catch (e) { if (e instanceof TransactionError && e.pgCode === 'BT409') setMessage('Already cancelled.') else throw e } await refresh() }
return ( <section> {rooms.data?.map((room) => ( <article key={room.id}> <h2> {room.name} ({room.capacity} seats) </h2> {[9, 10, 11, 13, 14].map((h) => { const taken = schedule.data?.some((b) => b.room_id === room.id && String(b.during).includes(`T${hh(h)}:00:00`)) return ( <button key={h} disabled={taken} onClick={() => book(room.id, h, h + 1)}> {h}:00{taken ? ' (taken)' : ''} </button> ) })} </article> ))} <h3>My bookings</h3> <ul> {mine.data?.map((b) => ( <li key={b.id}> {b.title} <button onClick={() => cancel(b.id)}>Cancel</button> <button onClick={() => move(b.id, b.room_id, 15, 16)}>Move to 15:00</button> </li> ))} </ul> <p role="status">{message}</p> </section> )}// app/rooms/page.tsx (Server Component)import { redirect } from 'next/navigation'import { baseServer } from '@/lib/base-server'import { Booking } from './Booking'
export default async function RoomsPage() { const base = await baseServer() const { data: { user } } = await base.auth.getUser() if (!user) redirect('/login') // bookings belong to a signed-in user (RLS: user_id = auth.uid())
const day = new Date().toISOString().slice(0, 10) return ( <main> <h1>Meeting rooms</h1> <Booking day={day} /> </main> )}// lib/base-server.ts// One client PER REQUEST: it holds the signed-in user's session.import { cookies } from 'next/headers'import { createServerClient } from '@potalab/base/next'
export async function baseServer() { const store = await cookies() return createServerClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY!, // pb_pub_... cookies: { getAll: () => store.getAll(), setAll: (list) => list.forEach((c) => store.set(c.name, c.value, c.options)), }, })}-- "No two active bookings of one room overlap" is a DATABASE CONSTRAINT, not application code and not a long transaction.-- Two concurrent inserts for overlapping slots: one commits, the other waits for it and then fails with 23P01 (HTTP 409).create extension if not exists btree_gist;
create table public.mrb_rooms ( id bigint generated always as identity primary key, name text not null unique, capacity int not null check (capacity > 0));
create table public.mrb_bookings ( id uuid primary key default gen_random_uuid(), room_id bigint not null references public.mrb_rooms (id) on delete cascade, user_id uuid not null default auth.uid(), title text not null default '' check (length(title) <= 200), during tstzrange not null, status text not null default 'booked' check (status in ('booked', 'cancelled')), created_at timestamptz not null default now(), -- half-open [start, end), bounded, at most 8 hours: adjacent slots never conflict constraint mrb_during_shape check ( not isempty(during) and lower_inc(during) and not upper_inc(during) and lower(during) is not null and upper(during) is not null and upper(during) - lower(during) <= interval '8 hours'), -- THE anti double booking rule. Cancelled bookings drop out of the index, so the slot can be booked again. constraint mrb_no_overlap exclude using gist (room_id with =, during with &&) where (status <> 'cancelled'));
create table public.mrb_attendees ( booking_id uuid not null references public.mrb_bookings (id) on delete cascade, user_id uuid not null, primary key (booking_id, user_id));
-- Serialise concurrent inserts per room. Without it, two parallel inserts of overlapping ranges can deadlock (40P01) or time out-- (55P03) before the clean 23P01 is reached. Nothing wrong is ever stored either way; this only gives the loser the clean error.-- A transaction that books SEVERAL rooms should send the inserts ordered by room_id.create function public.mrb_room_lock() returns trigger language plpgsql security invoker set search_path = '' as $$begin perform pg_advisory_xact_lock(hashtextextended('mrb_room:' || new.room_id::text, 0)); return new;end $$;create trigger mrb_room_lock before insert on public.mrb_bookings for each row execute function public.mrb_room_lock();
-- A client may only cancel (booked -> cancelled); nothing else about a booking changes. Admin roles are unrestricted.create function public.mrb_booking_guard() returns trigger language plpgsql security invoker set search_path = '' as $$begin if current_user not in ('anon', 'authenticated') then return new; end if; if new.id is distinct from old.id or new.room_id is distinct from old.room_id or new.user_id is distinct from old.user_id or new.during is distinct from old.during or new.title is distinct from old.title or new.created_at is distinct from old.created_at then raise exception 'booking columns are immutable' using errcode = '42501'; end if; if old.status <> 'booked' or new.status <> 'cancelled' then raise exception 'a booking can only go from booked to cancelled' using errcode = '42501'; end if; return new;end $$;create trigger mrb_booking_guard before update on public.mrb_bookings for each row execute function public.mrb_booking_guard();
-- The shared calendar: WHEN a room is taken, never WHO or why. The view runs with the owner's rights on purpose (it bypasses the-- RLS of mrb_bookings); auth.uid() still comes from the request's JWT.create view public.mrb_room_schedule as select b.id, b.room_id, b.during, (b.user_id = auth.uid()) as mine from public.mrb_bookings b where b.status <> 'cancelled';
alter table public.mrb_rooms enable row level security;alter table public.mrb_bookings enable row level security;alter table public.mrb_attendees enable row level security;
create policy mrb_rooms_read on public.mrb_rooms for select to authenticated using (true);create policy mrb_bookings_select on public.mrb_bookings for select to authenticated using (user_id = (select auth.uid()));create policy mrb_bookings_insert on public.mrb_bookings for insert to authenticated with check (user_id = (select auth.uid()));create policy mrb_bookings_update on public.mrb_bookings for update to authenticated using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));create policy mrb_attendees_select on public.mrb_attendees for select to authenticated using (user_id = (select auth.uid()) or exists (select 1 from public.mrb_bookings b where b.id = booking_id and b.user_id = (select auth.uid())));create policy mrb_attendees_insert on public.mrb_attendees for insert to authenticated with check (exists (select 1 from public.mrb_bookings b where b.id = booking_id and b.user_id = (select auth.uid())));
revoke all on public.mrb_rooms, public.mrb_bookings, public.mrb_attendees, public.mrb_room_schedule from anon, authenticated;grant select on public.mrb_rooms, public.mrb_room_schedule, public.mrb_bookings, public.mrb_attendees to authenticated;grant insert (room_id, user_id, title, during) on public.mrb_bookings to authenticated;grant update (status) on public.mrb_bookings to authenticated;grant insert on public.mrb_attendees to authenticated;Snippet for illustration, written for the Next.js App Router with @potalab/base/next,@potalab/base/react and @potalab/base. Set NEXT_PUBLIC_POTALAB_BASE_URL andNEXT_PUBLIC_POTALAB_BASE_KEY, adapt names and redirect URLs, and review policies before production.
Next: Timed ticket hold →