Skip to content

How do you make a booking retry safe across API instances?

1 min read · main part only; folded sections are optional

After this you can answer: How do you make a booking retry safe across API instances?

A pre-check alone is insufficient: two requests can both observe no previous booking. The unique database constraint settles that race. For two events using the same user and key, one transaction can lose its insert after decrementing seats; the entire losing transaction rolls back, then the query reads the winner’s booking.

The service compares the stored event and quantity with the new input. Matching parameters replay the public booking; different parameters yield a conflict. Existing successes remain replayable even after the event sells out or starts.

This implementation stores successful bookings rather than every HTTP response. A rejected booking writes no success row, so the same key may try again later. I would document that contract explicitly for clients. Keys do not expire in this schema, which simplifies correctness at the cost of retaining them with every booking.

Why scope the key to the user?
One user’s key must not reveal or replay another user’s booking. Ownership comes from the authenticated session, and the unique constraint includes user_id.
What if the two requests arrive simultaneously?
The event lock handles same-event contention. The unique constraint also handles different-event reuse; the loser rolls back before reading the committed winner.
Would a Redis SET NX be enough?
It would not atomically commit with the booking in Postgres. A crash between stores could permit a duplicate or leave a false completed marker; the database row avoids that extra protocol.

Read Idempotency, then inspect the rds-postgres piece →.

apps/api/src/services/bookings.ts → bookTicket

Read this book online: https://book.theversehub.in/