PostgreSQL Exclusion Constraints: Stop Double-Booking in SQL

Application-level overlap checks fail under concurrent writes. Use PostgreSQL tstzrange, btree_gist, and EXCLUDE USING gist to prevent double-booking safely.

PostgreSQL Exclusion Constraints: Stop Double-Booking in SQL
In this essay

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 UPDATE on rooms): 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 SERIALIZABLE isolation: PostgreSQL can detect read-write skew across ranges, but SERIALIZABLE requires every competing write path to catch serialization failures and retry from scratch. One missing retry wrapper turns traffic spikes into 500 errors.

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:

  1. Use tstzrange with half-open [) bounds. Writing tstzrange('2026-11-24 14:00+07', '2026-11-24 15:00+07', '[)') includes the start timestamp and excludes the end. A 15:00 checkout sits right next to a 15:00 check-in without triggering &&.
  2. Reject empty ranges. In PostgreSQL, 'empty'::tstzrange never overlaps anything, so && returns false and slips past the exclusion check unless NOT isempty(slot) blocks it.
  3. Exclude cancelled rows with WHERE. PostgreSQL 18 added SQL-standard UNIQUE (room_id, slot WITHOUT OVERLAPS) backed by the same GiST and btree_gist machinery, but table-level UNIQUE constraints cannot take a WHERE clause. 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 23P01 specifically. Losing a concurrent race raises PostgreSQL error code 23P01 (exclusion_violation), surfaced in Python drivers as IntegrityError. Check the SQLSTATE or constraint name and return 409 Conflict rather than treating every IntegrityError alike.
  • Avoid ON CONFLICT upserts. PostgreSQL's INSERT ... ON CONFLICT only accepts unique indexes or unique constraints as conflict arbiters—it rejects exclusion constraints. Pair idempotent endpoints with a separate UNIQUE idempotency key and treat 23P01 as a slot collision.
  • Keep constraints immediate by default. GiST writes cost slightly more CPU and WAL overhead than B-tree writes, and DEFERRABLE exclusion constraints add extra runtime cost. Only mark a constraint deferrable if a single transaction genuinely shifts adjacent bookings in place.

Sources

  1. postgresql.org
  2. postgresql.org
  3. postgresql.org
  4. docs.djangoproject.com

AI-assisted · Reviewed by PKN

0

Responses

Loading comments…