How to prevent race conditions in serverless apps with Postgres
Brief
Serverless requests can race even when each handler works correctly in isolation. The guide presents database-level fixes for common checkout, booking, editing and webhook failures.
Choose a fix for the invariant
- Use an atomic conditional UPDATE for single-row rules such as stock or quotas; add a CHECK constraint as a backstop.
- Use .forUpdate() when application logic must run between reading and writing an existing row; keep the transaction short and set a timeout.
- Use a version column to detect conflicting edits, and UNIQUE or EXCLUDE constraints to prevent duplicate or overlapping bookings.
- For rules spanning multiple rows, use SERIALIZABLE transactions and retry serialization failures; all competing writes must use that isolation level.
Handle duplicate events and test concurrency
- Record webhook event IDs in a unique column in the same transaction as fulfillment; ON CONFLICT DO NOTHING lets duplicate deliveries exit without repeating the work.
- Test with concurrent requests against a real database and warm the connection pool first. The article's example uses 20 connections to test selling one remaining ticket exactly once.
Generated by AI from the original article. Check the source for full details.