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

推荐订阅源

I
InfoQ
Spread Privacy
Spread Privacy
GbyAI
GbyAI
F
Fortinet All Blogs
小众软件
小众软件
B
Blog RSS Feed
博客园_首页
量子位
Y
Y Combinator Blog
美团技术团队
H
Hackread – Cybersecurity News, Data Breaches, AI and More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
T
The Blog of Author Tim Ferriss
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Vercel News
Vercel News
Last Week in AI
Last Week in AI
F
Full Disclosure
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
宝玉的分享
宝玉的分享
Microsoft Azure Blog
Microsoft Azure Blog
有赞技术团队
有赞技术团队
A
About on SuperTechFans
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
Tenable Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Project Zero
Project Zero
C
CXSECURITY Database RSS Feed - CXSecurity.com
Engineering at Meta
Engineering at Meta
博客园 - 叶小钗
S
SegmentFault 最新的问题
T
Threat Research - Cisco Blogs
博客园 - 司徒正美
MyScale Blog
MyScale Blog
云风的 BLOG
云风的 BLOG
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
V
Vulnerabilities – Threatpost
S
Schneier on Security
Latest news
Latest news
I
Intezer
A
Arctic Wolf
T
Threatpost

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Preventing double-bookings with PostgreSQL exclusion constraints
Lex Mulier · 2026-05-21 · via DEV Community

Most booking apps detect overlapping reservations in application code: pull all stays for the property, loop through them, compare date ranges. This works until two HTTP requests fly in at the same time and the database commits both. Welcome to Saturday lunch with two families standing at the front door of the same vacation home.

The fix is to push the conflict check down into the database, using PostgreSQL's tstzrange type and an EXCLUDE constraint. The result is bulletproof: even under perfectly-concurrent transactions, the database itself rejects the second booking with a constraint violation.

I'll walk through the pattern below, with the schema and a small test. This is the conflict-detection core of Ripazo, the booking app I'm building for families who co-own a vacation home.

The naive approach (and why it breaks)

Here's how most of us reach for it on day one:

async function createBooking(propertyId: string, start: Date, end: Date) {
  const overlapping = await db.query(`
    SELECT id FROM bookings
    WHERE property_id = $1
      AND $2 < end_at
      AND $3 > start_at
  `, [propertyId, start, end]);

  if (overlapping.length > 0) {
    throw new Error('Booking conflicts with existing stay');
  }

  return db.query(`
    INSERT INTO bookings (property_id, start_at, end_at)
    VALUES ($1, $2, $3) RETURNING *
  `, [propertyId, start, end]);
}

Enter fullscreen mode Exit fullscreen mode

This is the textbook "check-then-insert" anti-pattern. The check and the insert are two separate database operations. Between them, a concurrent transaction can sneak its own booking into the gap. Under realistic load, you will eventually get two bookings overlapping for the same property, and the only signal will be an angry email.

Wrapping the function in a transaction doesn't help unless you also escalate the isolation level. And even then, lock contention pushes the problem somewhere else. Let's fix it at the schema level instead.

PostgreSQL range types in 30 seconds

PostgreSQL ships with range types built in: int4range, numrange, tsrange (timestamp without timezone), and the one we want, tstzrange (timestamp WITH timezone). A range value combines a lower bound, an upper bound, and inclusivity flags:

SELECT tstzrange('2026-06-05 14:00+00', '2026-06-12 11:00+00', '[)');
-- ["2026-06-05 14:00:00+00","2026-06-12 11:00:00+00")

Enter fullscreen mode Exit fullscreen mode

The [) means "lower inclusive, upper exclusive" — the canonical convention for date ranges. The 5th overlaps with itself but the 12th is when the next booking can start.

Range types come with overlap and containment operators baked in:

SELECT tstzrange('2026-06-05', '2026-06-12', '[)') &&
       tstzrange('2026-06-10', '2026-06-15', '[)');
-- true (they overlap on Jun 10-11)

Enter fullscreen mode Exit fullscreen mode

That && is the overlap operator. It's also what we'll feed to the constraint.

The exclusion constraint

An EXCLUDE constraint says: across all rows in this table, no two rows can have these column values where this operator returns true. Combine it with a range column and the overlap operator, and the database refuses to insert a second row whose range overlaps an existing row's range.

CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE bookings (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  property_id uuid NOT NULL REFERENCES properties(id),
  stay        tstzrange NOT NULL,
  status      booking_status NOT NULL DEFAULT 'confirmed',
  created_at  timestamptz NOT NULL DEFAULT now(),

  EXCLUDE USING gist (
    property_id WITH =,
    stay        WITH &&
  ) WHERE (status = 'confirmed')
);

Enter fullscreen mode Exit fullscreen mode

Three things to notice:

  1. btree_gist lets us mix the = equality operator (B-tree backed) with the && overlap operator (GiST backed) in a single GiST index. Without this extension you can only put the range column in the constraint, not property_id as a co-key.

  2. The stay column is a single tstzrange, not two separate timestamp columns. This is a real schema-level choice — your application code now passes a range, not two dates. Most ORMs handle this fine; in Drizzle/Prisma you model it as a custom type.

  3. The WHERE (status = 'confirmed') clause means cancelled or tentative bookings can overlap with confirmed ones. This matters for "options" — a tentative hold that doesn't block confirmed reservations — and for keeping cancelled history in the table.

Insert two overlapping confirmed bookings, and you get:

ERROR:  conflicting key value violates exclusion constraint "bookings_property_id_stay_excl"
DETAIL:  Key (property_id, stay)=(...) conflicts with existing key.

Enter fullscreen mode Exit fullscreen mode

That error bubbles up regardless of concurrency. There is no race window, no isolation-level tuning, no application-side double-check.

Translating the error for users

Catch the database error and translate it into something humans can read:

import { DatabaseError } from 'pg';

try {
  await db.bookings.insert({ propertyId, stay });
} catch (e) {
  if (e instanceof DatabaseError && e.code === '23P01') {
    throw new BookingConflictError(
      'These dates overlap with an existing booking.'
    );
  }
  throw e;
}

Enter fullscreen mode Exit fullscreen mode

Postgres error code 23P01 is "exclusion_violation". Match on the code, not the message — the wording changes between versions and locales.

Tentative holds without blocking

The WHERE (status = 'confirmed') clause is the key to a feature most booking apps don't ship: tentative holds. Let one family say "we'd like this week but aren't sure yet" without locking everyone else out:

-- A tentative hold doesn't block anyone
INSERT INTO bookings (property_id, stay, status)
VALUES ($1, $2, 'option');

-- Someone else confirms the same week, no error
INSERT INTO bookings (property_id, stay, status)
VALUES ($1, $2, 'confirmed');

-- The original tentative tries to confirm — now it fails
UPDATE bookings SET status = 'confirmed' WHERE id = $1;
-- ERROR: exclusion constraint violation. By design.

Enter fullscreen mode Exit fullscreen mode

Tentative bookings can stack. Only confirmed bookings are mutually exclusive. The UPDATE that promotes a tentative to confirmed is checked against the constraint at update time, which is exactly the right moment to surface the conflict.

Half-open intervals: the off-by-one trap

I mentioned [) (lower inclusive, upper exclusive) above. It's not aesthetic, it's structural. With closed intervals on both ends, you can't represent two back-to-back bookings without a false overlap:

Booking A: [2026-06-05, 2026-06-12]   -- 12th inclusive
Booking B: [2026-06-12, 2026-06-19]   -- 12th inclusive
                            ^^^^^^^^
            Both rows touch on the 12th → overlap → exclusion error.

Enter fullscreen mode Exit fullscreen mode

With [):

Booking A: [2026-06-05, 2026-06-12)   -- 12th NOT included
Booking B: [2026-06-12, 2026-06-19)   -- 12th included
            They share a boundary but do not overlap.

Enter fullscreen mode Exit fullscreen mode

In a vacation home, this maps to the real-world handover: family A checks out on the 12th, family B checks in on the 12th, the cleaner shows up between them. The boundary is shared, not duplicated.

Supabase / RLS interaction

If you're on Supabase (or any Postgres with RLS), the exclusion constraint runs BEFORE row-level security policies. That's the right order — you don't want to leak booking ranges through a constraint-violation error message to a user who shouldn't be able to see the conflicting row. Constraint violations include the conflicting key in the error detail, so make sure your app code translates 23P01 to a generic "this slot isn't available" string before it reaches the client. Don't pass the raw DETAIL.

Test it

A minimal smoke test that proves the constraint works:

BEGIN;
  INSERT INTO bookings (property_id, stay)
  VALUES ('11111111-1111-1111-1111-111111111111',
          tstzrange('2026-06-05', '2026-06-12', '[)'));

  -- This second insert must fail with 23P01
  INSERT INTO bookings (property_id, stay)
  VALUES ('11111111-1111-1111-1111-111111111111',
          tstzrange('2026-06-10', '2026-06-15', '[)'));
ROLLBACK;

Enter fullscreen mode Exit fullscreen mode

You can also write a Node.js concurrency test that fires N parallel INSERT requests and asserts that exactly one succeeds. The constraint holds across true concurrent transactions — no application locks needed.

What changes operationally

The day this shipped in Ripazo, the application-side conflict-detection code shrunk to a single try/catch. The schema does the work. There's no "what if two people click confirm at the same time" question anymore.

It also makes the audit trail honest. Every conflict the database refuses is a real concurrent attempt, not a phantom result of stale cache. When two cousins both try to confirm the same week, both requests reach the database, one wins, one gets the constraint error, the loser sees a clear "this week was just taken" message and the calendar updates in real time.

For the product side of why this matters in a co-owned household (and what fails when you try to run a shared house on Google Calendar), there's the longer write-up on ripazo.com.

tl;dr

  • Don't check-then-insert. Push conflict detection into the schema.
  • Use tstzrange + EXCLUDE USING gist + the btree_gist extension for equality co-keys.
  • Half-open intervals ([)) let you do same-day handovers without phantom conflicts.
  • A WHERE clause on the constraint gives you tentative holds for free.
  • Catch error code 23P01 in app code and translate to something users can read.

If you're building any kind of reservation, calendar, or scheduling product, this pattern saves a long, miserable Saturday.