Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How Databases Prevent Double Bookings

· 6 min read · Home Tech

In this article
  1. Why Double Bookings Happen
  2. Core Techniques: Constraints and Locks
  3. How Transactions Make It Safe
  4. Handling Time Ranges and Overlaps
  5. Choosing the Right Approach for Your System
  6. Common Problems and Misconceptions
  7. Frequently Asked Questions

A database prevents two bookings for the same time by using constraints and transactions to enforce that a resource (like a room, seat, or appointment slot) is never assigned to more than one reservation at the same moment. This is typically done with a unique index on the resource and time period, combined with row-level locking during the booking insert.

Why Double Bookings Happen

Double bookings occur when two users (or two processes) check for availability at nearly the same time, both see the slot as free, and both insert a booking before the other finishes. Without protection, the database happily stores both rows because each insert only checks the data as it existed at the start of its own transaction. The classic race condition is called a check-then-insert problem: the check and the insert are two separate steps, and another transaction can slip in between them.

Databases solve this by making the check and insert atomic—either the whole operation succeeds or it fails, with no other transaction able to interfere in the middle. The exact mechanism depends on the database system, but the core idea is always to serialize access to the resource's availability.

Core Techniques: Constraints and Locks

There are three main approaches, and most production systems combine them.

  • Unique constraints / indexes: The simplest method. If a booking is for a single time slot (e.g., a 9:00 AM appointment), you create a unique index on (resource_id, start_time). The database will reject any second insert with the same resource and start time, even if two transactions try simultaneously.
  • Exclusion constraints (PostgreSQL): For bookings that span a time range (e.g., 9:00–10:00 AM), a unique index doesn't work because two different start times can overlap. PostgreSQL offers EXCLUDE USING gist (resource_id WITH =, tstzrange(start_time, end_time) WITH &&), which rejects any overlapping range for the same resource.
  • Row-level locking: Before inserting, the transaction locks the resource's row (e.g., SELECT * FROM rooms WHERE id = 123 FOR UPDATE). This forces any other transaction trying to book the same room to wait until the first commits, at which point it re-checks availability and sees the new booking.

In practice, you often use a lock on the resource row, then perform the availability check, then insert. The lock serializes all booking attempts for that resource, preventing the race.

How Transactions Make It Safe

A transaction groups the check and insert into one atomic unit. The key is the isolation level. The default in most databases is Read Committed, which means each statement sees only committed data. If you do a plain SELECT then an INSERT in separate statements, another transaction can commit between them—so you still get a double booking. To prevent this, you either:

  • Use SELECT ... FOR UPDATE to lock the resource row, which blocks other transactions from modifying it until you commit.
  • Use a higher isolation level like Serializable, which makes the database detect conflicts and abort one of the transactions if they would produce an inconsistent result.
  • Rely on a unique constraint as a final backstop—even if your application logic has a bug, the constraint rejects the duplicate insert.

The safest pattern is to use both a lock and a constraint. The lock prevents wasted work, and the constraint guarantees correctness even if the lock is forgotten.

Handling Time Ranges and Overlaps

Bookings often aren't single points in time—a hotel room is booked for nights, a meeting room for hours. To prevent overlaps, you need to check that the new booking's start time is not before an existing booking's end time, and vice versa. The SQL condition is:

WHERE resource_id = ? AND start_time < ? AND end_time > ?

If any row is returned, the slot is taken. With an exclusion constraint, the database does this check automatically and atomically. Without it, you must lock the resource row first, then run the overlap query, then insert—all in one transaction.

Be careful with time zones. Store times in UTC and convert to local time only for display. If you store local times, a daylight saving change can create ambiguous or non-existent times, leading to incorrect overlap checks.

Choosing the Right Approach for Your System

There is no one-size-fits-all answer. Consider these factors:

  • Single resource vs. many: If you have thousands of resources (e.g., hotel rooms), locking each resource row is fine. If you have one resource with high contention, you might need a queue or a separate availability table.
  • PostgreSQL vs. MySQL: PostgreSQL has native exclusion constraints; MySQL does not. In MySQL, you typically use SELECT ... FOR UPDATE on the resource row, or a unique index on a generated column that represents the time slot.
  • Application vs. database: Some teams try to handle this in application code with a distributed lock (e.g., Redis). That can work, but it's more complex and less reliable than a database constraint.
  • Read-heavy workloads: If you have many reads and few writes, you can use optimistic locking: add a version column to the resource, and in the update check that the version hasn't changed. But for bookings, pessimistic locking is more common because conflicts are frequent.

Common Problems and Misconceptions

A frequent mistake is thinking that a unique index on (resource_id, start_time) is enough for time-range bookings. It isn't—two bookings can start at different times and still overlap. You need an exclusion constraint or an overlap check with locking.

Another misconception is that SELECT ... FOR UPDATE is only for updates. It also locks the row for any other SELECT ... FOR UPDATE or UPDATE, which is exactly what you want. However, if you forget to use it in one of the booking paths, a double booking can slip through.

Deadlocks are possible when two transactions lock resources in different orders. For example, if transaction A locks room 1 then room 2, and transaction B locks room 2 then room 1, they can deadlock. The database will detect this and abort one transaction, which the application must handle by retrying.

Finally, don't rely on application-level checks alone. They are prone to race conditions, especially in multi-server deployments where each server has its own cache. Always have a database-level constraint as the final authority.

Frequently Asked Questions

Can a unique index prevent overlapping time ranges?

No. A unique index only prevents exact duplicates. For example, a unique index on (resource_id, start_time) would allow a booking from 9:00–10:00 and another from 9:30–10:30 because the start times differ. You need an exclusion constraint (PostgreSQL) or an overlap check with locking.

What happens if two users book the same slot at the exact same millisecond?

With a unique constraint, one insert will succeed and the other will fail with a duplicate key error. The application should catch that error and inform the user the slot is taken. With row locking, the second transaction will wait until the first commits, then see the new booking and fail its availability check.

Is it better to use a database lock or a unique constraint?

Use both. The lock prevents wasted work and gives a clean error message, while the constraint is a safety net. If you only use a lock, a bug in the code could still cause a double booking. If you only use a constraint, you might get a raw database error that's hard to handle gracefully.

How do I handle bookings that span multiple days?

Store the start and end timestamps in UTC. For the overlap check, use the same condition: start_time < new_end AND end_time > new_start. An exclusion constraint with a tstzrange also handles this automatically. Just make sure you convert correctly when displaying in local time.

Does using a transaction guarantee no double bookings?

No. A transaction alone doesn't prevent race conditions. You need to combine it with a lock or a constraint. The transaction ensures atomicity, but the lock or constraint provides the actual serialization.

What if I'm using a NoSQL database like MongoDB?

MongoDB supports unique indexes, but not exclusion constraints. You can use a unique index on a field that represents a fixed time slot, but for ranges you'd need to use a distributed lock or a separate collection that tracks availability with atomic updates. It's more complex than in a relational database.