Currently Available: Need a skilled Software Developer for your next project?
Categories
Databases PostgreSQL

Prevent Overlapping Reservations with PostgreSQL Exclusion Constraints

A reservation service has to stop two bookings from claiming the same room at the same time, even when requests arrive together. You can let PostgreSQL enforce that rule directly by storing each booking's start and end in a single column and adding a rule that rejects overlapping times for the same room.

PostgreSQL's range columns store a span of values as one value, such as the start and end of a reservation. An exclusion constraint rejects a pair of rows when every comparison in the constraint matches. Your service can still run an availability check to show users whether a room looks free before they submit a booking, while PostgreSQL uses the constraint to decide whether to save a conflicting reservation.

Why a pre-insert check leaves a race

A service often checks for a conflict before it inserts a reservation:

SELECT 1
FROM reservation
WHERE room_id = $1
  AND during && tstzrange($2, $3, '[)');

-- If no row is returned:
INSERT INTO reservation (room_id, during)
VALUES ($1, tstzrange($2, $3, '[)'));

Here, $1, $2, and $3 stand for values your client library supplies. The && operator checks whether two ranges overlap.

Because the service runs the check and the insert as separate statements, two concurrent requests can both see an open room. Session A checks and finds no reservation. Before session A commits its insert, session B checks the same time slot and also finds nothing. Under PostgreSQL's default READ COMMITTED isolation level, each statement only sees rows that were committed before that statement started, so session B cannot see session A's uncommitted insert. Both sessions then try to save their reservations. PostgreSQL's transaction documentation covers this statement-level visibility rule.

You can still run that check to show likely availability before a user submits a booking, but you cannot rely on it to guarantee the slot will stay open until the service writes the row.

Store each reservation as a range

When a reservation refers to specific moments in time rather than local clock readings, store it in a tstzrange column, which is PostgreSQL's range type for timestamps with time zone:

CREATE TABLE reservation (
    reservation_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    room_id        bigint NOT NULL,
    during         tstzrange NOT NULL,
    CHECK (NOT isempty(during))
);

The CHECK constraint rejects empty ranges, which can never overlap another range. Keep that check only if your booking rules forbid empty reservations. The NOT NULL constraints require every reservation to include a room and a time interval.

PostgreSQL also offers tsrange for timestamps without time zone. Use tstzrange when you store bookings that represent exact moments in time, and use tsrange when you store local clock readings that do not tie to a specific time zone. The PostgreSQL range types documentation lists the built-in range types and the value types they hold.

The query above uses [) bounds, where the opening bracket includes the start time and the closing parenthesis excludes the end time. That convention lets one reservation end at the exact moment the next one starts. For example, [10:00, 11:00) and [11:00, 12:00) do not overlap.

Reject overlaps for the same room

PostgreSQL enforces non-overlapping reservations with a GiST exclusion constraint. GiST is an index method that supports the range-overlap operator for checking whether two ranges share any values. It also supports equality comparisons on scalar values like room IDs, as long as the database has the operator classes that tell GiST how to compare those data types.

Because room_id is a bigint, install the btree_gist extension before you add the constraint:

CREATE EXTENSION btree_gist;

ALTER TABLE reservation
ADD CONSTRAINT reservation_no_room_overlap
EXCLUDE USING gist (
    room_id WITH =,
    during  WITH &&
);

The btree_gist extension provides GiST operator classes for scalar types such as bigint, letting PostgreSQL compare room IDs with = and time ranges with && in the same constraint. The official btree_gist documentation covers its operator classes for single-value types and multi-column GiST indexes. Before you run the migration, verify that btree_gist is available in your target database and that your migration role has permission to install it.

PostgreSQL rejects a new row only when both comparisons match an existing row, meaning they name the same room and their time ranges overlap. The PostgreSQL range example uses this same pairing for reservations. If your table tracks reservations for a single shared resource, you can drop room_id WITH = and keep only during WITH &&.

PostgreSQL automatically builds the GiST index the exclusion constraint needs, so you do not have to create one yourself. As the constraints documentation notes, exclusion constraints rely on an underlying index. A standard B-tree index on the room and time columns cannot support both comparisons, so it cannot replace the GiST index.

Once you add the constraint, concurrent requests can no longer commit overlapping reservations for the same room. Your availability check might still report the room as free before another request commits, and PostgreSQL will then reject the conflicting insert.

Handle the violation in the client

When an insert conflicts with an existing row, PostgreSQL raises an exclusion violation with SQLSTATE 23P01. The error message names the constraint, and the detail field can show the conflicting key values. Use that text for debugging, and have your application match on the SQLSTATE code instead of parsing human-readable messages. The PostgreSQL error-code reference lists 23P01 as exclusion_violation and recommends checking error codes.

Check the error code your database driver exposes against 23P01, then return a clear response such as "That time is no longer available." Because drivers name that error property differently, look up the field in your client library's documentation. If you run the insert inside a transaction, catch the error through your library's transaction API so you can roll back or recover cleanly.

By default, PostgreSQL checks the constraint immediately after the statement runs. You can define a deferrable exclusion constraint to postpone the check until later in the transaction, though your application then has to handle a possible 23P01 failure at commit time too. For ordinary reservation inserts, keeping the default immediate check surfaces the conflict right where the write happened.

Do not try to use ON CONFLICT DO UPDATE to overwrite an overlapping reservation. As PostgreSQL's INSERT reference notes, PostgreSQL does not support exclusion constraints as arbiters for that clause.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *