Advanced level · Module 1: Databases for Web Applications · Lesson 4 of 4
Transactions and Data Integrity
Keep related changes consistent with transactions and handle concurrent bookings correctly.
In this lesson you will
- Use transactions for multi-step changes
- Prevent double bookings with constraints and checks
Key concepts
transactioncommit and rollbackunique constraintrace condition
The lesson
A transaction groups changes so they succeed or fail together. Creating a booking and marking the time slot taken must both happen, or neither.
Two customers may try to book the last slot at the same moment. Checking availability in code and then inserting is not enough; a UNIQUE constraint on (staff_id, start_time) makes the database reject the second booking.
Catch the constraint error in the API and return a clear 409 Conflict: 'That time has just been booked — please choose another.'
Step by step
- Wrap booking creation in a transaction.
- Add a unique constraint for staff and start time.
- Simulate two simultaneous bookings.
- Return 409 with a helpful message for the loser.
Practice activity
Implement double-booking protection for the booking platform with a test that proves it.
Expected result: Simultaneous bookings for one slot produce one booking and one 409 response.
Check your understanding
-
What does a transaction guarantee?
Show answer
Its changes are applied all together or not at all.
-
Why is checking availability in code not enough to prevent double bookings?
Show answer
Two requests can check at the same time before either inserts; a database constraint prevents this.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.