Menu

The Bug Behind Double Bookings
📰

The Bug Behind Double Bookings

DEV Community: postgres·Vijay Rangan·2 days ago
#tIQSW7qd
#devtopostgresql#devto#dev#guest#night
Reading 0:00
15s threshold

Here's a booking function. It checks whether the room is free for the night, and if it is, it saves the booking.

async function book ( roomId : string , night : string , guest : string ) { const { rows } = await pool . query ( " SELECT count(*)::int AS taken FROM bookings WHERE room_id = $1 AND night = $2 " , [ roomId , night ], ); if ( rows [ 0 ]. taken > 0 ) return ` ${ guest } : sorry, already booked` ;

await pool . query ( " INSERT INTO bookings (room_id, night, guest) VALUES ($1, $2, $3) " , [ roomId , night , guest ], ); return ` ${ guest } : confirmed` ; }

Enter fullscreen mode

Exit fullscreen mode

Every line is correct. It passes the tests you'd write for it. And if ten guests try to book the same room for the same night at the same moment, all ten are confirmed.

The bug isn't in any single line. It's in the gap between two of them.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.