惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Postgres EXCLUDE Constraints: Stop Double-Booking Without Application Locks
The Practica · 2026-05-28 · via The Practical Developer

The booking endpoint had a SELECT followed by an INSERT, and it had worked for two years. A user picked a time slot, the app checked for overlapping reservations, and if nothing was found it inserted a new row. Then the marketing team ran a flash sale for a popular conference room. Forty users hit the same 9:00 AM slot within a ten-second window. The application served ten overlapping bookings before the cache even caught up. Customer support spent the next morning issuing refunds and apology emails.

The bug was not in the application logic. The application logic was correct. The bug was the assumption that a read followed by a write is an atomic operation. It is not. In a concurrent system, the gap between the SELECT and the INSERT is a window where another transaction can insert the same slot, commit, and make your check a lie. You cannot close that window in application code. You close it in the database.

Postgres has a constraint type that most teams have never used. It is called EXCLUDE, and it is a generalization of UNIQUE that understands ranges, overlaps, and custom operators. This post is the DDL, the extension, the index, and the error handling that turns a double-booking from a concurrency failure into an impossibility.

Why application-level checks always lose

The naive pattern looks like this:

SELECT 1 FROM bookings
WHERE room_id = $1
  AND start_time < $3
  AND end_time > $2;

If the query returns zero rows, the application inserts the booking. The logic is sound, but it is not safe. Here is the window:

  1. Transaction A checks for overlaps. Finds none.
  2. Transaction B checks for overlaps. Finds none.
  3. Transaction A inserts and commits.
  4. Transaction B inserts and commits.

Both checkers saw a clean slot because neither insert existed at the time of the check. This is a classic Time-of-Check to Time-of-Use (TOCTOU) race, and it happens at any concurrency level above one.

SELECT FOR UPDATE does not save you because there is no existing row to lock. Each transaction is checking for the absence of a row, and there is nothing to pin. Serializable isolation in Postgres can catch this, but it raises a 40001 (serialization failure) that your application must then detect and retry. If your retry loop is not bulletproof, you trade one bug for another. Worse, serializable mode applies to the entire transaction, which means every other table touch in the same transaction is also subject to serialization conflicts you did not ask for. The overhead is real, and the retry complexity is non-trivial.

Advisory locks are another common workaround. Map (room_id, time_slot) to an integer, lock it with pg_advisory_xact_lock, then insert. This works, but it is an application-layer semaphore that sits outside the schema. It does not survive schema changes gracefully, it requires careful key collision management, and it centralizes load on a single lock namespace that can become a bottleneck under extreme concurrency.

What you actually need is a declarative, schema-level rule that says: “For any given room, two bookings cannot occupy overlapping time ranges.” That is exactly what EXCLUDE does.

EXCLUDE is UNIQUE with superpowers

Most developers think UNIQUE is a separate, primitive constraint. It is not. UNIQUE(email) is syntactic sugar for:

EXCLUDE USING btree (email WITH =)

EXCLUDE says: “For any two rows, if the listed expressions compare as true using the given operators, reject the second insert.” UNIQUE uses the equality operator (=) on the column. EXCLUDE generalizes this to any operator supported by an index access method.

To block overlapping time ranges, we use the GiST index access method and the && (range overlap) operator. The constraint says: “For any two rows with the same room_id, the time ranges must not overlap.”

The prerequisite is the btree_gist extension, which lets GiST indexes handle scalar equality (=) alongside range operators:

CREATE EXTENSION IF NOT EXISTS btree_gist;

Without this, GiST does not know how to compare room_id (an integer) for equality inside an exclusion constraint.

The DDL that makes double-booking impossible

Here is the table. It is ordinary until the last line.

CREATE TABLE bookings (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    room_id int NOT NULL,
    start_time timestamptz NOT NULL,
    end_time timestamptz NOT NULL,
    user_id int NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now(),
    CONSTRAINT no_overlapping_bookings
      EXCLUDE USING gist (
        room_id WITH =,
        tstzrange(start_time, end_time, '[)') WITH &&
      )
);

Break it down:

  • EXCLUDE USING gist tells Postgres to build a GiST index to enforce the rule.
  • room_id WITH = means the constraint only compares rows that have the same room_id. A booking in room 3 does not interact with a booking in room 7.
  • tstzrange(start_time, end_time, '[)') WITH && constructs a timestamptz range from the columns and says: “If the ranges overlap (&&), reject.”
  • [) means the start is inclusive and the end is exclusive. A booking ending at 10:00 does not conflict with a booking starting at 10:00. This is the correct semantics for continuous time slots.

The constraint is named (no_overlapping_bookings) so that violation errors are readable, and so you can drop it later without guessing.

What happens when the race reoccurs

With the constraint in place, the same flash sale scenario plays out differently:

  1. Transaction A inserts the 9:00 AM slot. GiST index checks room 3, sees no overlap, and allows it.
  2. Transaction B tries to insert the same slot. GiST index checks room 3, finds the row committed by transaction A (or sees the overlapping range in progress and waits), and rejects the second insert with a constraint violation.

If transaction A has not yet committed, transaction B blocks until A commits or rolls back. If A commits with an overlap, B gets the error immediately. If A rolls back, B succeeds. Either way, the database guarantees that no two committed rows overlap for the same room.

Handling the exclusion violation in Node.js

The postgres client (pg) throws an error with code 23P01 when an exclusion constraint is violated. Your route handler should catch it and surface a clean, actionable error to the client.

import { Pool } from 'pg';

export const pool = new Pool({ connectionString: process.env.DATABASE_URL });

export async function createBooking(
  roomId: number,
  startTime: Date,
  endTime: Date,
  userId: number,
) {
  try {
    await pool.query(
      `INSERT INTO bookings (room_id, start_time, end_time, user_id)
       VALUES ($1, $2, $3, $4)`,
      [roomId, startTime, endTime, userId],
    );
  } catch (err: any) {
    if (err.code === '23P01') {
      const clean = new Error(
        'This time slot is no longer available. Please select another.',
      );
      (clean as any).statusCode = 409;
      throw clean;
    }
    throw err;
  }
}

The client gets a 409 Conflict with a clear message. The database has already done the hard work of locking, comparing, and rejecting. Your application does not need a retry loop, an advisory lock, or a distributed transaction coordinator.

If you use an ORM like Prisma or Drizzle, the same error bubbles up as a unique-constraint-like exception. Map the Postgres code in your error interceptor, not in the business logic.

Soft deletes and partial exclusion constraints

Most real systems do not physically delete bookings. They mark them as canceled. If you simply add a canceled_at column, the exclusion constraint still sees the canceled row as a conflict. A user cancels a booking and immediately tries to rebook the same slot, and the database rejects it.

The fix is a partial exclusion constraint:

ALTER TABLE bookings
DROP CONSTRAINT no_overlapping_bookings;

ALTER TABLE bookings
ADD CONSTRAINT no_overlapping_bookings
  EXCLUDE USING gist (
    room_id WITH =,
    tstzrange(start_time, end_time, '[)') WITH &&
  )
  WHERE (canceled_at IS NULL);

The WHERE clause makes the constraint apply only to rows where canceled_at is null. Canceled bookings are invisible to the overlap check. This is identical in spirit to partial unique indexes, but for exclusion constraints. The btree_gist extension must still be installed.

If you are migrating an existing table, do this during a low-traffic window. Dropping and re-adding the constraint rebuilds the GiST index. For very large tables, consider building the index with CREATE INDEX CONCURRENTLY first, then adding the constraint using the pre-built index:

CREATE INDEX CONCURRENTLY idx_bookings_exclude
ON bookings USING gist (
  room_id,
  tstzrange(start_time, end_time, '[)')
)
WHERE (canceled_at IS NULL);

ALTER TABLE bookings
ADD CONSTRAINT no_overlapping_bookings
  EXCLUDE USING gist (
    room_id WITH =,
    tstzrange(start_time, end_time, '[)') WITH &&
  )
  WHERE (canceled_at IS NULL)
  USING INDEX idx_bookings_exclude;

This avoids the AccessExclusive lock that a plain ALTER TABLE would take while building the index.

Variations: licenses, delivery windows, and seat limits

Exclusion constraints are not limited to room bookings. Any domain where overlapping ranges for a shared resource must be prevented is a candidate.

Software license seats:

CREATE TABLE license_allocations (
    license_key text NOT NULL,
    user_id int NOT NULL,
    start_date date NOT NULL,
    end_date date NOT NULL,
    EXCLUDE USING gist (
      license_key WITH =,
      daterange(start_date, end_date, '[)') WITH &&
    )
    WHERE (revoked = false)
);

This ensures a user cannot be assigned overlapping license periods for the same key.

Delivery windows per vehicle:

CREATE TABLE routes (
    vehicle_id int NOT NULL,
    delivery_zone tstzrange NOT NULL,
    EXCLUDE USING gist (
      vehicle_id WITH =,
      delivery_zone WITH &&
    )
);

Here the range is stored directly as a tstzrange column, which simplifies the constraint expression.

Parking space reservations:

CREATE TABLE parking_reservations (
    space_id int NOT NULL,
    reserved_during tstzrange NOT NULL,
    EXCLUDE USING gist (
      space_id WITH =,
      reserved_during WITH &&
    )
    WHERE (checked_out_at IS NULL)
);

Performance: what GiST costs you

GiST indexes are slower to insert and update than B-tree indexes. The penalty is usually 2 to 3 times the cost of a B-tree insert. For a booking system with hundreds of inserts per second, this is negligible. For a high-throughput event stream with tens of thousands of inserts per second, an exclusion constraint on the hot path may be the wrong tool. Measure your insert latency before and after adding the constraint.

If the table is large (millions of rows), the GiST index size will also be larger than an equivalent B-tree. Monitor pg_size_pretty(pg_total_relation_size('bookings')) after creation.

Partitioning by room_id or by time range can help if a single table becomes unwieldy. In a partitioned table, you must create the exclusion constraint on each partition. Postgres does not yet support global exclusion constraints across partition boundaries as a single declaration, so plan your partition key with this in mind. Range partitioning by month with a local exclusion constraint per partition works well for time-series bookings.

When not to use EXCLUDE

Exclusion constraints are powerful, but they are not universal.

Aggregate limits that depend on counts. If the rule is “a user may have at most three active bookings,” exclusion constraints cannot express that. Use a trigger, or enforce it in application code with a locking read, or model the remaining capacity explicitly in a room_availability table and lock that row.

Cross-table overlap rules. Exclusion constraints work on a single table. If you need to check that a booking in bookings does not overlap with a maintenance window in maintenance_windows, use a trigger or application logic.

High-frequency, low-cardinality overlap detection. If you are inserting 50,000 events per second and the overlap check is rare (e.g., collision detection in a game), a GiST index may be too expensive. Consider a partitioned in-memory check or a specialized spatial index like R-tree in an extension better suited for the write volume.

The production checklist

Before you add an exclusion constraint to a live table:

  1. Install btree_gist in a migration that runs before the constraint DDL. On managed Postgres (RDS, Cloud SQL, Supabase), the extension is usually allowed.
  2. Build the index CONCURRENTLY if the table has more than 100,000 rows. Then attach the constraint using the index.
  3. Verify your application catches 23P01 and maps it to a 409 or equivalent user-facing error. Do not let the raw Postgres error leak to the client.
  4. Add a test that fires two concurrent inserts for the same slot and asserts that exactly one succeeds.
  5. Monitor insert latency after shipping. GiST insert cost is real, even if small.

The takeaway

Double-booking is not a bug in your check logic. It is a bug in your trust model. You trusted application-level reads to guard writes, and concurrency proved you wrong. The fix is not more locks, more retries, or more clever JavaScript. The fix is a database constraint that understands time ranges.

Six lines of DDL replace an entire class of race conditions. Two transactions trying to book the same room at the same time now result in one success and one clean, immediate failure that your application catches and surfaces. No middleware. No distributed lock. No guesswork.

Your application code should decide what happens when a slot is taken. Postgres should decide whether the slot is taken at all.

A note from Yojji

The kind of data-modeling discipline that turns a concurrency race into a schema-level guarantee (partial exclusion constraints, range types, and the index strategy that makes them fast) is the kind of backend engineering Yojji builds into the systems they ship for clients.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their teams of 50+ senior engineers specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and the Postgres data modeling that keeps production systems correct under real load. If your application is still fighting race conditions with application-level checks, Yojji can help you move the guarantees to the right layer.