Quick Answers
How do you prevent double booking in a database?
To reliably prevent double booking, let your database handle the decision rather than your application code. Using database enforcement, such as unique constraints, PostgreSQL exclusion constraints, or atomic conditional updates, guarantees that only one request can successfully reserve a slot. Relying solely on an application level availability check followed by an insert creates a race condition, where concurrent requests can read the same slot as free and execute duplicate bookings simultaneously.
Why does an if (isAvailable) check fail under load?
Under heavy web traffic, multiple requests often read the exact same database row at the precise same moment. With standard transaction isolation levels like READ COMMITTED, each incoming request sees an available slot because neither request has committed its write yet. Consequently, both requests pass the application check and write conflicting rows, which is a normal database behavior that leads to duplicate reservations unless explicitly guarded at the schema level.
Should I use SELECT FOR UPDATE or an exclusion constraint?
Choose database exclusion constraints when your business logic is strictly data driven, such as preventing overlapping time ranges for a single resource or venue. Use pessimistic locking (such as SELECT FOR UPDATE) when managing complex multi-statement transaction logic. When using row level locking, always lock the parent resource (for example, the room or venue) rather than non-existent target booking rows, as uncreated rows cannot be locked.
How long should a booking hold last?
A temporary reservation hold should last just long enough for users to finish checkout without unnecessarily locking inventory away from other prospective buyers. A 10-minute time-to-live (TTL) window is an industry standard. Store an expiration timestamp (`expires_at`), clear abandoned holds using an automated background sweeper, and allow new customers to reserve the slot as soon as a hold expires.
Why the Obvious Availability Check Fails
A common design pattern is reading a slot from the database, confirming it is open, and then creating the booking record. While this logic passes local unit tests, it falls short in production environments under real concurrency.
When two users attempt to book the exact same slot at the same time, both application instances read `status = ‘open’`. Since both read operations succeed, both insert a new record, resulting in an unintended double booking for a single resource.
Standard database transactions do not automatically solve this issue. Under the default READ COMMITTED isolation level in databases like PostgreSQL, a standard `SELECT` statement does not place locks on rows. As a result, concurrent transactions read uncommitted snapshot data, missing pending writes from other active connections.
To fix race conditions in booking systems, transfer validation responsibility directly into the database engine, forcing conflicting concurrent writes to fail predictably.
The Concurrency Control Decision Matrix
| Approach | Best use case | Contention handling | Failure mode | Engineering complexity |
| Unique or exclusion constraint | Rules expressible as data, such as one seat, one room, or no overlapping ranges. | The loser gets an immediate error with no waiting. | A constraint violation surfaces as a 500 if nobody catches the SQLSTATE. | Low to add, and medium to design around cancelled rows. |
| Pessimistic lock (SELECT FOR UPDATE) | Multi-statement decisions on one parent resource. | The second request waits, then re-reads and loses fairly. | A lock held too long blocks other bookings, and long waits exhaust the pool. | Medium. |
| Optimistic lock (version or status check) | Single-row state changes with no long decision. | The loser sees zero affected rows and either retries or is told no. | Retry storms appear under high contention, and a silent success follows if the row count is ignored. | Low. |
| Temporary hold with TTL | Anything with a checkout step or a payment provider. | The slot is reserved for one person until expires_at. | Abandoned holds block inventory until the sweeper runs. | Medium to high, because it needs a sweeper and idempotency. |
Production architecture frequently combines these approaches: temporary TTL holds reserve inventory during payment processing, while hard database constraints or atomic conditional updates finalize the booking transaction.
Implement the simplest concurrency control mechanism that meets your core requirements. Introducing complex multi-stage hold systems to simple scheduling workflows adds unnecessary engineering overhead.
Understanding optimistic vs. pessimistic locking helps clarify system selection. Optimistic concurrency control minimizes database overhead for low-contention operations, whereas pessimistic locking works best for complex multi-statement operations on parent entities. However, neither replaces dedicated reservation hold lifecycles designed for multi-step checkout flows.
Blocking Overlaps at the Engine Level
To enforce business rules like “no overlapping bookings for the same room,” PostgreSQL exclusion constraints provide robust engine-level prevention. By combining the `btree_gist` extension with GiST indexes, you can evaluate equality on entity identifiers alongside overlap operators on timestamp ranges.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
id bigserial PRIMARY KEY,
room_id bigint NOT NULL,
during tstzrange NOT NULL,
status text NOT NULL DEFAULT 'held',
expires_at timestamptz,
CONSTRAINT bookings_no_overlap
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
In PostgreSQL, the `&&` operator detects overlapping range types (`tstzrange`). If an incoming row overlaps an existing booking period, the database automatically blocks the operation with an exclusion constraint violation (`SQLSTATE 23P01`). Because this check runs entirely inside the database engine, race conditions are eliminated.
When working with exclusion constraints, keep two key architectural behaviors in mind:
1. Cancelled bookings maintain active time ranges: Because native exclusion constraints ignore row status flags, cancelled records still trigger overlap errors. To free up slots, remove cancelled bookings, adjust their time bounds, or archive them in a separate table.
2. Boundary conditions require half-open ranges: Prevent back-to-back reservation conflicts (such as one booking ending at 10:00 AM while another starts at 10:00 AM) by defining half-open time ranges (`[)`), making start bounds inclusive and end bounds exclusive.
For simpler scheduling structures, such as fixed single-seat day passes, a standard unique composite index on `(seat_id, booking_date)` achieves the exact same prevention with simpler database infrastructure.
Engines like MySQL lack native exclusion constraints, requiring developers to rely on pessimistic row-level locking paired with application validation or precalculated slot identifiers enforced by unique indexes.
The Atomic Conditional Update
When reserving pre-allocated database rows (such as specific seat numbers), atomic conditional updates provide an efficient, lightweight concurrency control solution.
UPDATE slots
SET status = 'booked', booked_at = now()
WHERE id = $1
AND status = 'open'
RETURNING id;
Combining status validation and row updates into a single SQL statement eliminates the race window. Relational databases execute conditional updates atomically, forcing concurrent operations to queue behind row locks until the primary transaction settles.
To implement this safely, applications must explicitly check the number of affected rows returned by the query executor.
Receiving an affected row count of 1 confirms a successful reservation. Receiving 0 indicates that a concurrent transaction already updated the record, requiring your application to return a friendly `409 Conflict` response instead of falsely confirming an uncompleted booking.
This pattern provides cross-database compatibility across PostgreSQL, MySQL, SQL Server, and Oracle without requiring proprietary extensions.
Locking the Right Row
A frequent SQL error in concurrency control involves attempting pessimistic locking on uncreated records using queries like `SELECT … FROM bookings WHERE room_id = $1 FOR UPDATE`.
Because targeted target booking rows do not exist prior to insert, the database cannot acquire row-level locks on them.
Instead, acquire an explicit row lock on the existing parent record (e.g., the parent `rooms` table):
BEGIN;
SELECT id FROM rooms WHERE id = $1 FOR UPDATE;
INSERT INTO bookings (room_id, during, status)
VALUES (2, $3, '[)'), 'booked');
COMMIT;
Locking the parent room record serializes incoming reservation attempts. Concurrent transactions wait sequentially for the lock release before verifying available slots or encountering database constraints.
Always acquire multiple resource locks in a strict, consistent order to avoid database deadlocks. Additionally, avoid holding row locks while executing external HTTP calls or third-party API integrations (such as payment gateways).
In MySQL, locking reads using `FOR UPDATE` or `FOR SHARE` achieve identical serialization patterns when managed correctly inside transaction blocks.
The Checkout Gap: Two-Phase Holds
Database transactions expect fast execution times. Since user interactions like payment details entry introduce significant network delay, keeping transaction locks open during checkout causes database connection pool exhaustion and system failure.
To decouple payment delays from database connection holds, implement a robust two-phase reservation architecture:
UPDATE slots
SET status = 'held',
hold_token = $2,
expires_at = now() + interval '10 minutes'
WHERE id = $1
AND (status = 'open' OR (status = 'held' AND expires_at < now()))
RETURNING id, expires_at;
Phase 1: Execute a rapid, non-blocking transaction that marks the item as `held` with an explicit expiry timestamp. Commit the transaction immediately so database locks are not held during checkout interaction.
Phase 2: Once payment succeeds via API webhooks, update the slot status to `booked`. If checkout fails or is aborted, revert the slot status to `open` so it becomes immediately available to other users.
Incorporate unique idempotency keys into your hold endpoints to safely handle duplicate client requests without creating multiple reservation holds.
Automate state recovery using scheduled background database cleanup operations:
UPDATE slots
SET status = 'open', hold_token = NULL, expires_at = NULL
WHERE status = 'held' AND expires_at < now();
Always include the `hold_token` in confirmation `WHERE` clauses to avoid late payments claiming resold inventory. Configure background sweeper tasks to run continuously at intervals shorter than your hold TTL.
Ensure inventory listing endpoints treat active `held` items as unavailable to prevent checkout conflicts on front-end interfaces.
Testing It Properly
Single-threaded test suites cannot detect race conditions. Validate concurrency logic using automated load-testing scripts or parallel integration tests that execute overlapping requests simultaneously.
Focus assertions on execution results rather than code paths: exactly one incoming request must succeed, while concurrent operations receive appropriate conflict statuses (`409 Conflict`).
Verify test suite accuracy by temporarily disabling constraints to confirm that double-booking failures are properly caught. Log specific database error codes (like `23P01` or `23505`) to prevent constraint violations from masking as unhandled `500 Server Errors`.
If your application needs robust concurrency prevention, our custom software team provides complete database schema, constraint, and hold lifecycle optimization. Our API integration team implements idempotent endpoints, conflict handling, and automated inventory background sweepers.
This guide focuses specifically on database and API concurrency control for booking platforms. For distributed background job and worker locking strategies, see our dedicated engineering guide.
Frequently Asked Questions
Will a unique index stop double booking?
Yes, but only for exact matches like reserving a specific seat on a specific date. For variable or overlapping time ranges, use database exclusion constraints instead of standard unique indexes.
What SQLSTATE should the API return for a conflict?
Catch PostgreSQL error codes `23P01` (exclusion violation) and `23505` (unique violation) in your application layer, and translate them to `HTTP 409 Conflict` API responses with descriptive error messages.
Should expired holds be deleted or reopened?
Reopen expired holds by updating their status back to `open`. Reopening records maintains audit trails, historical telemetry, and pricing analytics, whereas deleting rows discards valuable business metrics.
Do I need both a constraint and a conditional update?
Yes, combining both provides optimal defense-in-depth architecture. Atomic conditional updates keep the primary execution path performant, while database constraints provide a definitive fail-safe against schema-level double bookings.
References
- PostgreSQL Documentation: Constraints, including exclusion constraints.
- PostgreSQL Documentation: Explicit Locking.
- PostgreSQL Documentation: Transaction Isolation.
- PostgreSQL Documentation: Range Types.
- PostgreSQL Documentation: btree_gist.
- PostgreSQL Documentation: Appendix A, PostgreSQL Error Codes.
- MySQL 8.4 Reference Manual: Locking Reads.