Concurrency bugs in code
Send the code path and describe the wrong result, and have Claude Opus 5 explain how two requests can interleave and give a fix that holds under load. Confirm it with a test that fires the requests at the same time.
Example: Why can two people book the same seat?
Material
- book.ts
- const seat = await db.getSeat(id); if (!seat.taken) await db.markTaken(id);
- Incident
- Two customers received confirmations for seat 14C on the same flight, 40 ms apart.
PromptUsing the code and the incident, explain how two bookings for one seat can succeed, and give a fix that stays correct when requests arrive at the same moment.
Sample answer · written by hand to show the reasoning
The code reads the seat, then writes it in a separate step. Both requests read seat 14C as free before either one marked it, so both succeeded. Make the check and the write one statement, such as UPDATE seats SET taken = true WHERE id = $1 AND taken = false, and treat zero updated rows as already booked. Test it by sending two requests for the same seat at once.