Timed ticket hold
A hold is a row with an expiry, taken in one short transaction, never an open transaction waiting for payment. Expiry is lazy: a hold stops counting the moment it ends, with no job needed. The payment provider calls a webhook (signature checked, idempotent) that turns the hold into gapless ticket numbers; a payment that arrives late is flagged for refund instead of overselling.
Tested with many simultaneous buyers: holds, payments and delayed callbacks (including duplicates and late payments) never confirmed more tickets than the capacity, and ticket numbers had no gaps. The webhook secret in the schema is a placeholder: keep the real one in a secret store. One project, one environment: a correctness check, not a performance guarantee. See the Transactions docs.
Summer concert
$20.00 per ticket. 6 tickets left
Held for a short time so you can pay.
A hold is a row with an expiry, not an open transaction. The payment webhook confirms it; after the timer the tickets go back on sale on their own.
'use client'import { useEffect, useState } from 'react'import { createBrowserClient } from '@potalab/base/next'
const createBase = () => createBrowserClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.NEXT_PUBLIC_POTALAB_BASE_KEY! })
type Hold = { id: string; qty: number; status: string; expires_at: string }
export function Tickets({ eventId }: { eventId: number }) { const base = createBase() const [available, setAvailable] = useState<number | null>(null) const [holds, setHolds] = useState<Hold[]>([]) const [tickets, setTickets] = useState<{ number: number }[]>([]) const [now, setNow] = useState(() => Date.now()) const [message, setMessage] = useState('')
// One request, one consistent snapshot of my holds and tickets (RLS: only mine). async function load() { const r = await base.transaction((tx) => ({ holds: tx.from('tix_holds').select('id', 'qty', 'status', 'expires_at').eq('event_id', eventId).order('created_at', { ascending: false }), tickets: tx.from('tix_tickets').select('number').eq('event_id', eventId).order('number'), })) setHolds(r.of(r.value.holds).rows as Hold[]) setTickets(r.of(r.value.tickets).rows as { number: number }[]) const left = await base.rpc('tix_available', { p_event_id: eventId }) setAvailable(left.data as number) } useEffect(() => { void load() const t = setInterval(() => setNow(Date.now()), 1000) // countdown only; the server decides what is expired return () => clearInterval(t) }, [])
// A hold is a ROW with an expiry, taken in one short transaction (tix_hold). Nothing stays open afterwards. async function hold(qty: number) { const { error } = await base.rpc('tix_hold', { p_event_id: eventId, p_qty: qty, p_ttl_seconds: 600 }) if (error?.message?.includes('tix_sold_out')) setMessage('Not enough tickets left.') else if (error?.message?.includes('tix_user_limit')) setMessage('At most 4 tickets per person.') else if (error) throw error else setMessage('Held for 10 minutes. Pay before the timer ends.') await load() }
// Creates a pending payment intent (amount from the catalog). The provider calls our webhook when the money arrives. async function pay(holdId: string) { const { data, error } = await base.rpc('tix_start_payment', { p_hold_id: holdId }) if (error?.message?.includes('tix_hold_not_active')) setMessage('The hold expired. Tickets went back on sale.') else if (error) throw error else window.location.href = `https://pay.example.com/checkout/${(data as { provider_ref: string }).provider_ref}` await load() }
const left = (h: Hold) => Math.max(0, Math.round((Date.parse(h.expires_at) - now) / 1000)) return ( <section> <p>{available ?? '...'} tickets left</p> <button onClick={() => hold(2)}>Hold 2 tickets</button> <ul> {holds.map((h) => ( <li key={h.id}> {h.qty} tickets, {h.status === 'held' && left(h) > 0 ? `${left(h)} s left` : h.status === 'held' ? 'expired' : h.status} {h.status === 'held' && left(h) > 0 && <button onClick={() => pay(h.id)}>Pay</button>} </li> ))} </ul> {tickets.length > 0 && <p>Your tickets: {tickets.map((t) => `#${t.number}`).join(', ')}</p>} <p role="status">{message}</p> </section> )}// app/tickets/page.tsx (Server Component)import { redirect } from 'next/navigation'import { baseServer } from '@/lib/base-server'import { Tickets } from './Tickets'
export default async function TicketsPage() { const base = await baseServer() const { data: { user } } = await base.auth.getUser() if (!user) redirect('/login') // holds belong to a signed-in user (tix_hold reads auth.uid() itself)
const { data: events } = await base.from('tix_events').select('id,name,price').order('id').limit(1) const event = events?.[0] if (!event) return <p>No event on sale.</p>
return ( <main> <h1>{event.name}</h1> <p>${event.price} per ticket</p> <Tickets eventId={event.id} /> </main> )}// app/api/payments/webhook/route.ts (server only)// The payment provider calls this when money arrives. It is the ONLY thing that turns a hold into tickets.// The SQL function checks the HMAC signature over the exact bytes, is idempotent per provider event id, and, if the hold already// expired, does NOT confirm: the payment is flagged `refund_required` instead (capacity is never exceeded).import { createClient } from '@potalab/base'
const base = createClient({ url: process.env.NEXT_PUBLIC_POTALAB_BASE_URL!, key: process.env.POTALAB_BASE_SECRET_KEY!, // pb_sec_...: never ship it to a browser. The function is executable by service_role only.})
export async function POST(request: Request) { const body = await request.text() // the RAW body: the signature is over these exact bytes const signature = request.headers.get('x-signature') ?? '' const { data, error } = await base.rpc('tix_payment_webhook', { p_body: body, p_signature: signature }) if (error?.message?.includes('tix_bad_signature')) return new Response('bad signature', { status: 401 }) if (error) return new Response('retry later', { status: 500 }) // the provider redelivers; duplicates are harmless return Response.json(data) // { result: 'confirmed' | 'duplicate' | 'noop' | 'refund_required' | ... }}// 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)), }, })}-- A hold is a ROW with an expiry, not an open transaction. tix_hold() is one short transaction: lock the event row, count what is-- still taken (confirmed + held-and-not-expired), insert the hold, commit. Expiry is LAZY: a hold stops counting the moment-- expires_at passes; the job at the bottom only tidies the status. Money never confirms anything inside the hold request: the-- provider's webhook (tix_payment_webhook) is the only thing that turns a hold into tickets, atomically.create extension if not exists pgcrypto;
create table public.tix_events ( id bigint generated always as identity primary key, name text not null unique, capacity int not null check (capacity >= 0), price numeric(12,2) not null default 0 check (price >= 0), tickets_issued int not null default 0 check (tickets_issued >= 0) -- gapless counter, bumped inside the confirm transaction);
create table public.tix_holds ( id uuid primary key default gen_random_uuid(), event_id bigint not null references public.tix_events (id) on delete cascade, user_id uuid not null, qty int not null check (qty between 1 and 10), status text not null default 'held' check (status in ('held', 'confirmed', 'expired')), expires_at timestamptz not null, created_at timestamptz not null default now());
create sequence public.tix_receipt_seq; -- receipt numbers: unique and increasing, gaps are acceptable
create table public.tix_payments ( id uuid primary key default gen_random_uuid(), hold_id uuid not null references public.tix_holds (id) on delete cascade, user_id uuid not null, provider_ref text not null unique default ('pi_' || replace(gen_random_uuid()::text, '-', '')), amount numeric(12,2) not null check (amount >= 0), status text not null default 'pending' check (status in ('pending', 'succeeded', 'failed', 'refund_required', 'refunded')), receipt_no bigint unique);create unique index tix_payments_one_open on public.tix_payments (hold_id) where status in ('pending', 'succeeded');
create table public.tix_tickets ( event_id bigint not null references public.tix_events (id) on delete cascade, number int not null check (number > 0), hold_id uuid not null references public.tix_holds (id) on delete cascade, user_id uuid not null, primary key (event_id, number));
create table public.tix_webhook_events (provider_event_id text primary key, result text); -- idempotency key of the webhookcreate table public.tix_config (key text primary key, value text not null); -- the webhook secret: no API role can read itinsert into public.tix_config values ('webhook_secret', 'change-me');
-- Seats free right now. Expired holds count for nothing.create function public.tix_available(p_event_id bigint) returns intlanguage sql stable security definer set search_path = '' as $$ select e.capacity - coalesce((select sum(h.qty)::int from public.tix_holds h where h.event_id = e.id and (h.status = 'confirmed' or (h.status = 'held' and h.expires_at > clock_timestamp()))), 0) from public.tix_events e where e.id = p_event_id$$;
-- DEFINER because it must see everybody's holds; the owner is auth.uid(), never an argument.-- The event row lock serialises holds of ONE event for a few ms, which makes "available >= qty, then insert" atomic-- (a SUM cannot be written as a CHECK or EXCLUDE constraint).create function public.tix_hold(p_event_id bigint, p_qty int, p_ttl_seconds int default 600) returns public.tix_holdslanguage plpgsql security definer set search_path = '' as $$declare v_uid uuid := auth.uid(); v_avail int; v_hold public.tix_holds;begin if v_uid is null then raise exception 'tix_not_signed_in' using errcode = '28000'; end if; if p_qty not between 1 and 10 or p_ttl_seconds not between 1 and 900 then raise exception 'tix_bad_argument' using errcode = '22023'; end if; perform 1 from public.tix_events where id = p_event_id for update; if not found then raise exception 'tix_unknown_event' using errcode = '23503'; end if; v_avail := public.tix_available(p_event_id); if p_qty > v_avail then raise exception 'tix_sold_out: wanted %, available %', p_qty, v_avail using errcode = 'P0001'; end if; if p_qty + coalesce((select sum(h.qty) from public.tix_holds h where h.event_id = p_event_id and h.user_id = v_uid and (h.status = 'confirmed' or (h.status = 'held' and h.expires_at > clock_timestamp()))), 0) > 4 then raise exception 'tix_user_limit: at most 4 tickets per person' using errcode = 'P0001'; end if; insert into public.tix_holds (event_id, user_id, qty, expires_at) values (p_event_id, v_uid, p_qty, clock_timestamp() + make_interval(secs => p_ttl_seconds)) returning * into v_hold; return v_hold;end $$;
-- Pending payment intent for an own, still active hold. The amount comes from the catalog. Idempotent.create function public.tix_start_payment(p_hold_id uuid) returns public.tix_paymentslanguage plpgsql security definer set search_path = '' as $$declare v_uid uuid := auth.uid(); v_hold public.tix_holds; v_pay public.tix_payments;begin select * into v_hold from public.tix_holds where id = p_hold_id and user_id = v_uid; if not found then raise exception 'tix_hold_not_found' using errcode = 'P0002'; end if; if v_hold.status <> 'held' or v_hold.expires_at <= clock_timestamp() then raise exception 'tix_hold_not_active' using errcode = 'P0001'; end if; select * into v_pay from public.tix_payments where hold_id = p_hold_id and status in ('pending', 'succeeded'); if found then return v_pay; end if; insert into public.tix_payments (hold_id, user_id, amount) select p_hold_id, v_uid, e.price * v_hold.qty from public.tix_events e where e.id = v_hold.event_id returning * into v_pay; return v_pay;end $$;
-- The provider's callback (service_role only). p_body is the RAW body, p_signature its hex HMAC-SHA256.-- Lock order everywhere: payment -> event -> hold, so a callback never deadlocks with tix_hold or the job.create function public.tix_payment_webhook(p_body text, p_signature text) returns jsonblanguage plpgsql security definer set search_path = '' as $$declare v_json jsonb; v_pay public.tix_payments; v_hold public.tix_holds; v_last int; v_new int; v_secret text := (select value from public.tix_config where key = 'webhook_secret');begin if lower(coalesce(p_signature, '')) <> encode(public.hmac(convert_to(coalesce(p_body, ''), 'utf8'), convert_to(v_secret, 'utf8'), 'sha256'), 'hex') then raise exception 'tix_bad_signature' using errcode = '28000'; end if; v_json := p_body::jsonb; -- {"id": "evt_...", "type": "payment.succeeded", "provider_ref": "pi_...", "amount": 40.00} insert into public.tix_webhook_events (provider_event_id) values (v_json ->> 'id') on conflict do nothing; get diagnostics v_new = row_count; if v_new = 0 then return jsonb_build_object('result', 'duplicate'); end if; -- same provider event delivered again
select * into v_pay from public.tix_payments where provider_ref = v_json ->> 'provider_ref' for update; if not found or v_pay.status <> 'pending' then return jsonb_build_object('result', 'noop'); end if; if v_json ->> 'type' = 'payment.failed' then update public.tix_payments set status = 'failed' where id = v_pay.id; return jsonb_build_object('result', 'failed_recorded'); end if; perform 1 from public.tix_events where id = (select event_id from public.tix_holds where id = v_pay.hold_id) for update; select * into v_hold from public.tix_holds where id = v_pay.hold_id for update;
if (v_json ->> 'amount')::numeric = v_pay.amount and v_hold.status = 'held' and v_hold.expires_at > clock_timestamp() then -- atomic confirm: hold -> confirmed, gapless ticket numbers from the event counter, receipt number from the sequence update public.tix_holds set status = 'confirmed' where id = v_hold.id; update public.tix_events set tickets_issued = tickets_issued + v_hold.qty where id = v_hold.event_id returning tickets_issued into v_last; insert into public.tix_tickets (event_id, number, hold_id, user_id) select v_hold.event_id, n, v_hold.id, v_hold.user_id from generate_series(v_last - v_hold.qty + 1, v_last) n; update public.tix_payments set status = 'succeeded', receipt_no = nextval('public.tix_receipt_seq') where id = v_pay.id; return jsonb_build_object('result', 'confirmed', 'first_ticket', v_last - v_hold.qty + 1, 'last_ticket', v_last); end if; -- the money arrived but the hold is gone (or the amount is wrong): never confirm past capacity, flag it for a refund update public.tix_payments set status = 'refund_required' where id = v_pay.id; return jsonb_build_object('result', 'refund_required');end $$;
-- Cleanup job, e.g. select cron.schedule('tix-release', '* * * * *', 'select public.tix_release_expired()'). Correctness never depends on it.create function public.tix_release_expired() returns intlanguage sql security invoker set search_path = '' as $$ with u as (update public.tix_holds set status = 'expired' where status = 'held' and expires_at <= clock_timestamp() returning 1) select count(*)::int from u$$;
alter table public.tix_events enable row level security;alter table public.tix_holds enable row level security;alter table public.tix_payments enable row level security;alter table public.tix_tickets enable row level security;alter table public.tix_webhook_events enable row level security;alter table public.tix_config enable row level security;create policy tix_events_read on public.tix_events for select to authenticated using (true);create policy tix_holds_read on public.tix_holds for select to authenticated using (user_id = (select auth.uid()));create policy tix_payments_read on public.tix_payments for select to authenticated using (user_id = (select auth.uid()));create policy tix_tickets_read on public.tix_tickets for select to authenticated using (user_id = (select auth.uid()));
-- Clients can only SELECT their own rows. The only ways to write are the functions below.revoke all on public.tix_events, public.tix_holds, public.tix_payments, public.tix_tickets, public.tix_webhook_events, public.tix_config from anon, authenticated;grant select (id, name, capacity, price) on public.tix_events to authenticated;grant select on public.tix_holds, public.tix_payments, public.tix_tickets to authenticated;revoke all on function public.tix_available(bigint), public.tix_hold(bigint, int, int), public.tix_start_payment(uuid), public.tix_payment_webhook(text, text), public.tix_release_expired() from public;grant execute on function public.tix_available(bigint), public.tix_hold(bigint, int, int), public.tix_start_payment(uuid) to authenticated;grant execute on function public.tix_payment_webhook(text, text), public.tix_release_expired() to service_role;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.