DEV Community

Yassine Khattari
Yassine Khattari

Posted on

4 bugs readers found in my Postgres booking trigger (and how I fixed them)

A few weeks ago I wrote about preventing double bookings in Postgres with advisory locks, and recorded a short video where I test it live with two concurrent requests:

Readers reviewed the code, and reviewing it myself again turned up more. This post lists four real problems, what each one looked like, and the fix. If you build booking or checkout flows, you may have the same bugs.

Bug 1: the trigger ran with the wrong privileges

My first snippet was a plain trigger function. A trigger function runs with the privileges of the user doing the insert. With Row Level Security on, that user may only see their own rows, so count(*) could miss other people's bookings and the check would pass when it should not.

Fix: run the function as its owner, with a fixed search_path and qualified table names.

sql
CREATE OR REPLACE FUNCTION public.check_booking_availability()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $$
-- ... lock, then count overlapping rows from public.bookings ...
$$;

On Supabase the owner is postgres, which has BYPASSRLS. I verified this with a query on pg_proc and pg_roles instead of assuming it.

Bug 2: the trigger only fired on INSERT

This one is subtle. A BEFORE INSERT trigger checks new bookings, but nothing checks the UPDATE that confirms one.

Client A starts paying. Their booking is pending with a hold.
The hold expires while A is still on the payment page.
Client B books the freed slot.
A's payment webhook arrives and sets A to confirmed.

Both rows end up confirmed for the same slot, with no error. The same happens if an admin moves a booking to another time.

Fix: fire the same function on UPDATE, and exclude the row itself from the overlap query.

sql
-- in the overlap query
AND b.id IS DISTINCT FROM NEW.id

CREATE TRIGGER bookings_check_availability
BEFORE INSERT OR UPDATE OF status, staff_id, booking_date, start_time, end_time
ON public.bookings
FOR EACH ROW
WHEN (NEW.status IN ('pending', 'confirmed'))
EXECUTE FUNCTION public.check_booking_availability();

Now A's late confirmation raises "This time slot is no longer available".

Bug 3: the webhook ignored the error

Fixing the trigger created a new question: what does the Stripe webhook do when that exception fires?

A reader (Sunnatulla) pointed me at the webhook, so I opened my handler. It updated the booking with supabase-js, which does not throw on a database error. It returns { error }, and I was not checking it. So the handler returned 200 OK, the payment stayed paid, the booking stayed pending, and nothing retried. The client would have been charged for a slot they did not get, silently.

Bug 4: an update that matches zero rows looks like a success

The same handler had a second hole. Say the client or an admin cancels the pending booking while the Stripe page is still open, and then the payment goes through. My update was .eq("status", "pending"), which now matches nothing, and the library reports that as success. Same outcome: charged, no booking.

The fix for both: ask for the updated rows back, and treat every outcome on purpose.

ts
const { data: updated, error } = await supabaseAdmin
.from("bookings")
.update({ status: "confirmed", hold_expires_at: null })
.eq("id", bookingId)
.eq("status", "pending")
.select("id"); // ask for the updated rows back

if (error) {
// 23P01 is what the trigger raises for a slot conflict
return error.code === "23P01" ? refund() : retryLater(); // 500: Stripe retries
}

if (updated.length === 0) {
// matched nothing: already confirmed (a Stripe retry) or cancelled meanwhile
const { data: row } = await supabaseAdmin
.from("bookings").select("status").eq("id", bookingId).maybeSingle();
return row?.status === "confirmed" ? ok() : refund();
}

(refund(), retryLater() and ok() are placeholders for your own responses.)

Three details that matter:

Keep the "already confirmed" branch. Stripe retries events. Without it, a retry of an event you already handled looks like a failure, and you would refund a booking that is fine.
Refund with an idempotency key (idempotencyKey: "booking-unavailable-refund-" + paymentId), so a retried event cannot refund twice.
Match the error code, not the message. message.includes("no longer available") breaks quietly the day someone rewords the exception. Raise the conflict with a stable SQLSTATE and match error.code:
sql
RAISE EXCEPTION 'This time slot is no longer available'
USING ERRCODE = 'exclusion_violation'; -- SQLSTATE 23P01

I moved the decision into a small pure function and unit-tested the cases: conflict, zero rows, already confirmed, cancelled, unreadable status. I have not run the full flow against Stripe yet, so test it in Stripe test mode before you rely on it.

What I would take from this
Test the race, then test the edges around it. My first test only covered two inserts. The bugs lived in updates and in the code around the trigger.
Check how your client library reports errors. If it returns { error }, an unchecked call fails silently.
Zero rows is not an error, and not a success either. Ask for the rows back and decide what each result means.
Match error codes, not messages.
Decide what "handled" means for webhooks. Return 200 only when the situation is really dealt with. Return 500 when you want a retry.
Public code review is useful. Readers pointed me at the places I had not looked, and the bugs above came out of that.

If you want to see the whole thing running, the full booking engine (with these fixes) is available as a source-code starter kit. It is $99 one-time, and the known limits are listed on the page: Stripe is test mode only, the Moroccan CMI gateway is a mock, and the refund path is unit-tested but not yet run end to end against Stripe.

Details and live demo: https://grow-roots-landing.vercel.app/?ref=devto2
Free repo with the SQL and a concurrency test script (MIT): https://github.com/Yassineai1/postgres-double-booking-demo
First article: https://dev.to/yassine_khattari_3cb9d27d/how-i-prevent-double-bookings-in-postgres-advisory-locks-supabase-11dl

What bugs did your booking or checkout code have that you only found later?

Top comments (9)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

Glad the webhook check was useful. One more case in the zero-rows branch: if the user opens checkout twice for the same pending booking, both payments can succeed, and the second one sees status confirmed and returns ok(), so they get charged twice. Saving the payment intent id on confirm and comparing it there would catch that.

Collapse
 
yassine_khattari_3cb9d27d profile image
Yassine Khattari •

You're right, and I confirmed it in my code: each checkout creates its own payment row, so a second successful payment for the same booking hits the zero-rows branch, sees confirmed, and returns 200 without a refund. I'm going to store the confirming payment id on the booking and compare it there: same id means a Stripe retry, a different id means refund. I'll also stop a second checkout being created while one is pending. Thanks for catching it.

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

One catch with blocking a second checkout: a Stripe Checkout session stays open for 24 hours by default, so a user who closed the tab is locked out of that booking for a day. Setting expires_at to 30 minutes, or expiring the old session before you create a new one, keeps that window short.

Thread Thread
 
yassine_khattari_3cb9d27d profile image
Yassine Khattari •

Fair point, and the 24-hour default was a real issue in my code. Two things: opening a new checkout now expires the previous session first (and only refuses if that session is already complete), so a closed tab does not lock the booking. I also set expires_at to 30 minutes, which is Stripe's minimum, so an abandoned session cannot be paid long after the 15-minute hold ended. I have unit tests for the decision logic but have not run the session expiry against real Stripe in test mode yet.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

A zero-rows update that looks like success hides a double charge, and the webhook returning 200 for a booking it never handled is how it gets there.

Collapse
 
yassine_khattari_3cb9d27d profile image
Yassine Khattari •

Exactly. The zero-rows update said "success", the webhook answered 200 for a payment it had not really handled, and nothing was left to retry or refund. Two things closed it for me: the handler now stores which payment confirmed the booking (confirmed_payment_id) and compares it, so a retry of the same payment returns 200 and a second payment gets refunded. And opening a new checkout now closes the previous one first. One caveat: this is covered by unit tests, but I have not run the refund against real Stripe in test mode yet, so I would not call it proven until I do.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

Storing which payment confirmed the booking is the fix. The untested refund is the honest caveat. Run it in test mode before calling it proven.

Thread Thread
 
yassine_khattari_3cb9d27d profile image
Yassine Khattari •

Agreed. I'll run it in Stripe test mode (a normal payment, a duplicate payment on the same booking, a replayed event, and the session expiry) and post what actually happens, including anything that fails.

Thread Thread
 
robertpaschal profile image
Odinaka Robert Nnamani •

The replayed event is the one I'm most curious about. Post the numbers when they land.