Back to articles
How I Fixed a Race Condition in a Live Seat Booking System (And Lost Sleep Over It)

How I Fixed a Race Condition in a Live Seat Booking System (And Lost Sleep Over It)

via Dev.to JavaScriptJeremiah Deku

𝗧𝘄𝗼 𝘂𝘀𝗲𝗿𝘀. 𝗢𝗻𝗲 𝘀𝗲𝗮𝘁. 𝗧𝗼𝘁𝗮𝗹 𝗰𝗵𝗮𝗼𝘀. It was a regular Tuesday on a client project — a bus ticket booking platform. Everything looked fine until a support ticket landed: two passengers had been assigned the same seat on the same trip. My first instinct? "That can't happen — I have a check before booking." Famous last words. 𝗪𝗵𝗮𝘁 𝘄𝗮𝘀 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗵𝗮𝗽𝗽𝗲𝗻𝗶𝗻𝗴: User A and User B both queried the seat at nearly the same millisecond. Both saw it as available. Both proceeded to book. The database updated twice — same seat, two owners. 𝗠𝘆 𝗳𝗶𝗿𝘀𝘁 (𝘄𝗿𝗼𝗻𝗴) 𝗮𝘁𝘁𝗲𝗺𝗽𝘁𝘀 I tried a simple if check before updating — reading the seat status, then writing. Seemed logical. Broke immediately under any real concurrency. Read-then-write is not atomic. The window between those two operations is exactly where race conditions live. Then I tried a client-side flag. Also wrong. Socket.io events can arrive out of order, and the UI state is not a source of truth. The fix: atomic update + real-time lock broadcast The solution w

Continue reading on Dev.to JavaScript

Opens in a new tab

Read Full Article
5 views

Related Articles