<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Yassine Khattari</title>
    <description>The latest articles on DEV Community by Yassine Khattari (@yassine_khattari_3cb9d27d).</description>
    <link>https://dev.to/yassine_khattari_3cb9d27d</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4232329%2Fe80b3d10-e222-42f1-a44b-9e360b6b74c7.png</url>
      <title>DEV Community: Yassine Khattari</title>
      <link>https://dev.to/yassine_khattari_3cb9d27d</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/yassine_khattari_3cb9d27d"/>
    <language>en</language>
    <item>
      <title>I finally tested my Stripe webhook end to end. It found a bug no unit test could</title>
      <dc:creator>Yassine Khattari</dc:creator>
      <pubDate>Sun, 29 Nov 2026 02:21:45 +0000</pubDate>
      <link>https://dev.to/yassine_khattari_3cb9d27d/i-finally-tested-my-stripe-webhook-end-to-end-it-found-a-bug-no-unit-test-could-2ck7</link>
      <guid>https://dev.to/yassine_khattari_3cb9d27d/i-finally-tested-my-stripe-webhook-end-to-end-it-found-a-bug-no-unit-test-could-2ck7</guid>
      <description>&lt;p&gt;In my last post I fixed five bugs readers found in my booking webhook, and ended with an honest line: "I have not run the full flow against Stripe yet." A reader replied: "Run it in test mode before calling it proven. The replayed event is the one I'm most curious about. Post the numbers when they land."&lt;/p&gt;

&lt;p&gt;Here they are.&lt;/p&gt;

&lt;p&gt;The first thing I found: the app never went to Stripe&lt;/p&gt;

&lt;p&gt;I opened my deployed demo, picked a paid service, confirmed the booking, and clicked the "Simulate payment success" button. It worked, so I almost moved on.&lt;/p&gt;

&lt;p&gt;Then I realised that button belongs to my mock payment provider. My booking page never redirected to Stripe Checkout at all. The webhook code I had been reviewing for weeks was fine, but nothing in the UI could ever reach it. Unit tests cannot find this kind of bug, because every unit was correct.&lt;/p&gt;

&lt;p&gt;The fix was small:&lt;/p&gt;

&lt;p&gt;ts&lt;br&gt;
if (res.checkoutKind === "redirect" &amp;amp;&amp;amp; res.redirectUrl) {&lt;br&gt;
  window.location.assign(res.redirectUrl);&lt;br&gt;
  return; // keep the button disabled while the browser navigates&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;I also made the server refuse to "simulate" a payment that belongs to Stripe, so a real payment can only be confirmed by Stripe's webhook.&lt;/p&gt;

&lt;p&gt;The setup&lt;br&gt;
A Stripe Sandbox (test mode) with a webhook destination pointing at /api/stripe/webhook on the deployed demo.&lt;br&gt;
Test card 4242 4242 4242 4242.&lt;br&gt;
Supabase SQL editor to check the database after every step.&lt;/p&gt;

&lt;p&gt;The check I ran each time:&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
select b.status as booking_status,&lt;br&gt;
       b.confirmed_payment_id = p.id as same_payment,&lt;br&gt;
       p.status as payment_status&lt;br&gt;
from public.payments p&lt;br&gt;
join public.bookings b on b.id = p.booking_id&lt;br&gt;
order by p.created_at desc&lt;br&gt;
limit 3;&lt;br&gt;
Test 1: the happy path&lt;/p&gt;

&lt;p&gt;Confirm booking, get redirected to checkout.stripe.com, pay with the test card, land back on "My bookings".&lt;/p&gt;

&lt;p&gt;Result: webhook checkout.session.completed returned 200. Booking confirmed, payment paid, and confirmed_payment_id equals the payment's id.&lt;/p&gt;

&lt;p&gt;Test 2: the replayed event&lt;/p&gt;

&lt;p&gt;This is the one the reader asked about. In the Stripe dashboard I opened the delivered event and clicked Resend.&lt;/p&gt;

&lt;p&gt;Result: the same event ID was delivered a second time, 200 OK again. Stripe's payments list still showed one payment and no refund. The booking row was unchanged.&lt;/p&gt;

&lt;p&gt;The reason it works: on a retry, the update WHERE status = 'pending' matches zero rows, so the handler reads the booking and sees that confirmed_payment_id is this same payment. Same id means "a retry, answer 200", not "a duplicate, refund".&lt;/p&gt;

&lt;p&gt;Test 3: a duplicate payment&lt;/p&gt;

&lt;p&gt;The UI now closes an open checkout before opening a new one, so a normal user cannot easily pay twice. To test the handler anyway, I created a second payment row for the already confirmed booking and a second Checkout Session with that payment's id in its metadata (from the Stripe shell), then paid it.&lt;/p&gt;

&lt;p&gt;Result:&lt;/p&gt;

&lt;p&gt;payment status&lt;br&gt;
first   paid, and it is the booking's confirmed_payment_id&lt;br&gt;
second  refunded&lt;br&gt;
booking still confirmed&lt;/p&gt;

&lt;p&gt;The handler saw a different payment id on an already confirmed booking, refunded the second payment, and left the booking alone.&lt;/p&gt;

&lt;p&gt;What I did not test&lt;br&gt;
Expired sessions and the retry path are covered by unit tests only. I did not run them against Stripe.&lt;br&gt;
Live mode is untested. Everything above is test mode.&lt;br&gt;
The duplicate in Test 3 was created by hand, so it proves the webhook logic, not a real customer opening two tabs.&lt;br&gt;
What I would take from this&lt;br&gt;
A passing unit test is not a working product. The most important bug here was not in the logic. It was a missing redirect.&lt;br&gt;
Test the replay. Retried events are normal in production. Resend one on purpose.&lt;br&gt;
Store which payment confirmed the booking. One nullable column (confirmed_payment_id) is what separates a retry from a duplicate.&lt;br&gt;
Verify with the database, not the green message. I checked rows after every step.&lt;br&gt;
Say what you did not test. It costs nothing and readers trust the rest more.&lt;/p&gt;

&lt;p&gt;If you want to see the whole flow running, the booking engine with these fixes is a source-code starter kit: $99 one-time, with its limits listed on the page.&lt;/p&gt;

&lt;p&gt;Details and live demo: &lt;a href="https://grow-roots-landing.vercel.app/?ref=devto3" rel="noopener noreferrer"&gt;https://grow-roots-landing.vercel.app/?ref=devto3&lt;/a&gt;&lt;br&gt;
Previous post: &lt;a href="https://dev.to/yassine_khattari_3cb9d27d/how-i-prevent-double-bookings-in-postgres-advisory-locks-supabase-11dl"&gt;https://dev.to/yassine_khattari_3cb9d27d/how-i-prevent-double-bookings-in-postgres-advisory-locks-supabase-11dl&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Which flow in your own app have you only ever tested with a mock?&lt;/p&gt;

</description>
      <category>stripe</category>
      <category>supabase</category>
      <category>postgres</category>
      <category>webdev</category>
    </item>
    <item>
      <title>5 bugs readers found in my Postgres booking trigger and Stripe webhook (and how I fixed them)</title>
      <dc:creator>Yassine Khattari</dc:creator>
      <pubDate>Tue, 24 Nov 2026 15:07:02 +0000</pubDate>
      <link>https://dev.to/yassine_khattari_3cb9d27d/5-bugs-readers-found-in-my-postgres-booking-trigger-and-stripe-webhook-and-how-i-fixed-them-2cll</link>
      <guid>https://dev.to/yassine_khattari_3cb9d27d/5-bugs-readers-found-in-my-postgres-booking-trigger-and-stripe-webhook-and-how-i-fixed-them-2cll</guid>
      <description>&lt;p&gt;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:&lt;/p&gt;

&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/fQfZT6RWkCs" width="710" height="399"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 1: the trigger ran with the wrong privileges&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Fix: run the function as its owner, with a fixed search_path and qualified table names.&lt;/p&gt;

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

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 2: the trigger only fired on INSERT&lt;/p&gt;

&lt;p&gt;This one is subtle. A BEFORE INSERT trigger checks new bookings, but nothing checks the UPDATE that confirms one.&lt;/p&gt;

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

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

&lt;p&gt;Fix: fire the same function on UPDATE, and exclude the row itself from the overlap query.&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
-- in the overlap query&lt;br&gt;
AND b.id IS DISTINCT FROM NEW.id&lt;/p&gt;

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

&lt;p&gt;Now A's late confirmation raises "This time slot is no longer available".&lt;/p&gt;

&lt;p&gt;Bug 3: the webhook ignored the error&lt;/p&gt;

&lt;p&gt;Fixing the trigger created a new question: what does the Stripe webhook do when that exception fires?&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 4: an update that matches zero rows looks like a success&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;The fix for both: ask for the updated rows back, and treat every outcome on purpose.&lt;/p&gt;

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

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

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

&lt;p&gt;(refund(), retryLater() and ok() are placeholders for your own responses.)&lt;/p&gt;

&lt;p&gt;Three details that matter:&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
Refund with an idempotency key (idempotencyKey: "booking-unavailable-refund-" + paymentId), so a retried event cannot refund twice.&lt;br&gt;
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:&lt;br&gt;
sql&lt;br&gt;
RAISE EXCEPTION 'This time slot is no longer available'&lt;br&gt;
  USING ERRCODE = 'exclusion_violation'; -- SQLSTATE 23P01&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 5: two payments for one booking&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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:&lt;/p&gt;

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

&lt;p&gt;In the zero-rows branch I now read status and confirmed_payment_id together:&lt;/p&gt;

&lt;p&gt;same payment id: a Stripe retry, answer 200&lt;br&gt;
different payment id: a duplicate payment, refund it and keep the booking&lt;/p&gt;

&lt;p&gt;Two details:&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;What I would take from this&lt;br&gt;
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.&lt;br&gt;
Check how your client library reports errors. If it returns { error }, an unchecked call fails silently.&lt;br&gt;
Zero rows is not an error, and not a success either. Ask for the rows back and decide what each result means.&lt;br&gt;
Match error codes, not messages.&lt;br&gt;
"Already done" is only safe if you know who did it. Store which payment or event handled the work, and compare it.&lt;br&gt;
Decide what "handled" means for webhooks. Return 200 only when the situation is really dealt with. Return 500 when you want a retry.&lt;br&gt;
Public code review is useful. Readers pointed me at the places I had not looked, and the bugs above came out of that.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

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

&lt;p&gt;What bugs did your booking or checkout code have that you only found later?&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>supabase</category>
      <category>stripe</category>
      <category>webdev</category>
    </item>
    <item>
      <title>4 bugs readers found in my Postgres booking trigger (and how I fixed them)</title>
      <dc:creator>Yassine Khattari</dc:creator>
      <pubDate>Mon, 23 Nov 2026 14:44:45 +0000</pubDate>
      <link>https://dev.to/yassine_khattari_3cb9d27d/4-bugs-readers-found-in-my-postgres-booking-trigger-and-how-i-fixed-them-2ahf</link>
      <guid>https://dev.to/yassine_khattari_3cb9d27d/4-bugs-readers-found-in-my-postgres-booking-trigger-and-how-i-fixed-them-2ahf</guid>
      <description>&lt;p&gt;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:&lt;/p&gt;

&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/fQfZT6RWkCs" width="710" height="399"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 1: the trigger ran with the wrong privileges&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Fix: run the function as its owner, with a fixed search_path and qualified table names.&lt;/p&gt;

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

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 2: the trigger only fired on INSERT&lt;/p&gt;

&lt;p&gt;This one is subtle. A BEFORE INSERT trigger checks new bookings, but nothing checks the UPDATE that confirms one.&lt;/p&gt;

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

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

&lt;p&gt;Fix: fire the same function on UPDATE, and exclude the row itself from the overlap query.&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
-- in the overlap query&lt;br&gt;
AND b.id IS DISTINCT FROM NEW.id&lt;/p&gt;

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

&lt;p&gt;Now A's late confirmation raises "This time slot is no longer available".&lt;/p&gt;

&lt;p&gt;Bug 3: the webhook ignored the error&lt;/p&gt;

&lt;p&gt;Fixing the trigger created a new question: what does the Stripe webhook do when that exception fires?&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Bug 4: an update that matches zero rows looks like a success&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;The fix for both: ask for the updated rows back, and treat every outcome on purpose.&lt;/p&gt;

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

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

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

&lt;p&gt;(refund(), retryLater() and ok() are placeholders for your own responses.)&lt;/p&gt;

&lt;p&gt;Three details that matter:&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
Refund with an idempotency key (idempotencyKey: "booking-unavailable-refund-" + paymentId), so a retried event cannot refund twice.&lt;br&gt;
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:&lt;br&gt;
sql&lt;br&gt;
RAISE EXCEPTION 'This time slot is no longer available'&lt;br&gt;
  USING ERRCODE = 'exclusion_violation'; -- SQLSTATE 23P01&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;What I would take from this&lt;br&gt;
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.&lt;br&gt;
Check how your client library reports errors. If it returns { error }, an unchecked call fails silently.&lt;br&gt;
Zero rows is not an error, and not a success either. Ask for the rows back and decide what each result means.&lt;br&gt;
Match error codes, not messages.&lt;br&gt;
Decide what "handled" means for webhooks. Return 200 only when the situation is really dealt with. Return 500 when you want a retry.&lt;br&gt;
Public code review is useful. Readers pointed me at the places I had not looked, and the bugs above came out of that.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

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

&lt;p&gt;What bugs did your booking or checkout code have that you only found later?&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>supabase</category>
      <category>stripe</category>
      <category>webdev</category>
    </item>
    <item>
      <title>3 bugs readers found in my Postgres booking trigger (and how I fixed them)</title>
      <dc:creator>Yassine Khattari</dc:creator>
      <pubDate>Sun, 15 Nov 2026 16:14:19 +0000</pubDate>
      <link>https://dev.to/yassine_khattari_3cb9d27d/3-bugs-readers-found-in-my-postgres-booking-trigger-and-how-i-fixed-them-27ha</link>
      <guid>https://dev.to/yassine_khattari_3cb9d27d/3-bugs-readers-found-in-my-postgres-booking-trigger-and-how-i-fixed-them-27ha</guid>
      <description>&lt;p&gt;I built a booking app for gyms with React, TanStack Start and Supabase. The part that looked easy and wasn't: two people booking the same slot at the same moment.&lt;/p&gt;

&lt;p&gt;This post explains the approach I ended up with, with a simplified version of the code.&lt;/p&gt;

&lt;p&gt;I also recorded a short video where I test it live, with two requests hitting the same slot:&lt;/p&gt;

&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/fQfZT6RWkCs" width="710" height="399"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Updates after reader feedback (thank you to everyone who reviewed the code):&lt;/p&gt;

&lt;p&gt;My first snippet ran with the inserter's privileges, so Row Level Security could hide other users' bookings from the availability check. Fixed below (SECURITY DEFINER, fixed search_path, qualified table names).&lt;br&gt;
The trigger only fired on INSERT, so a late UPDATE to confirmed could bypass it. Fixed below.&lt;br&gt;
Sunnatulla pointed out the webhook side: what happens when that late confirmation is rejected, and later two more cases (an UPDATE that matches zero rows, and matching on the error code instead of the message). I checked my handler and both were real. See "Handle it in your webhook" below.&lt;br&gt;
The problem&lt;/p&gt;

&lt;p&gt;A client opens the booking page, picks a service, a date and a time slot. Two clients can do this for the same trainer and the same slot within milliseconds of each other.&lt;/p&gt;

&lt;p&gt;If your app does this in two steps:&lt;/p&gt;

&lt;p&gt;SELECT to check the slot is free&lt;br&gt;
INSERT the booking&lt;/p&gt;

&lt;p&gt;then both requests can pass step 1 before either one reaches step 2. Result: a double booking.&lt;/p&gt;

&lt;p&gt;Checking in the frontend or in your API code doesn't fix it, because the race happens between your two queries.&lt;/p&gt;

&lt;p&gt;Why not just a unique constraint?&lt;/p&gt;

&lt;p&gt;A unique constraint works if every booking uses exactly the same start time. It breaks down quickly:&lt;/p&gt;

&lt;p&gt;Services have different durations (30 min, 60 min), so bookings overlap without being equal.&lt;br&gt;
Group classes allow several people in the same slot, up to a capacity.&lt;/p&gt;

&lt;p&gt;An exclusion constraint can handle simple overlaps, but group capacity ("up to 10 people") doesn't fit that model nicely.&lt;/p&gt;

&lt;p&gt;The approach: lock, then check, inside the database&lt;/p&gt;

&lt;p&gt;I put the check in a BEFORE INSERT trigger on the bookings table, and I take a transaction-level advisory lock first. The lock key is the staff member plus the date:&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
-- Simplified. The real version also handles group capacity and expired holds.&lt;br&gt;
CREATE OR REPLACE FUNCTION public.check_booking_availability()&lt;br&gt;
RETURNS trigger&lt;br&gt;
LANGUAGE plpgsql&lt;br&gt;
SECURITY DEFINER&lt;br&gt;
SET search_path = ''&lt;br&gt;
AS $$&lt;br&gt;
DECLARE&lt;br&gt;
  overlapping integer;&lt;br&gt;
BEGIN&lt;br&gt;
  -- Serialize concurrent bookings for the same staff member on the same day.&lt;br&gt;
  PERFORM pg_advisory_xact_lock(&lt;br&gt;
    hashtextextended(NEW.staff_id::text || NEW.booking_date::text, 0)&lt;br&gt;
  );&lt;/p&gt;

&lt;p&gt;SELECT count(*) INTO overlapping&lt;br&gt;
  FROM public.bookings b&lt;br&gt;
  WHERE b.staff_id = NEW.staff_id&lt;br&gt;
    AND b.booking_date = NEW.booking_date&lt;br&gt;
    AND b.id IS DISTINCT FROM NEW.id  -- don't count the row itself on UPDATE&lt;br&gt;
    AND b.status IN ('pending', 'confirmed')&lt;br&gt;
    AND b.start_time &amp;lt; NEW.end_time&lt;br&gt;
    AND b.end_time &amp;gt; NEW.start_time;&lt;/p&gt;

&lt;p&gt;IF overlapping &amp;gt; 0 THEN&lt;br&gt;
    RAISE EXCEPTION 'This time slot is no longer available'&lt;br&gt;
      USING ERRCODE = 'exclusion_violation';  -- SQLSTATE 23P01, easy to match in code&lt;br&gt;
  END IF;&lt;/p&gt;

&lt;p&gt;RETURN NEW;&lt;br&gt;
END;&lt;br&gt;
$$;&lt;/p&gt;

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

&lt;p&gt;What this gives you:&lt;/p&gt;

&lt;p&gt;The advisory lock is held until the transaction ends. A second booking for the same staff member and day waits for the first to commit or roll back, then runs its own check and sees the first booking.&lt;br&gt;
Different staff members, or different days, use different lock keys, so they don't block each other.&lt;br&gt;
The rule lives in the database, so it applies no matter which client inserts (your API, an admin script, a future mobile app).&lt;br&gt;
Why SECURITY DEFINER matters here&lt;/p&gt;

&lt;p&gt;A trigger function normally runs with the privileges of the user doing the insert. If bookings has Row Level Security, that user may only be allowed to see their own rows, and then count(*) would miss other people's bookings. The check would pass when it shouldn't.&lt;/p&gt;

&lt;p&gt;Running the function as its owner fixes that, as long as the owner can see all the relevant rows. In my case the owner is postgres, which has BYPASSRLS on Supabase (you can verify with pg_proc and pg_roles). A few notes:&lt;/p&gt;

&lt;p&gt;Set a fixed search_path on every SECURITY DEFINER function and qualify table names (public.bookings). The real project uses a fixed search_path of public; an empty one is stricter.&lt;br&gt;
FORCE ROW LEVEL SECURITY can still constrain an ordinary table owner, but superusers and BYPASSRLS roles skip it, so know which role owns your function.&lt;br&gt;
Keep the lock and the check together in the same function. Changing visibility alone doesn't fix the race.&lt;/p&gt;

&lt;p&gt;In the app, when the trigger raises the exception, the booking request fails and the client sees a message asking them to pick another slot.&lt;/p&gt;

&lt;p&gt;Don't forget UPDATE&lt;/p&gt;

&lt;p&gt;A BEFORE INSERT trigger alone leaves a gap: nothing checks the UPDATE that confirms a booking. Example: client A's hold expires while they are still on the payment page, client B books the freed slot, then A's payment webhook sets A to confirmed. Both rows end up confirmed for the same slot. The same happens if an admin moves a booking to another time.&lt;/p&gt;

&lt;p&gt;The fix is to fire the same function on UPDATE too, and to exclude the row itself from the overlap query (b.id IS DISTINCT FROM NEW.id). Now A's late confirm raises "This time slot is no longer available", and you can refund or offer another slot. If a booking can move to another staff member or day, the lock only covers the new key, which is fine since that is the slot being claimed.&lt;/p&gt;

&lt;p&gt;Handle it in your webhook&lt;/p&gt;

&lt;p&gt;Once the trigger rejects the late UPDATE, your payment webhook has to deal with it. This is where I found two more bugs in my own code, both silent.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;A rejected update is not an exception. supabase-js does not throw on a database error. It returns { error }, and I was not checking it. The handler returned 200 OK, the payment stayed paid, the booking stayed pending, and the client was charged for a slot they did not get.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;An update that matches zero rows looks like a success. Say the client (or an admin) cancels the pending booking while the Stripe page is still open, and then the payment goes through. .eq("status", "pending") matches nothing, and the library reports success. Same result: charged, no booking. (Thanks again to Sunnatulla for this one.)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The fix is to ask for the updated rows back and treat each outcome on purpose:&lt;/p&gt;

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

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

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

&lt;p&gt;(refund(), retryLater() and ok() are placeholders for your own responses.)&lt;/p&gt;

&lt;p&gt;Details that matter:&lt;/p&gt;

&lt;p&gt;The "already confirmed" branch is important. Stripe retries events. Without it, a retry of an event you already handled would look like a failure and you would refund a booking that is fine.&lt;br&gt;
Refund with an idempotency key, so a retried event cannot refund twice.&lt;br&gt;
Match the error code, not the message. message.includes("no longer available") breaks quietly the day someone rewords the exception. With USING ERRCODE = 'exclusion_violation' in the trigger, the client gets error.code === "23P01". A reader checked this behind PostgREST. Keep the message check only as a fallback for databases that have not run the migration yet.&lt;/p&gt;

&lt;p&gt;I moved this 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.&lt;/p&gt;

&lt;p&gt;Group classes and capacity&lt;/p&gt;

&lt;p&gt;For group classes, the check changes from "any overlap blocks" to "count the people already in this class and compare with capacity". Same lock, same trigger, different condition.&lt;/p&gt;

&lt;p&gt;Temporary holds for paid bookings&lt;/p&gt;

&lt;p&gt;If a service requires payment, I create the booking as pending with a hold_expires_at timestamp while the client pays. The availability check ignores pending bookings whose hold has expired, so an abandoned checkout doesn't block a slot forever:&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
AND NOT (b.status = 'pending'&lt;br&gt;
         AND b.hold_expires_at IS NOT NULL&lt;br&gt;
         AND b.hold_expires_at &amp;lt; now())&lt;br&gt;
Things I'd warn you about&lt;br&gt;
Test the race, don't assume it. Fire two inserts for the same slot in parallel (two terminals, or a small script) and confirm only one succeeds.&lt;br&gt;
Advisory locks are application-defined. Nothing stops other code from inserting without going through the trigger path, so keep the check in the trigger and not in the app only.&lt;br&gt;
Time zones. Store timestamps in UTC and convert per business. It's easy to get the "day" wrong near midnight.&lt;br&gt;
Row Level Security still matters. The trigger prevents double bookings; RLS policies decide who can create or cancel a booking at all. And remember the trigger must be able to see every relevant booking, which is why the function above is SECURITY DEFINER.&lt;br&gt;
Wrapping up&lt;/p&gt;

&lt;p&gt;The core idea is small: lock the resource, then check, then insert, all in one transaction. Everything else (capacity, holds, payments) builds on that.&lt;/p&gt;

&lt;p&gt;I packaged this booking engine, the owner dashboard and the public booking page as a source-code starter kit for developers who build booking apps for clients. It's $99 one-time. The known limits are listed upfront: the CMI (Moroccan gateway) integration is a mock, Stripe is test mode only, and there's no automated test suite.&lt;/p&gt;

&lt;p&gt;Video: &lt;a href="https://youtu.be/fQfZT6RWkCs" rel="noopener noreferrer"&gt;https://youtu.be/fQfZT6RWkCs&lt;/a&gt;&lt;br&gt;
30-second demo: &lt;a href="https://youtube.com/shorts/SKSHpPnNcOQ" rel="noopener noreferrer"&gt;https://youtube.com/shorts/SKSHpPnNcOQ&lt;/a&gt;&lt;br&gt;
Details and live demo: &lt;a href="https://grow-roots-landing.vercel.app/?ref=devto" rel="noopener noreferrer"&gt;https://grow-roots-landing.vercel.app/?ref=devto&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you've solved double bookings differently (exclusion constraints, SELECT ... FOR UPDATE, queues), I'd like to hear what worked for you.&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>supabase</category>
      <category>stripe</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How I prevent double bookings in Postgres (advisory locks + Supabase)</title>
      <dc:creator>Yassine Khattari</dc:creator>
      <pubDate>Sat, 07 Nov 2026 15:15:13 +0000</pubDate>
      <link>https://dev.to/yassine_khattari_3cb9d27d/how-i-prevent-double-bookings-in-postgres-advisory-locks-supabase-11dl</link>
      <guid>https://dev.to/yassine_khattari_3cb9d27d/how-i-prevent-double-bookings-in-postgres-advisory-locks-supabase-11dl</guid>
      <description>&lt;p&gt;I built a booking app for gyms with React, TanStack Start and Supabase. The part that looked easy and wasn't: two people booking the same slot at the same moment.&lt;/p&gt;

&lt;p&gt;This post explains the approach I ended up with, with a simplified version of the code.&lt;/p&gt;

&lt;p&gt;I also recorded a short video where I test it live, with two requests hitting the same slot:&lt;/p&gt;

&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/fQfZT6RWkCs" width="710" height="399"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;If you want to run it yourself, here is a free, MIT-licensed repo with the trigger and a race test (it fires 10 simultaneous requests at one slot and checks exactly one wins): &lt;a href="https://github.com/Yassineai1/postgres-double-booking-demo" rel="noopener noreferrer"&gt;https://github.com/Yassineai1/postgres-double-booking-demo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Updates after reader feedback (thank you to everyone who reviewed the code):&lt;/p&gt;

&lt;p&gt;My first snippet ran with the inserter's privileges, so Row Level Security could hide other users' bookings from the availability check. Fixed below (SECURITY DEFINER, fixed search_path, qualified table names).&lt;br&gt;
The trigger only fired on INSERT, so a late UPDATE to confirmed could bypass it. Fixed below.&lt;br&gt;
Sunnatulla pointed out the webhook side: what happens when that late confirmation is rejected, and later two more cases (an UPDATE that matches zero rows, and matching on the error code instead of the message). I checked my handler and both were real. See "Handle it in your webhook" below.&lt;br&gt;
The problem&lt;/p&gt;

&lt;p&gt;A client opens the booking page, picks a service, a date and a time slot. Two clients can do this for the same trainer and the same slot within milliseconds of each other.&lt;/p&gt;

&lt;p&gt;If your app does this in two steps:&lt;/p&gt;

&lt;p&gt;SELECT to check the slot is free&lt;br&gt;
INSERT the booking&lt;/p&gt;

&lt;p&gt;then both requests can pass step 1 before either one reaches step 2. Result: a double booking.&lt;/p&gt;

&lt;p&gt;Checking in the frontend or in your API code doesn't fix it, because the race happens between your two queries.&lt;/p&gt;

&lt;p&gt;Why not just a unique constraint?&lt;/p&gt;

&lt;p&gt;A unique constraint works if every booking uses exactly the same start time. It breaks down quickly:&lt;/p&gt;

&lt;p&gt;Services have different durations (30 min, 60 min), so bookings overlap without being equal.&lt;br&gt;
Group classes allow several people in the same slot, up to a capacity.&lt;/p&gt;

&lt;p&gt;An exclusion constraint can handle simple overlaps, but group capacity ("up to 10 people") doesn't fit that model nicely.&lt;/p&gt;

&lt;p&gt;The approach: lock, then check, inside the database&lt;/p&gt;

&lt;p&gt;I put the check in a BEFORE INSERT trigger on the bookings table, and I take a transaction-level advisory lock first. The lock key is the staff member plus the date:&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
-- Simplified. The real version also handles group capacity and expired holds.&lt;br&gt;
CREATE OR REPLACE FUNCTION public.check_booking_availability()&lt;br&gt;
RETURNS trigger&lt;br&gt;
LANGUAGE plpgsql&lt;br&gt;
SECURITY DEFINER&lt;br&gt;
SET search_path = ''&lt;br&gt;
AS $$&lt;br&gt;
DECLARE&lt;br&gt;
  overlapping integer;&lt;br&gt;
BEGIN&lt;br&gt;
  -- Serialize concurrent bookings for the same staff member on the same day.&lt;br&gt;
  PERFORM pg_advisory_xact_lock(&lt;br&gt;
    hashtextextended(NEW.staff_id::text || NEW.booking_date::text, 0)&lt;br&gt;
  );&lt;/p&gt;

&lt;p&gt;SELECT count(*) INTO overlapping&lt;br&gt;
  FROM public.bookings b&lt;br&gt;
  WHERE b.staff_id = NEW.staff_id&lt;br&gt;
    AND b.booking_date = NEW.booking_date&lt;br&gt;
    AND b.id IS DISTINCT FROM NEW.id  -- don't count the row itself on UPDATE&lt;br&gt;
    AND b.status IN ('pending', 'confirmed')&lt;br&gt;
    AND b.start_time &amp;lt; NEW.end_time&lt;br&gt;
    AND b.end_time &amp;gt; NEW.start_time;&lt;/p&gt;

&lt;p&gt;IF overlapping &amp;gt; 0 THEN&lt;br&gt;
    RAISE EXCEPTION 'This time slot is no longer available'&lt;br&gt;
      USING ERRCODE = 'exclusion_violation';  -- SQLSTATE 23P01, easy to match in code&lt;br&gt;
  END IF;&lt;/p&gt;

&lt;p&gt;RETURN NEW;&lt;br&gt;
END;&lt;br&gt;
$$;&lt;/p&gt;

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

&lt;p&gt;What this gives you:&lt;/p&gt;

&lt;p&gt;The advisory lock is held until the transaction ends. A second booking for the same staff member and day waits for the first to commit or roll back, then runs its own check and sees the first booking.&lt;br&gt;
Different staff members, or different days, use different lock keys, so they don't block each other.&lt;br&gt;
The rule lives in the database, so it applies no matter which client inserts (your API, an admin script, a future mobile app).&lt;br&gt;
Why SECURITY DEFINER matters here&lt;/p&gt;

&lt;p&gt;A trigger function normally runs with the privileges of the user doing the insert. If bookings has Row Level Security, that user may only be allowed to see their own rows, and then count(*) would miss other people's bookings. The check would pass when it shouldn't.&lt;/p&gt;

&lt;p&gt;Running the function as its owner fixes that, as long as the owner can see all the relevant rows. In my case the owner is postgres, which has BYPASSRLS on Supabase (you can verify with pg_proc and pg_roles). A few notes:&lt;/p&gt;

&lt;p&gt;Set a fixed search_path on every SECURITY DEFINER function and qualify table names (public.bookings). The real project uses a fixed search_path of public; an empty one is stricter.&lt;br&gt;
FORCE ROW LEVEL SECURITY can still constrain an ordinary table owner, but superusers and BYPASSRLS roles skip it, so know which role owns your function.&lt;br&gt;
Keep the lock and the check together in the same function. Changing visibility alone doesn't fix the race.&lt;/p&gt;

&lt;p&gt;In the app, when the trigger raises the exception, the booking request fails and the client sees a message asking them to pick another slot.&lt;/p&gt;

&lt;p&gt;Don't forget UPDATE&lt;/p&gt;

&lt;p&gt;A BEFORE INSERT trigger alone leaves a gap: nothing checks the UPDATE that confirms a booking. Example: client A's hold expires while they are still on the payment page, client B books the freed slot, then A's payment webhook sets A to confirmed. Both rows end up confirmed for the same slot. The same happens if an admin moves a booking to another time.&lt;/p&gt;

&lt;p&gt;The fix is to fire the same function on UPDATE too, and to exclude the row itself from the overlap query (b.id IS DISTINCT FROM NEW.id). Now A's late confirm raises "This time slot is no longer available", and you can refund or offer another slot. If a booking can move to another staff member or day, the lock only covers the new key, which is fine since that is the slot being claimed.&lt;/p&gt;

&lt;p&gt;Handle it in your webhook&lt;/p&gt;

&lt;p&gt;Once the trigger rejects the late UPDATE, your payment webhook has to deal with it. This is where I found two more bugs in my own code, both silent.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;A rejected update is not an exception. supabase-js does not throw on a database error. It returns { error }, and I was not checking it. The handler returned 200 OK, the payment stayed paid, the booking stayed pending, and the client was charged for a slot they did not get.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;An update that matches zero rows looks like a success. Say the client (or an admin) cancels the pending booking while the Stripe page is still open, and then the payment goes through. .eq("status", "pending") matches nothing, and the library reports success. Same result: charged, no booking. (Thanks again to Sunnatulla for this one.)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The fix is to ask for the updated rows back and treat each outcome on purpose:&lt;/p&gt;

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

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

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

&lt;p&gt;(refund(), retryLater() and ok() are placeholders for your own responses.)&lt;/p&gt;

&lt;p&gt;Details that matter:&lt;/p&gt;

&lt;p&gt;The "already confirmed" branch is important. Stripe retries events. Without it, a retry of an event you already handled would look like a failure and you would refund a booking that is fine.&lt;br&gt;
Refund with an idempotency key, so a retried event cannot refund twice.&lt;br&gt;
Match the error code, not the message. message.includes("no longer available") breaks quietly the day someone rewords the exception. With USING ERRCODE = 'exclusion_violation' in the trigger, the client gets error.code === "23P01". A reader checked this behind PostgREST. Keep the message check only as a fallback for databases that have not run the migration yet.&lt;/p&gt;

&lt;p&gt;I moved this 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.&lt;/p&gt;

&lt;p&gt;Group classes and capacity&lt;/p&gt;

&lt;p&gt;For group classes, the check changes from "any overlap blocks" to "count the people already in this class and compare with capacity". Same lock, same trigger, different condition.&lt;/p&gt;

&lt;p&gt;Temporary holds for paid bookings&lt;/p&gt;

&lt;p&gt;If a service requires payment, I create the booking as pending with a hold_expires_at timestamp while the client pays. The availability check ignores pending bookings whose hold has expired, so an abandoned checkout doesn't block a slot forever:&lt;/p&gt;

&lt;p&gt;sql&lt;br&gt;
AND NOT (b.status = 'pending'&lt;br&gt;
         AND b.hold_expires_at IS NOT NULL&lt;br&gt;
         AND b.hold_expires_at &amp;lt; now())&lt;br&gt;
Things I'd warn you about&lt;br&gt;
Test the race, don't assume it. Fire two inserts for the same slot in parallel (two terminals, or a small script) and confirm only one succeeds. The repo above has a script for that: &lt;a href="https://github.com/Yassineai1/postgres-double-booking-demo" rel="noopener noreferrer"&gt;https://github.com/Yassineai1/postgres-double-booking-demo&lt;/a&gt;&lt;br&gt;
Advisory locks are application-defined. Nothing stops other code from inserting without going through the trigger path, so keep the check in the trigger and not in the app only.&lt;br&gt;
Time zones. Store timestamps in UTC and convert per business. It's easy to get the "day" wrong near midnight.&lt;br&gt;
Row Level Security still matters. The trigger prevents double bookings; RLS policies decide who can create or cancel a booking at all. And remember the trigger must be able to see every relevant booking, which is why the function above is SECURITY DEFINER.&lt;br&gt;
Wrapping up&lt;/p&gt;

&lt;p&gt;The core idea is small: lock the resource, then check, then insert, all in one transaction. Everything else (capacity, holds, payments) builds on that.&lt;/p&gt;

&lt;p&gt;I packaged this booking engine, the owner dashboard and the public booking page as a source-code starter kit for developers who build booking apps for clients. It's $99 one-time. The known limits are listed upfront: the CMI (Moroccan gateway) integration is a mock, Stripe is test mode only, and there's no automated test suite.&lt;/p&gt;

&lt;p&gt;Video: &lt;a href="https://youtu.be/fQfZT6RWkCs" rel="noopener noreferrer"&gt;https://youtu.be/fQfZT6RWkCs&lt;/a&gt;&lt;br&gt;
30-second demo: &lt;a href="https://youtube.com/shorts/SKSHpPnNcOQ" rel="noopener noreferrer"&gt;https://youtube.com/shorts/SKSHpPnNcOQ&lt;/a&gt;&lt;br&gt;
Details and live demo: &lt;a href="https://grow-roots-landing.vercel.app/?ref=devto" rel="noopener noreferrer"&gt;https://grow-roots-landing.vercel.app/?ref=devto&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you've solved double bookings differently (exclusion constraints, SELECT ... FOR UPDATE, queues), I'd like to hear what worked for you.&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>supabase</category>
      <category>react</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
