Payments and long-running steps
A payment takes seconds to minutes. A database transaction should not wait that long: it holds a connection and locks, and it dies with timeouts and restarts (an interactive transaction lasts at most 10 s anyway). Instead, split the work into short transactions connected by rows that record where you are. This is a saga: each step is its own commit, and a failed or late step is undone by a compensating step, not by a rollback.
This is a pattern you build with tables and functions, not a built-in feature. The timed hold example is a complete, tested version (event tickets with a 10 minute hold).
The steps
Section titled “The steps”- Reserve. One short transaction checks availability and inserts a
holdsrow withexpires_at = now() + interval '10 minutes'. After the commit nothing stays open or locked. - Start payment. Create a
pendingpayment for the hold. Compute the amount on the server from your catalog, never from the client, and make the call idempotent. The customer then pays at the provider. - Confirm from the callback. The provider calls your endpoint. It verifies the signature and, in one transaction, marks the hold
confirmed, the paymentsucceeded, and issues what was bought. - Release or compensate. A hold past
expires_atfrees its units. A payment that arrives after that is not confirmed: mark itrefund_requiredand refund it.
Every step is idempotent, because providers retry callbacks and clients retry requests.
Make expiry correct without a job
Section titled “Make expiry correct without a job”Put the expiry in every count: units available = capacity - confirmed - holds that are not expired.
select capacity - coalesce(sum(qty) filter (where status = 'confirmed'), 0) - coalesce(sum(qty) filter (where status = 'held' and expires_at > clock_timestamp()), 0) from public.events e left join public.holds h on h.event_id = e.id where e.id = $1 group by e.id;The moment a hold expires its units are free again, even if no job has run. A scheduled job that sets status = 'expired' only tidies the data; correctness never depends on it.
To keep “available >= qty, then insert” atomic when a sum is involved (a CHECK cannot express it), lock one parent row, such as the event, inside the reserve function for those few milliseconds.
An idempotent callback
Section titled “An idempotent callback”Run the callback in an Edge Function whose auth mode is public, because the provider has no user token. Verify the provider’s signature over the raw body before anything else, then call a database function that only service_role can execute (the function setting allow_service_role gives the function ctx.admin).
create table public.payment_events (event_id text primary key);
create function public.confirm_payment(p_event_id text, p_payment_id uuid, p_amount int)returns text language plpgsql security definer set search_path = '' as $$begin insert into public.payment_events (event_id) values (p_event_id) on conflict do nothing; if not found then return 'duplicate'; end if; -- same provider event again
update public.payments set status = 'succeeded' where id = p_payment_id and status = 'pending' and amount = p_amount; if not found then return 'noop'; end if; -- already settled, or amount mismatch -- confirm the hold only if it has not expired; otherwise set status = 'refund_required' return 'confirmed';end $$;
revoke execute on function public.confirm_payment(text, uuid, int) from public, anon, authenticated;grant execute on function public.confirm_payment(text, uuid, int) to service_role;Ten parallel deliveries of the same event confirm once. Keep the signing secret out of tables an API role can read.
Rules that keep it safe
Section titled “Rules that keep it safe”- Numbers. Ticket or seat numbers that must not skip are incremented in the same transaction that confirms; a rollback undoes both. A sequence is faster but not gap-free, which is fine for receipt numbers where only uniqueness matters.
- Late payment. Decide the policy up front. The example refunds a late payment even when the units happen to be free again, because reviving the hold is a product decision and a race.
- Hoarding. Cap the quantity, the hold time and the holds per user, and add rate limits or a captcha before the reserve call.
- Definer functions. Functions that must see everybody’s holds run as
SECURITY DEFINERwithset search_path = ''and read the user fromauth.uid(), never from an argument. The one-requestbase.transaction()refuses definer functions, so call them withbase.rpc(): one call is already one transaction.