PotaLab
← All examples
SnippetTransactionsData APIRLSNext.js

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.

localhost:3000/rooms

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.

Preview · sample data
'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>
)
}

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 →