When I built an online booking flow for a dental clinic site (Next.js 15, Drizzle ORM, PostgreSQL), the scariest bug wasn't a UI glitch. It was this one: two patients look at the same free 9:00 slot, both click "Book" within the same second, and both get a confirmation email.
The usual first attempt looks fine and is still broken:
// ❌ check, then insert const clash = await db . select ( ) . from ( appointments ) . where ( overlaps ( doctorId , start , end ) ) ; if ( clash . length ) throw new Error ( "slot_taken" ) ; await db . insert ( appointments ) . values ( { doctorId , startsAt : start , endsAt : end , . . . } ) ;
Enter fullscreen mode
Exit fullscreen mode
Between the select and the insert another request can run the same check, see the same empty result, and insert too. Under load (or just two fast clicks from two phones) you get two appointments at 9:00.
Here's what I ended up with, in three small layers.
1.…