Urgent.News

What's breaking now, across hundreds of outlets.

Tech

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…

This article describes four bugs found in the author's Postgres booking trigger for preventing double bookings, along with the fixes for each issue. The first bug is that the trigger runs with the wrong privileges, causing it to miss other users' bookings when Row Level Security is enabled. The fix is to run the function as its owner and set a fixed search_path.

The second bug is that the trigger only fires on INSERT, not on UPDATE. This oversight allows a client to book a slot that becomes unavailable after the payment is confirmed, by updating the booking status to "confirmed". The solution is to fire the trigger on UPDATE as well, excluding the row itself from the overlap query. The third bug is that the webhook handler does not check for errors when updating the booking with Stripe's library, resulting in silent failures and charged but unconfirmed bookings.

The fix is to check the response for errors and handle them appropriately, refunding or retrying as needed. The fourth bug is that an UPDATE statement that matches zero rows is treated as a success, causing similar issues to the previous one. The author resolves this by asking for the updated rows back and treating each outcome differently, such as refunding or retrying based on the specific case.

The article concludes by emphasizing the importance of testing, error handling, and public code review to catch and address such bugs.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

Report a problem with this story

More in Tech

What are your goals for the week? #206

It's Thanksgiving week in the US. Many people will have a three day workweek followed by a long weekend. If you're working international you won't see us.

  • Focus on Black Friday Sales article for Tuesday publication
  • Personal goals include job search, networking, and side project work
  • Goal-setting thread on Virtual Coffee Slack scheduled for Thursday

More from Monday 23 November →