Put the allocation rule in the database
Two customers can both see an available room before either reservation commits. An availability query is useful feedback, but a later insert needs an independent authority. For exclusive bookings, write the invariant precisely: two active rows must not share a tenant, a resource and an overlapping time range.
A PostgreSQL exclusion constraint rejects a pair of rows when every specified operator comparison is true. Equivalently, a valid pair must have at least one comparison that is false or null. Equality on tenant_id and resource_id narrows the conflict domain. The range overlap operator && supplies the time condition. This is the contract in the PostgreSQL constraint reference.
The downloadable fixture runs 17 behavioral cases and 14 endpoint probes on an isolated PostgreSQL 17.11 server. A competing insertion waits for an uncommitted reservation, then fails with SQLSTATE 23P01 if its owner commits. It succeeds if that owner rolls back. These are observed database outcomes, without a latency or throughput claim.
Combine GiST range overlap with scalar equality
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE reservations (
id bigint PRIMARY KEY,
tenant_id bigint NOT NULL,
resource_id bigint NOT NULL,
slot tstzrange NOT NULL,
status text NOT NULL CHECK (status IN ('active','cancelled')),
CONSTRAINT valid_slot 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)
),
CONSTRAINT no_active_overlap EXCLUDE USING gist (
tenant_id WITH =, resource_id WITH =, slot WITH &&
) WHERE (status = 'active') DEFERRABLE INITIALLY IMMEDIATE
);GiST provides the range-index behavior. The btree_gist extension adds suitable operator classes for scalar types such as bigint so equality can participate in the same exclusion index. btree_gist is not a replacement for an ordinary B-tree unique index. Here it joins equality and range overlap in one constraint.
The constraint creates its supporting index. It is a rule over active reservation pairs, not a global ban on overlapping timestamps. Another resource in the same tenant is allowed, and the same numeric resource identifier in another tenant is allowed. The fixture tests both. The primary key independently identifies a reservation. It does not enforce the scheduling rule.
Choose endpoint semantics before writing availability queries
A tstzrange stores a range of timestamp-with-time-zone values. A tsrange uses timestamps without time zone. Daterange represents dates. Match that choice to the business meaning rather than converting a daily rental or a local recurring appointment into instants without a policy. The range-type documentation covers constructors and inclusive or exclusive bounds.
For adjacent exclusive bookings, use a half-open interval: [start, end). A reservation ending at 12:00 does not overlap one starting at 12:00. With both bounds inclusive, the shared endpoint belongs to both ranges. Subtracting an arbitrary second or microsecond from an end time is a different policy and introduces avoidable precision assumptions.
| Candidate (UTC) | Both ranges [start, end) | Both ranges [start, end] |
|---|---|---|
| 08:00 to 09:00 | Accepted | Accepted |
| 09:00 to 10:00 | Accepted | Rejected: 23P01 |
| 10:00 to 11:00 | Rejected: 23P01 | Rejected: 23P01 |
| 11:00 to 12:00 | Rejected: 23P01 | Rejected: 23P01 |
| 12:00 to 13:00 | Accepted | Rejected: 23P01 |
| 13:00 to 14:00 | Accepted | Accepted |
| 14:00 to 15:00 | Accepted | Accepted |
The half-open series accepted five candidates and rejected two. The closed series accepted three and rejected four. This second series uses a separate bare-overlap table: the main reservation schema deliberately requires [start, end), so it would reject closed bounds at its validation check first.
Explicit UTC offsets keep this fixture unambiguous. They do not solve recurring local schedules or daylight-saving transitions. A booking UI still needs an explicit time-zone and ambiguous-time policy. Store the instants and retain any business time-zone identifier separately when recurrence or presentation requires it.
Reject ranges that make the business rule meaningless
An exclusion constraint alone is not complete input validation. Equality with a null tenant or resource does not produce the all-true conflict condition. A null range is another missing value. The schema therefore declares all three columns NOT NULL. The corresponding fixture inserts fail with 23502.
An empty range contains no points, so it overlaps nothing. Equal start and end values with [) produce an empty range. The valid_slot check rejects that value with 23514. A reversed bound is different: the range constructor rejects an upper bound below its lower bound with 22000 before there is a valid range to store.
An omitted constructor bound, including a SQL NULL used as a bound, creates an unbounded side. That differs from a null range value. lower_inf and upper_inf identify unbounded sides. An explicit timestamp value of infinity is a separate case. The check rejects both unbounded sides and non-finite timestamp bounds using isfinite. Those fixture attempts both return 23514.
The final lower_inc and upper_inc checks enforce the endpoint convention. NOT NULL remains separate because a CHECK can pass when its expression is null. If your domain permits open-ended allocations or zero-duration markers, give those records an intentional representation instead of quietly inheriting this example's policy.
Observe the competing transaction before choosing a response
-- Session A
BEGIN;
INSERT INTO reservations VALUES (
1, 1, 1,
tstzrange('2026-01-01 10:00+00','2026-01-01 12:00+00','[)'),
'active'
);
-- Session B: waits while A is unresolved
INSERT INTO reservations VALUES (
2, 1, 1,
tstzrange('2026-01-01 10:30+00','2026-01-01 11:30+00','[)'),
'active'
);
-- Session A: choose one outcome
COMMIT; -- B receives 23P01
-- ROLLBACK instead: B succeedsThe runner uses a third connection to observe session B as active with wait_event_type equal to Lock in pg_stat_activity. Only after that observation does it finish session A. Both commit and rollback branches leave exactly one reservation. The observer proves a wait occurred. It does not measure its duration or promise the same wait behavior for every workload.
A SELECT that finds no overlap can race with another writer. Keep it for a helpful availability screen, then let the database arbitrate the write. Avoid holding the transaction open while a customer pays or chooses a room. A slow owner can make another request wait even though the final outcome will be a routine booking conflict.
This fixture uses the server's normal transaction behavior for these explicit statements. It does not test a web request timeout, a connection pool or a distributed transaction. Apply statement deadlines and cancellation deliberately, and inspect the actual error rather than treating every failed insertion as an overlap.
Treat 23P01 as a booking outcome with transaction consequences
PostgreSQL names 23P01 exclusion_violation in its SQLSTATE catalog. Inspect the structured SQLSTATE and the relevant constraint name through your driver. Message text can vary. A unique-key violation, a check failure and a cancellation require different handling.
For this allocation rule, a confirmed overlap normally means ask for another interval or resource. Blindly retrying the same occupied slot does not make it available. A caller can retry after a genuine change in availability, subject to an explicit policy. If a conflict occurs inside an explicit transaction, roll it back or recover to a suitable savepoint before reusing that transaction.
Do not turn the database's detailed conflicting-key message into a public error response. It may expose identifiers or timestamps a caller should not see. Return an authorized booking-conflict response and keep diagnostic details in access-controlled operational records. The database invariant does not establish permission to inspect another tenant's reservations.
Keep cancellation and reactivation inside the invariant
WHERE (status = 'active') makes this a partial exclusion constraint. Canceled rows remain available for history but do not occupy the resource. The fixture accepts a canceled row whose slot overlaps an active reservation. Changing that row to active triggers the constraint and fails with 23P01.
The status column has both NOT NULL and a finite allowed-value check. Without a complete status policy, a misspelled or missing status can accidentally fall outside the predicate. Soft deletion needs the same review: specify exactly which states reserve capacity and ensure every transition into those states is checked.
A pending-payment hold that occupies the room must be included in the exclusion predicate or represented as an active allocation. Do not use a moving wall-clock predicate to assume expired holds automatically disappear from an index. Perform a real state transition under a reviewed expiry workflow. The fixture tests active and canceled only. It implements no hold-expiration service.
Use deferral for a valid final schedule, then check the commit
A direct swap can temporarily overlap even when the final schedule is valid. DEFERRABLE INITIALLY IMMEDIATE preserves normal statement checks while allowing a transaction to defer this named constraint. The fixture swaps two adjacent reservations by changing the first row into the second row's slot, then moving the second row into the first slot.
BEGIN;
SET CONSTRAINTS no_active_overlap DEFERRED;
UPDATE reservations
SET slot = tstzrange('2026-01-01 12:00+00','2026-01-01 14:00+00','[)')
WHERE id = 1;
UPDATE reservations
SET slot = tstzrange('2026-01-01 10:00+00','2026-01-01 12:00+00','[)')
WHERE id = 2;
SET CONSTRAINTS no_active_overlap IMMEDIATE;
COMMIT;Both updates succeed and the final start hours are 12 and 10. SET CONSTRAINTS ... IMMEDIATE forces pending checks at that point. Otherwise they can wait until commit. The SET CONSTRAINTS reference explains this retroactive check.
A separate fixture transaction defers the constraint, inserts an unresolved overlap and receives 23P01 at COMMIT. Its extra row is rolled back, leaving the original row. A successful statement inside that transaction is not confirmation of a successful reservation. Report success to an external caller only after the transaction commits.
Deferral does not postpone NOT NULL or CHECK validation. It also changes which conflict-arbitration features are available to INSERT. Keep the transaction short and use deferral for a concrete final-state operation rather than enabling it for every request by habit.
Choose the mechanism that owns the actual invariant
UNIQUE compares equal keys. Even a unique pair of start and end values would allow two different overlapping intervals. CHECK validates a row's shape. It is not the right mechanism for a cross-row lookup that must remain valid under concurrent writes. A trigger that merely queries for conflicts inherits the coordination problem unless its concurrency design resolves it.
An advisory lock can coordinate a larger workflow when every participating writer uses the same key and lifetime. It does not automatically constrain an insertion from a script or a different service. The PostgreSQL advisory-lock guide covers that cooperative protocol. Exclusion places this particular row invariant on all ordinary writes to the table.
Serializable transactions can be another part of a correct allocation design, but they require transaction-wide retry handling and a reviewed read/write protocol. This fixture does not compare isolation strategies or performance. Prefer the exclusion rule when the business rule directly matches pairwise equality plus non-overlap.
ON CONFLICT DO UPDATE does not support exclusion constraints as arbiters. Additionally, this example's deferrable constraint cannot be used as an ON CONFLICT arbiter, including an attempted named-constraint shortcut. The PostgreSQL INSERT reference owns those restrictions. Do not turn a booking collision into an accidental update of somebody else's reservation.
Preflight existing data and plan a real constraint installation
SELECT a.id AS first_id, b.id AS second_id
FROM reservations AS a
JOIN reservations AS b
ON a.id < b.id
AND a.tenant_id = b.tenant_id
AND a.resource_id = b.resource_id
AND a.slot && b.slot
WHERE a.status = 'active' AND b.status = 'active';Review null keys, invalid bounds and state values as well as overlaps. Resolve conflicts with a business owner. Deleting a booking to make a migration pass is not an integrity strategy. A preflight query can become stale while writes continue, so include a controlled installation window or another reviewed write-coordination plan.
In PostgreSQL 17, NOT VALID on ADD CONSTRAINT is available for foreign keys and CHECK constraints, not exclusion constraints. Attaching a prebuilt unique index is another mechanism with its own restrictions. It is not a generic way to attach an exclusion index. The ALTER TABLE reference documents the scans and lock requirements. Do not present CREATE INDEX CONCURRENTLY as a complete online installation recipe for this constraint.
Partitioning needs a separate review of the exact server version, partition keys and conflict domain. Independent local constraints are insufficient if two conflicting allocations can land in different partitions. The tested table here is not partitioned. GiST index size, contention and query plans also depend on the actual data distribution. The fixture supplies no throughput, index-size or migration-duration estimate.
Keep allocation integrity separate from authorization and capacity
A tenant_id comparison permits equal resource identifiers in different tenant namespaces. It does not prove that a resource belongs to that tenant. Pair the allocation rule with appropriate tenant-aware references, access controls and authenticated query scope. The tenant foreign-key guide owns parent-child integrity across that boundary.
This pairwise rule models one exclusive unit. A workshop with several interchangeable seats or a room admitting several simultaneous occupants needs an explicit capacity model. One option is to allocate separate exclusive units. A different model may need aggregate capacity coordination. An exclusion constraint does not calculate the number of remaining seats.
The article uses PostgreSQL 17 syntax and a tested 17.11 server. Newer temporal-key shorthand, temporal foreign keys, multirange allocation, spatial exclusion and ORM-specific migrations have separate contracts. Django, SQLAlchemy and Rails adapters do not remove the need to inspect the generated database constraint. None of those integrations was executed here.
Reproduce the 17 cases and 14 endpoint probes
Download the standard-library Python runner and saved PostgreSQL results. Use an owned disposable PostgreSQL 17.11 container with btree_gist available, no published port and no shared data. The runner drops and recreates only its exclusion_lab schema, so never point it at an existing application database.
python3 experiment.py --container YOUR_DISPOSABLE_CONTAINER > actual.jsonThe 17 cases include three NOT NULL failures, three range-check failures, a reversed-range constructor failure, cancellation/reactivation, a valid deferred swap and an invalid deferred commit. Two real-session races observe the waiting contender before resolving its owner. The separate 14 probes vary bounds and candidate start times. The chart reads those saved results directly.
Two executions produced byte-identical JSON. The harness bounds its waits to avoid hanging, but publishes no elapsed time as a result. It does not exercise an application server, authorization layer, ORM, connection pool, partitioned table or production dataset. Keep those as separate acceptance tests when adopting the schema.
Review the booking contract at the write boundary
Before release, identify the exact states that consume capacity and the columns defining one resource. Verify adjacent intervals, rejected empty values and the cancellation-to-active transition. Test the same conflict through each writer that can reach the table, then confirm that the API waits for a successful commit before returning a reservation.
After deployment, a rise in exclusion violations can represent honest demand for an occupied slot, a faulty time conversion or an unexpected retry loop. Classify the constraint and transaction outcome before changing the rule. The database can decide that two rows conflict. Only the product's allocation policy can decide which alternative to offer the customer.
Sources
Documentation checked .

Continue the conversation
Comments (0)