Checking for overlapping time slots in application code before inserting a booking eventually fails under concurrent traffic. To make double-booking structurally impossible without locking whole tables, push that rule into PostgreSQL using tstzrange, btree_gist, and an EXCLUDE USING gist constraint.
Why Application-Level Overlap Checks Leak
Most double-booking bugs start with a familiar two-step handler: run SELECT EXISTS with starts_at < new_end AND ends_at > new_start for a target room, confirm zero rows match, and execute INSERT. In local tests and quiet staging environments, that check looks airtight.
Under PostgreSQL's default READ COMMITTED isolation level, however, each statement only sees rows committed before that statement began. When two requests book the same room for overlapping afternoon windows within milliseconds of each other, both SELECT queries read an empty calendar. Both handlers proceed to INSERT, and PostgreSQL commits both transactions because neither violates a primary key or UNIQUE constraint.
Teams usually reach for two workarounds, and both carry real friction:
- Locking a parent row (
SELECT ... FOR UPDATEonrooms): This stops the race, but serializes every booking for that room. Someone booking Monday morning blocks someone else booking Friday afternoon. Worse, when no single parent row exists—for example, matching couriers or shared equipment pools—there is nothing clean to lock. - Switching to
SERIALIZABLEisolation: PostgreSQL can detect read-write skew across ranges, butSERIALIZABLErequires every competing write path to catch serialization failures and retry from scratch. One missing retry wrapper turns traffic spikes into500errors.
Enforcing Non-Overlapping Slots with tstzrange and GiST
Standard UNIQUE constraints cannot catch overlapping intervals because B-tree indexes only test scalar equality. The windows [14:00, 15:00) and [14:30, 15:30) are distinct values, yet they collide on the timeline.
PostgreSQL solves this generalized uniqueness problem with exclusion constraints. An exclusion constraint pairs each column or expression with a commutative operator and guarantees that for any two rows, not all paired comparisons return true simultaneously. For room bookings, PostgreSQL rejects a write whenever room_id = existing.room_id and slot && existing.slot (using the && overlap operator).
Exclusion constraints run on GiST indexes. Out of the box, GiST indexes range types like tstzrange and daterange, but lacks operator classes for plain scalar types like bigint, uuid, or text. Enabling PostgreSQL's built-in btree_gist extension bridges that gap so one GiST index can combine scalar equality (=) with range overlap (&&):
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id bigint NOT NULL,
slot tstzrange NOT NULL,
cancelled boolean NOT NULL DEFAULT false,
CONSTRAINT non_empty_slot CHECK (NOT isempty(slot)),
CONSTRAINT no_overlapping_bookings
EXCLUDE USING gist (room_id WITH =, slot WITH &&)
WHERE (NOT cancelled)
);
Three details in that definition prevent subtle bugs:
- Use
tstzrangewith half-open[)bounds. Writingtstzrange('2026-11-24 14:00+07', '2026-11-24 15:00+07', '[)')includes the start timestamp and excludes the end. A15:00checkout sits right next to a15:00check-in without triggering&&. - Reject empty ranges. In PostgreSQL,
'empty'::tstzrangenever overlaps anything, so&&returnsfalseand slips past the exclusion check unlessNOT isempty(slot)blocks it. - Exclude cancelled rows with
WHERE. PostgreSQL 18 added SQL-standardUNIQUE (room_id, slot WITHOUT OVERLAPS)backed by the same GiST andbtree_gistmachinery, but table-levelUNIQUEconstraints cannot take aWHEREclause. When cancelled bookings stay in the table for history,EXCLUDE USING gist (...) WHERE (NOT cancelled)remains the practical choice because it indexes only active slots.
Fitting Legacy Columns and Django Models
Existing tables often store separate starts_at and ends_at columns, and rewriting every query around a range column is rarely worth the churn. Because EXCLUDE USING gist accepts expressions, you can keep both columns, enforce starts_at < ends_at, and index tstzrange(starts_at, ends_at, '[)') directly.
Django supports this pattern in django.contrib.postgres. After running BtreeGistExtension() in a migration, wrap both DateTimeField columns in a TSTZRANGE expression inside Meta.constraints:
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import DateTimeRangeField, RangeBoundary, RangeOperators
from django.db import models
from django.db.models import F, Func, Q
class TsTzRange(Func):
function = "TSTZRANGE"
output_field = DateTimeRangeField()
class RoomBooking(models.Model):
room_id = models.BigIntegerField()
starts_at = models.DateTimeField()
ends_at = models.DateTimeField()
cancelled = models.BooleanField(default=False)
class Meta:
constraints = [
models.CheckConstraint(
condition=Q(starts_at__lt=F("ends_at")),
name="starts_before_ends",
),
ExclusionConstraint(
name="no_overlapping_bookings",
expressions=[
("room_id", RangeOperators.EQUAL),
(TsTzRange("starts_at", "ends_at", RangeBoundary()), RangeOperators.OVERLAPS),
],
condition=Q(cancelled=False),
),
]
Here RangeBoundary() defaults to '[)', matching PostgreSQL's half-open convention. And because PostgreSQL builds a real GiST index for the constraint, availability queries filtering by room_id and range overlap can reuse that index.
Operational Trade-Offs Before Shipping
Moving overlap checks into PostgreSQL removes application race conditions, with three operational caveats to plan around:
- Catch SQLSTATE
23P01specifically. Losing a concurrent race raises PostgreSQL error code23P01(exclusion_violation), surfaced in Python drivers asIntegrityError. Check the SQLSTATE or constraint name and return409 Conflictrather than treating everyIntegrityErroralike. - Avoid
ON CONFLICTupserts. PostgreSQL'sINSERT ... ON CONFLICTonly accepts unique indexes or unique constraints as conflict arbiters—it rejects exclusion constraints. Pair idempotent endpoints with a separateUNIQUEidempotency key and treat23P01as a slot collision. - Keep constraints immediate by default. GiST writes cost slightly more CPU and WAL overhead than B-tree writes, and
DEFERRABLEexclusion constraints add extra runtime cost. Only mark a constraint deferrable if a single transaction genuinely shifts adjacent bookings in place.




Loading comments…