DEV Community

Yassine Khattari
Yassine Khattari

Posted on

5 bugs readers found in my Postgres booking trigger and Stripe webhook (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 five 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.

Bug 5: two payments for one booking

After I published the fix above, another reader found a hole in the "already confirmed" branch. If a client opens checkout twice for the same pending booking and pays in both, the first payment confirms the booking. The second one matches zero rows, sees confirmed, and my handler answers 200 as if it were a Stripe retry. The client is charged twice.

The status alone cannot tell a retry of the same payment from a second payment. So the booking has to remember which payment confirmed it:

sql
ALTER TABLE public.bookings
ADD COLUMN confirmed_payment_id uuid REFERENCES public.payments(id) ON DELETE SET NULL;
ts
.update({ status: "confirmed", hold_expires_at: null, confirmed_payment_id: paymentId })

In the zero-rows branch I now read status and confirmed_payment_id together:

same payment id: a Stripe retry, answer 200
different payment id: a duplicate payment, refund it and keep the booking

Two details:

A signed-in client can update their own booking under RLS, so I added a trigger that rejects writes to confirmed_payment_id from the anon and authenticated roles.
I also close the old checkout before opening a new one for the same booking. With Stripe that means expiring the open Checkout Session, and refusing the retry if the session is already complete. A reader also pointed out that a Checkout Session stays open for 24 hours by default, long after my 15-minute hold, so I set expires_at to 30 minutes, which is Stripe's minimum. This second layer is best effort. The first one is what guarantees the refund.

I added the new cases to the unit tests: same id, different id, completed and no_show bookings, and a booking confirmed by hand with no payment recorded. I still have not run the refund or the session expiry against real Stripe, so the same warning applies.

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.
"Already done" is only safe if you know who did it. Store which payment or event handled the work, and compare it.
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 (0)