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

推荐订阅源

L
LangChain Blog
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
S
Security @ Cisco Blogs
N
News and Events Feed by Topic
H
Hacker News: Front Page
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
N
Netflix TechBlog - Medium
U
Unit 42
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
Google Online Security Blog
Google Online Security Blog
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
T
Tenable Blog
博客园 - 叶小钗
D
DataBreaches.Net
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
人人都是产品经理
人人都是产品经理
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
量子位
P
Proofpoint News Feed
H
Help Net Security
Blog — PlanetScale
Blog — PlanetScale
宝玉的分享
宝玉的分享
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Fortinet All Blogs
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
S
Schneier on Security
V
Vulnerabilities – Threatpost
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
G
GRAHAM CLULEY
G
Google Developers Blog
月光博客
月光博客
V
V2EX
T
Troy Hunt's Blog
A
Arctic Wolf

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
5 PostgreSQL locking behaviors that trip people up
Shinya Kato · 2026-05-27 · via DEV Community

Introduction

PostgreSQL uses MVCC (Multi-Version Concurrency Control) for concurrency control: reads never block writes, and writes never block reads.

Its locking system has 8 table-level lock modes and 4 row-level lock modes, and the conflict tables in the documentation tell you exactly which lock modes conflict with which.

In practice, though, once you actually operate PostgreSQL, locks end up conflicting in places you never expected. Queries take far longer than anticipated, and in the worst case you end up with an outage.

This article walks through five of these counterintuitive locking behaviors.

Environment

  • Version: PostgreSQL 18
  • Transaction isolation level: READ COMMITTED (the default)

1. Once an ACCESS EXCLUSIVE request is queued, subsequent queries get blocked in a chain

The first one: an ALTER TABLE that should finish instantly can bring your entire service to a halt.

Suppose one session is running a long SELECT on table t, and another session runs the following ALTER TABLE:

Session 1

SELECT pg_sleep(600) FROM t LIMIT 1; -- a long-running SELECT

Enter fullscreen mode Exit fullscreen mode

Session 2

ALTER TABLE t ADD COLUMN name text;

Enter fullscreen mode Exit fullscreen mode

Since Session 1 holds an ACCESS SHARE lock on table t, the ACCESS EXCLUSIVE lock that Session 2's ALTER TABLE requires is forced to wait. So far, this is expected behavior.

But PostgreSQL's lock waiting works like a FIFO queue. While the ACCESS EXCLUSIVE lock is waiting, any SELECT issued against table t afterward gets stuck behind it — even though that SELECT does not conflict with Session 1's currently running SELECT at all.

Diagram showing subsequent SELECTs also forced to wait in the lock queue

Besides a long-running SELECT, the same thing happens with a session that ran a SELECT inside a BEGIN transaction and then left it open without COMMIT/ROLLBACK (a so-called idle in transaction session). An ACCESS SHARE lock is held until the transaction ends, so even if the SELECT itself finished in an instant, simply forgetting to close the transaction will keep blocking ALTER TABLE. This is often caused by a missing commit in the application, or by a connection left idle after fetching its results — so watch out for it.

The result is the following chain:

  1. A long-running SELECT is executing.
  2. An ALTER TABLE (or any statement that acquires an ACCESS EXCLUSIVE lock) is forced to wait due to a lock conflict.
  3. Every subsequent SELECT lines up behind the lock wait in step 2.

This chained blocking makes your SELECTs wait far longer than expected, which can lead to an outage.

Mitigations

  • In transactions that run statements acquiring an ACCESS EXCLUSIVE lock, set lock_timeout so the lock wait can't drag on indefinitely.
  • Check in advance for long-running queries via the pg_stat_activity view.

2. The "invisible" deadlock caused by foreign key constraints

The second one comes from the locks that a foreign key constraint acquires implicitly.

When you run an INSERT, PostgreSQL takes a FOR KEY SHARE lock on the referenced row in every parent table that the foreign keys point to. This mechanism prevents the situation where deleting or updating the referenced row in the parent table would break the referencing side's integrity.

For example, when you INSERT into table t, a FOR KEY SHARE lock is automatically taken on the referenced row in the parent table s. Because FOR KEY SHARE and FOR UPDATE conflict, a deadlock arises if two sessions each "lock a different row in s with FOR UPDATE, then run an INSERT whose foreign key references the other session's row" in opposite orders — a circular wait forms.

Session 1

BEGIN;
SELECT * FROM s WHERE id=1 FOR UPDATE; -- lock row s.id=1 with FOR UPDATE

Enter fullscreen mode Exit fullscreen mode

Session 2

BEGIN;
SELECT * FROM s WHERE id=2 FOR UPDATE; -- lock row s.id=2 with FOR UPDATE

Enter fullscreen mode Exit fullscreen mode

Session 1

INSERT INTO t (s_id) VALUES (2); -- wants FOR KEY SHARE on row s.id=2 (waits for Session 2)

Enter fullscreen mode Exit fullscreen mode

Session 2

INSERT INTO t (s_id) VALUES (1); -- wants FOR KEY SHARE on row s.id=1 (deadlock detected)

Enter fullscreen mode Exit fullscreen mode

What's counterintuitive here is:

  • Application code that contains nothing but INSERT statements is implicitly locking rows in the foreign key's parent table.
  • Looking at the application's SQL, the lock acquisition never surfaces.

Mitigations

  • Avoid a design where multiple sessions lock a row in a foreign key's parent table with FOR UPDATE and then INSERT a different row referencing it, in opposite orders — that causes deadlocks.
  • If you really need it, make the lock acquisition order consistent across the entire application (for example, always lock rows in s in ascending id order — enforce a single, one-directional locking order).
  • Deadlocks are always reported as errors, so implement with retries in mind.

3. A deadlock between two INSERTs caused by the unique constraint duplicate check

The third one: two transactions that only do INSERTs can deadlock simply by inserting each other's already-inserted values in opposite orders.

Run SQL like the following:

Session 1

BEGIN;
INSERT INTO t (id) VALUES (1);

Enter fullscreen mode Exit fullscreen mode

Session 2

BEGIN;
INSERT INTO t (id) VALUES (2);

Enter fullscreen mode Exit fullscreen mode

Session 1

INSERT INTO t (id) VALUES (2); -- waits for Session 2 to commit

Enter fullscreen mode Exit fullscreen mode

Session 2

INSERT INTO t (id) VALUES (1); -- deadlock detected

Enter fullscreen mode Exit fullscreen mode

The reason this happens is that the duplicate check for PRIMARY KEY and UNIQUE constraints waits for the other transaction to finish if that transaction is currently inserting the same value. This is how PostgreSQL settles the outcome: "if the other transaction commits, it's a unique constraint violation; if it rolls back, the insert succeeds."

So in the example above:

  • Session 1 tries to insert id=2 → Session 2 is inserting id=2, so it waits.
  • Session 2 tries to insert id=1 → Session 1 is inserting id=1, so it waits.
  • They wait on each other's commit → deadlock detected.

Mitigations

  • Avoid a design where the same value can be inserted concurrently from multiple sessions (using a sequence such as SERIAL/IDENTITY avoids duplicates entirely).
  • As mentioned in the previous section's mitigations, deadlocks are reported as errors, so implement with retries in mind.

4. Only the transaction-ID-wraparound-prevention autovacuum refuses to yield on conflict

The fourth one is about an exceptional behavior of autovacuum.

When the SHARE UPDATE EXCLUSIVE lock that autovacuum acquires conflicts with another statement, autovacuum is normally the one that gets canceled, so it doesn't block other statements for long. That's why the common understanding is "it's fine to just leave autovacuum running."

There is one exception, however: the autovacuum running to prevent transaction ID wraparound (the one whose query column in pg_stat_activity ends with (to prevent wraparound)) is not canceled automatically, even when there is a conflict.

Here's what actually happens:

  1. A table's relfrozenxid age exceeds autovacuum_freeze_max_age.
  2. The wraparound-prevention autovacuum starts (holding SHARE UPDATE EXCLUSIVE).
  3. Another process issues an ALTER TABLE to create a partition.
  4. The ALTER TABLE waits for autovacuum ← it would normally be canceled, but it isn't.
  5. Every SELECT lines up in the queue ← the chained blocking described in #1 occurs.

When this combines with the first behavior, it can turn fatal in a hurry — that's the key point.

Mitigations

  • If you see autovacuum: VACUUM ... (to prevent wraparound) in pg_stat_activity, recognize that an autovacuum that won't be canceled is running, and wait for it to complete.
  • Prevention matters more than reacting after the fact. Periodically monitor age(relfrozenxid) in pg_class to know which tables are approaching autovacuum_freeze_max_age (200 million transactions by default).
  SELECT relname, age(relfrozenxid)
  FROM pg_class
  WHERE relkind = 'r'
  ORDER BY age(relfrozenxid) DESC;

Enter fullscreen mode Exit fullscreen mode

  • If you have DDL such as ALTER TABLE planned, check the target table's age(relfrozenxid) beforehand, and if it's close to the threshold, run a manual VACUUM FREEZE before the DDL.

5. VACUUM's hidden ACCESS EXCLUSIVE phase

The last one is also about an exceptional behavior of VACUUM.

Normally VACUUM operates with SHARE UPDATE EXCLUSIVE, but the final truncate phase — truncating empty pages at the end of the table and returning the disk space to the OS — is the one exception: it acquires an ACCESS EXCLUSIVE lock.

As in the earlier examples, if a long-running SELECT is executing while VACUUM waits to acquire that ACCESS EXCLUSIVE lock, subsequent queries all get blocked in the same chained-blocking pattern described in #1.

And on a streaming replication standby, the situation is different. When ACCESS EXCLUSIVE is acquired and released on the primary, that operation reaches the standby as WAL. The standby's WAL replay process tries to apply that operation, but a long-running SELECT executing on the standby conflicts with it, so WAL replay stalls. While WAL replay is stalled, the apply lag for already-received WAL keeps growing, and once that lag exceeds max_standby_streaming_delay, the conflicting SELECT is forcibly canceled and replay resumes.

On the primary, a SELECT is allowed to wait until it finishes naturally; on a standby, the SELECT is forcibly canceled by an external factor (WAL replay). That's the big difference.

Mitigations

  • On PostgreSQL 12 and later, you can disable VACUUM's truncate phase per table with vacuum_truncate = false.
  • PostgreSQL 18 and later also adds a server-wide vacuum_truncate parameter.
  • If you run long-running queries on a standby, set max_standby_streaming_delay (30 seconds by default) higher to extend how long WAL replay is allowed to wait (-1 for unlimited).

Conclusion

Every one of these cases is behavior that emerges because PostgreSQL's lock design faithfully implements the mechanisms needed to keep things correct. Natural as a specification, but a pitfall from an operational point of view.

In particular, the chained blocking in #1 can rapidly escalate into a fatal incident when combined with the other cases, so setting lock_timeout and continuously monitoring pg_stat_activity are the minimum defensive lines you'll want in place.

References