TL;DR
- Use PostgreSQL exclusion constraints for booking systems that need to prevent two active reservations for the same resource at overlapping times. Model the booking as a finite, half-open interval. Put resource equality and range overlap into the same constraint. Competing transactions then resolve against the same invariant even when they come from different application processes.
- Keep holds in the database when checkout promises to reserve a resource. An explicit status determines whether a row occupies a slot. A short database transaction moves timed-out holds from
heldtoexpired. Holding a Redis lease or hiding overdue rows from a calendar does not release a row protected by the database constraint. - Return HTTP
409when the named exclusion constraint rejects a competing request. Treat idempotent replays separately and retry only transient failures with an explicit budget. For reservations against a shared quantity, use a capacity allocation model.
Why concurrent booking requests can both see an open slot
Consider a scheduling API with eight workers and a calendar served from a replica. Two customers click the last available 10:00 appointment for the same practitioner. Each request starts a PostgreSQL transaction and queries for an overlapping appointment. The first check sees no row. The second check also sees no committed row. If the schema permits overlapping times, both requests can insert and commit. The calendar now shows two people the same confirmation, even when the replica is completely up to date.
Moving the first query to the primary makes its information fresher and leaves the fundamental race intact. At READ COMMITTED, each statement uses a snapshot and does not see another transaction’s uncommitted reservation. A row lock on a query that returns no matches locks no reservation rows. You could lock the practitioner or room row instead, with a requirement that every writer take that lock before making the overlap decision. PostgreSQL can express the underlying rule directly. PostgreSQL transaction isolation and snapshots
The first decision is what is actually scarce. A meeting room is a resource. A ticket category with 500 exchangeable seats is a capacity pool. Some lodging platforms sell a room type and assign a physical room later. Choose the invariant that matches the sales contract. This example reserves one identifiable resource. It allows identical intervals under a different resource ID or tenant.
An availability read is still useful. It can render a calendar, filter impossible slots and help the user recover when another customer wins. Keep checkout completion contingent on a successful database commit. If you accept payment on a separate system, there are multiple independently durable events to reconcile, even if your first-choice schedule is always consistent.
Model booking overlap as a resource and a time range
A range stores lower and upper bounds and specifies whether either bound is included. Use [) for a booking that owns its start and excludes its end. The intervals 10:00–11:00 and 11:00–12:00 touch and can both be valid. The intervals 10:00–11:00 and 10:59–11:59 overlap. The && operator tests for shared elements. Think through clearance or cleaning time explicitly. If it occupies the resource, include it in the protected range and retain the customer-facing times separately. PostgreSQL range bounds, operators and examples
Use daterange when a booking is made in calendar dates, such as hotel nights with a checkout date excluded. Use tstzrange when each endpoint identifies an instant. Interpret local dates and times in the resource’s named time zone before passing an instant to PostgreSQL. Decide how to handle ambiguous and nonexistent local times at daylight-saving transitions. A saved UTC instant does not retain the property’s original time zone, so retain that separately where necessary for displaying the booking correctly.
A GiST exclusion constraint specifies a combination of operators that cannot all match for two protected rows. Here, the constraint rejects a row when the tenant IDs are equal, the resource IDs are equal, and the ranges overlap. The btree_gist extension adds GiST operator classes for scalar values including bigint. For this design, a partial predicate includes held and confirmed rows and excludes cancelled and expired rows. PostgreSQL’s btree_gist operator classes
Search availability → show a candidate slot
Create hold on primary → resolve exclusivity in PostgreSQL
Payment workflow → confirm an eligible hold or compensate
Expiry worker → move overdue held rows to expired
Hold expiry is a lifecycle event. A row does not leave a partial index as wall time passes. A predicate involving the current clock also fails the immutability rule for index definitions. Model the overdue hold as occupying the resource until a transaction changes its status. This creates a measurable interval between the promised expiry and the slot becoming available again. If that delay matters, expire eligible overlapping rows on the write path as well as running the background sweeper. PostgreSQL partial index predicates and immutability requirements
Implement booking overlap constraints in PostgreSQL
Create the range table and exclusion constraint
The example targets PostgreSQL 18 and assumes your migration role can install or use btree_gist. Model the resource’s ownership separately in an application table and add a composite foreign key in production. This example shows the scheduling invariant on its own. Tenant, resource and range are required so a null comparison cannot bypass the rule. The range check rejects unbounded bounds, explicit infinite timestamps and empty ranges.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE booking (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id bigint NOT NULL,
resource_id bigint NOT NULL,
request_key text NOT NULL,
slot tstzrange NOT NULL,
status text NOT NULL CHECK (status IN ('held','confirmed','expired','cancelled')),
hold_expires_at timestamptz,
UNIQUE (tenant_id, request_key),
CHECK (NOT isempty(slot)
AND NOT lower_inf(slot) AND NOT upper_inf(slot)
AND isfinite(lower(slot)) AND isfinite(upper(slot))
AND lower_inc(slot) AND NOT upper_inc(slot)),
CHECK (status <> 'held' OR (hold_expires_at IS NOT NULL
AND isfinite(hold_expires_at))),
CONSTRAINT booking_no_overlap EXCLUDE USING gist (
tenant_id WITH =, resource_id WITH =, slot WITH &&
) WHERE (status IN ('held', 'confirmed'))
);
CREATE INDEX booking_hold_expiry
ON booking (hold_expires_at, id)
WHERE status = 'held';
Use parameterised queries and build the range from validated timestamps with an explicit [) bound specification. Insert a hold using the primary, and keep the transaction open just long enough to do local work. If a second request conflicts with an uncommitted hold, it can wait for that transaction’s outcome within your timeout budget. If the first holds and commits, the other transaction cannot commit another overlapping active row.
Claim the slot and classify a competing request
BEGIN;
SET LOCAL lock_timeout = '300ms';
SET LOCAL statement_timeout = '2s';
INSERT INTO booking
(tenant_id, resource_id, request_key, slot, status, hold_expires_at)
VALUES (7, 102, 'checkout-7f42',
tstzrange('2027-02-08 10:00+00', '2027-02-08 11:00+00', '[)'),
'held', clock_timestamp() + interval '5 minutes')
RETURNING id, status, hold_expires_at;
COMMIT;
Store a client request key with the resource and requested slot. The application should check the booking belongs to the authorised caller and compare the original intent on replay. If the insert encounters either the exclusion violation or the unique request key, roll back the failed transaction before reading the existing record on the primary. If the same key describes the same intent, return the stored ID and current status. For a reused key with different intent, reject the request. For another customer’s overlap, return a generic availability conflict without leaking their details.
In psycopg 3, inspect the exception SQLSTATE and diag.constraint_name. In this schema, 23P01 and booking_no_overlap identify the overlap rejection. The unique request key can raise 23505. Lock timeouts such as 55P03, deadlocks 40P01, and serialization failures 40001 are different outcomes. Retry a whole transaction only when that error is transient and your request still has time. Repeating a confirmed exclusion violation rarely helps the customer. PostgreSQL SQLSTATE error codes
Check availability using the active status predicate and slot && tstzrange(...). Avoid filtering out logically overdue holds when claiming a resource would still be rejected. If the UI is designed to show estimated availability, label it accordingly. Track the time from expiry deadline to state transition and choose where to handle overdue holds if stale display becomes a support issue.
Confirm the hold and release expired rows
Decide what a deadline means when transactions race. The code below obtains a row lock and checks the wall clock in the next statement. Confirmation is eligible when that check occurs before expiry. The transaction may commit just after the cutoff. If the sweeper has already changed the row’s status, the update returns zero rows. Keep payment work outside this SQL transaction, and define what happens if money has already been captured when it returns no row.
-- The app takes this row lock before running its conditional confirmation.
BEGIN;
SELECT id FROM booking
WHERE tenant_id = 7 AND request_key = 'checkout-7f42'
FOR UPDATE;
UPDATE booking
SET status = 'confirmed'
WHERE tenant_id = 7 AND request_key = 'checkout-7f42'
AND status = 'held' AND hold_expires_at > clock_timestamp()
RETURNING id;
COMMIT;
-- Separate sweeper transaction. Re-run periodically on the primary.
BEGIN;
WITH due AS (
SELECT id FROM booking
WHERE status = 'held' AND hold_expires_at <= statement_timestamp()
ORDER BY hold_expires_at, id
FOR UPDATE SKIP LOCKED LIMIT 100
)
UPDATE booking b
SET status = 'expired'
FROM due WHERE b.id = due.id
RETURNING b.id;
COMMIT;
Process expiry in bounded batches so workers can share a backlog. SKIP LOCKED can leave a row for the next pass, and the query always scans the oldest eligible held rows again. This pattern is appropriate for a queue-like sweep where skipped work is picked up later. A timer can trigger one pass, and the job can iterate until it hits its time budget or finds no due holds. Monitor its exit status and the age of the oldest due hold. PostgreSQL locking clauses and SKIP LOCKED
# /etc/systemd/system/booking-expiry.timer
[Unit]
Description=Release expired booking holds
[Timer]
OnBootSec=10s
OnUnitInactiveSec=15s
AccuracySec=1s
Unit=booking-expiry.service
[Install]
WantedBy=timers.target
# /etc/systemd/system/booking-expiry.service
[Unit]
Description=Run one booking hold sweeper pass
[Service]
Type=oneshot
User=booking-worker
EnvironmentFile=/etc/booking/worker.env
ExecStart=/opt/booking/.venv/bin/python -m app.booking_expiry --batch-size=100
TimeoutStartSec=10s
This systemd example assumes your Python worker implements the sweeper SQL and reads its primary database connection from an environment file with restricted permissions. The displayed batch size and timer interval are starting values. A cluster scheduler can launch the same job. Define permissions so the sweeper can update status but cannot confirm or mutate appointments arbitrarily. Consider separate, narrower expiry and confirmation functions for that boundary.
Failure modes to reproduce with two database connections
Adjacent appointments are rejected or overlap unexpectedly
A client supplies inclusive end times or adds a cleaning buffer only in the UI. Two adjacent customer requests either conflict unnecessarily or leave no real time for setup. Keep the protected interval consistent at every entry point and test equal endpoints, a one-second overlap, and an interval that appears adjacent before adding buffers. For date-only bookings, test a checkout and next check-in on the same date.
A duplicate request looks like a different customer’s conflict
Checkout times out after a successful commit and submits the same request again. The replay may encounter a uniqueness violation or an overlap. Read the stored request on the primary after rolling back the failed statement. Exercise one concurrent same-key test and one concurrent different-key test with the same range. Expect one committed booking in both cases, and different responses for replay versus a real conflict.
A late payment succeeds after another customer books
A provider webhook arrives after expiry and a new hold now owns the slot. An unconditional confirmation would attempt to resurrect the old row, possibly raising the exclusion error. Keep transitions conditional on status and deadline. Record the provider event durably, then follow a documented compensation flow such as voiding an authorisation or issuing an idempotent refund, depending on the payment contract.
A single import bypasses application state transitions
Someone loads records with direct database access and uses the wrong status or assigns them to the wrong physical room. The constraint protects only the rows and identity represented in its predicate. Restrict direct table writes, stage imported reservations and compare ranges and resource mappings before moving them into the live schedule. An existing table with overlaps needs cleanup before an exclusion constraint can be installed.
When another booking model makes sense
- Fixed slots with a unique key. Use a unique key on resource and slot when reservations can only start at predetermined times and each occupies exactly one unit. If longer bookings span several units, claim every unit in one transaction.
- A parent row lock with a capacity calculation. Use an inventory row or another deliberately chosen serialisation key to protect pooled capacity. The rule can then compare available quantities and claim a unit atomically. All writers must honor that same lock and inventory calculation.
- Redis leases for traffic shaping. Use a short lease to dampen contention or provide UI feedback if temporary discrepancies are acceptable. The PostgreSQL commit still decides exclusivity. Redis and PostgreSQL have independent failure and recovery paths.
Estimate the delay before an expired slot becomes available
This is a hypothetical operating budget. If a sweep starts every 15 seconds, finishes in one second and there is no backlog, an expiry observed just after the previous sweep can take roughly 16 seconds to become claimable. The illustrated systemd setup waits 15 seconds after completion, so account for job runtime and scheduler jitter too. With 100 holds processed per pass and about four passes per minute, a single-pass job clears roughly 400 holds per minute at that cadence. Measure actual volume and track both p95 expiry lag and write contention for the busiest resource. A test spread uniformly across resources will miss the launch-day rush on a single popular slot.
Frequently asked questions
How do PostgreSQL exclusion constraints prevent double booking?
Define an exclusion constraint using GiST with equal resource keys and the range overlap operator. PostgreSQL rejects a protected row when an existing protected row has the same resource and an overlapping time range. The invariant applies to competing writes even when different application processes never see each other’s preliminary availability checks.
Should booking ranges use daterange or tstzrange?
Use daterange for calendar dates such as hotel nights where the checkout day is excluded. Use tstzrange for reservations tied to particular instants. Interpret entered wall times in the resource’s named time zone before converting them. Half-open intervals allow one booking to end exactly when another one starts.
Can expiring checkout holds use NOW in a PostgreSQL exclusion predicate?
Use a stored status in the predicate. PostgreSQL requires immutable expressions in index definitions and a timestamp that passes does not cause index membership to change. A worker or claiming transaction should change expired holds to a nonblocking status. Monitor how long the release takes after the deadline.
When should a booking API return HTTP 409?
Return HTTP 409 when the named exclusion constraint rejects a requested slot that overlaps another active booking. Before concluding there is a conflict, check whether a successfully committed booking already owns the same request key and represents the same intent. Treat timeouts, deadlocks and mismatched request keys separately.
Further reading
- Choose PostgreSQL indexes for common SaaS workloads
- Plan safe PostgreSQL schema changes with Alembic
- PostgreSQL exclusion constraints
- PostgreSQL range constraint examples
Designing PostgreSQL exclusion constraints for a booking system? Talk to Dumb Potato about interval boundaries, checkout states and the concurrency tests to run before launch.
