PostgreSQL and MySQL InnoDB differ fundamentally in process model, table layout, and MVCC. PostgreSQL uses a process-per-connection model sharing shared_buffers rather than MySQL's threads, making large idle connection pools heavier and making PgBouncer standard in production. InnoDB stores rows inside a primary-key clustered index, whereas PostgreSQL uses an unordered heap table where every index—including the primary key—points to a physical ctid. For MVCC, PostgreSQL keeps old versions inline in the heap instead of a separate undo log—giving instant rollbacks at the cost of dead tuples needing VACUUM—and it defaults to Read Committed with richer indexing, JSONB, and transactional DDL.
这里还有个很大的副作用叫写放大:因为所有索引都指向物理位置 ctid,一行更新换了位置,表上所有索引都要跟着更新。PostgreSQL 用 HOT 更新来缓解这个问题——只要你改的不是索引列,而且当前数据页里还有空位,新版本就留在同一页里,页内用指针串起来,索引完全不用动。对更新特别频繁的表,我们会把 fillfactor 从默认 100 调低到 80 左右,专门留出空位给 HOT 用。
English PitchEnglish · ~60s
Unlike InnoDB's separate undo log, PostgreSQL stores row versions inline in the heap, stamping each tuple header with xmin for the creating transaction and xmax for the deleting or updating transaction. Readers compare xmin and xmax against their snapshot so reads and writes never block each other. Because UPDATE marks the old tuple's xmax and inserts a new tuple instead of overwriting in place, superseded rows become dead tuples once no active snapshot needs them, awaiting VACUUM. Moving a tuple's ctid normally updates every index, so PostgreSQL uses HOT updates when no indexed column changes and the same page has space—making a lower fillfactor valuable on update-heavy tables.
Key terms:xmin / xmax, dead tuples, write amplification, HOT (Heap-Only Tuple), fillfactor
Likely follow-up: "What exact two conditions must hold for PostgreSQL to perform a HOT update instead of updating every index?"
表膨胀在生产里最常见的原因,其实是长事务,尤其是应用代码里的 idle in transaction,或者废弃的复制槽。只要有一个老事务挂着不结束,VACUUM 就动不了它之后产生的所有死元组,表越胀越大,全表扫和索引扫都变慢。另外对上亿行的大表,默认 20% 死元组才触发清理也太晚了,要单独把触发比例调小。
至于事务 ID 回卷,是因为 PostgreSQL 的事务号是 32 位的,跑满约 20 亿个写事务就会绕回来,如果不把老元组标记成永久冻结,老数据会突然“消失”。所以运维上一定要监控最老事务年龄和表膨胀率。
English PitchEnglish · ~55s
Because PostgreSQL UPDATEs and DELETEs leave dead tuples in the heap, Autovacuum is essential for stability. Regular VACUUM works without blocking reads or writes to mark dead space reusable in the Free Space Map, update the Visibility Map for Index-Only Scans, and freeze old transaction IDs—unlike table-locking VACUUM FULL, so online disk shrinking uses pg_repack. Production table bloat typically stems from idle-in-transaction sessions or abandoned replication slots pinning the vacuum horizon, or default 20 percent thresholds firing too late on huge tables. Failing to freeze 32-bit transaction IDs risks wraparound, forcing PostgreSQL to halt writes to protect data.
Key terms:Autovacuum, table bloat, idle in transaction, transaction ID wraparound, pg_repack
Likely follow-up: "How do you tune autovacuum thresholds on a 500-million-row table so bloat does not accumulate before cleanup triggers?"
Because PostgreSQL tables are heaps, every index points to physical ctid locations, and choosing an index depends on operators and data order. B-Tree is the default for equality, ranges, and sorting. GIN is an inverted index for JSONB containment, arrays, and full-text search—fast on reads but slower on writes, where fastupdate pending lists can cause occasional flush spikes. GiST supports geospatial queries, range overlaps, and exclusion constraints like preventing double-booked rooms, while BRIN stores tiny min-max summaries per block range for huge append-only time-series tables—provided physical disk order aligns tightly with the indexed column.
Index-Only Scan 只读索引就返回结果,可用 INCLUDE 附带非键列。但 PostgreSQL 索引不存事务可见性,必须查可见性映射确认整页对所有事务可见才不回表;若页面刚被修改、VACUUM 尚未更新映射,仍需回堆表确认。部分索引只索引满足 WHERE 的行,表达式索引对函数结果建索引,都能大幅缩小体积。
正式解释
1. 覆盖索引与 Index-Only Scan:
SQL
CREATE INDEX idx_orders_user_created ON orders (user_id, created_at) INCLUDE (total_amount);
第二个是部分索引,就是在建索引时加一个 WHERE 条件。比如一张几千万行的订单表,99% 都是已完成的,业务只频繁查待处理的订单,那我只对 status 等于 PENDING 的行建索引,索引小到可以直接全放内存里,更新已完成订单时也完全不用维护这个索引。还可以用它来做“只对未软删除记录生效的唯一索引”。
PostgreSQL provides three powerful indexing features. An Index-Only Scan reads results straight from the index—often attaching non-key columns via INCLUDE—but still hits the heap if visibility isn't guaranteed. Because PostgreSQL index tuples lack xmin/xmax MVCC metadata, scans check the Visibility Map; pages modified since the last VACUUM aren't marked all-visible and require heap checks, visible as high Heap Fetches in EXPLAIN (ANALYZE, BUFFERS). Partial indexes add a WHERE filter (like status = 'PENDING' or deleted_at IS NULL), slashing index size and enabling conditional uniqueness. Expression indexes index IMMUTABLE expressions like lower(email) so matching function queries avoid full table scans.
In PostgreSQL, json stores validated raw text verbatim—preserving whitespace, key order, and duplicates—so writes are slightly faster, but every query re-parses text and cannot use GIN indexes. jsonb stores a parsed binary format, making reads much faster and enabling GIN indexes (jsonb_path_ops for compact @> containment), while an expression B-Tree is even lighter for querying a single fixed key—which is why jsonb wins 99 percent of the time, reserving text or json only when byte-exact payloads matter for signature checks. jsonb fits sparse, evolving attributes or webhook snapshots, not core business columns: you lose foreign keys, strong types, and nested planner stats, and mutating large documents causes heavy TOAST write amplification.
Likely follow-up: "If you only query a single fixed key like payload->>'tenant_id', should you build a GIN index or an expression B-Tree index, and why?"
追问2 个
只查 payload->>'tenant_id',建 GIN 还是 B-Tree?
建表达式 B-Tree ON t ((payload->>'tenant_id')),体积小、写开销低、等值和排序都更快。
ALTER TABLE articles ADDCOLUMN search_vec tsvector
GENERATED ALWAYS AS (to_tsvector('english', coalesce(title,'') ||' '||coalesce(body,''))) STORED;
CREATE INDEX idx_articles_search ON articles USING GIN (search_vec);
SELECT id, title FROM articles
WHERE search_vec @@ websearch_to_tsquery('english', 'postgres index')
ORDERBY ts_rank(search_vec, websearch_to_tsquery('english', 'postgres index')) DESC;
PostgreSQL's isolation levels differ noticeably from the SQL standard and MySQL. It defaults to Read Committed—taking a fresh snapshot per statement—and treats Read Uncommitted identically, so dirty reads never happen. Repeatable Read uses Snapshot Isolation with one snapshot per transaction, preventing both non-repeatable and phantom reads and aborting concurrent updates to the same row, though write skew across disjoint rows remains possible. Serializable eliminates write skew using Serializable Snapshot Isolation (SSI): instead of blocking readers with two-phase locking, it tracks non-blocking predicate locks for dependency cycles and aborts one transaction with SQLState 40001, requiring full transaction retries in application code.
WITH next_job AS (
SELECT id
FROM job_queue
WHERE status ='PENDING'AND run_at <= now()
ORDERBY run_at, id
LIMIT 10FORUPDATESKIP LOCKED
)
UPDATE job_queue j
SET status ='RUNNING', locked_at = now()
FROM next_job
WHERE j.id = next_job.id
RETURNING j.*;
普通 FOR UPDATE:10 个 worker 同时抢第一条,9 个都在等第 1 个释放锁,吞吐极差。
FOR UPDATE SKIP LOCKED:正在被其他事务锁住的行直接跳过,每个 worker 立即拿到互不重叠的一批任务,吞吐随 worker 数线性扩展。
行锁有四种,除了常规的 FOR UPDATE 和 FOR SHARE,PostgreSQL 还专门细化出了 FOR NO KEY UPDATE 和 FOR KEY SHARE。这个设计很巧妙:当你更新父表里一个非主键字段时,拿的是 FOR NO KEY UPDATE;而子表插入数据做外键检查时拿的是 FOR KEY SHARE,这两种锁互不冲突,大大减少了父子表的锁等待。
PostgreSQL locking covers table locks—from ACCESS SHARE on SELECTs up to ACCESS EXCLUSIVE on DDL—four row locks, and in-memory advisory locks. Splitting FOR NO KEY UPDATE from FOR KEY SHARE lets parent non-key updates run alongside child foreign-key checks without blocking. For reliable job queues or Outbox polling, the go-to pattern is SELECT FOR UPDATE SKIP LOCKED: concurrent workers skip already-locked rows and claim the next free batch with zero contention or duplicates. Wrapping it in UPDATE RETURNING atomically claims, updates status, and returns payloads in a single round trip.
Key terms:ACCESS SHARE / ACCESS EXCLUSIVE, FOR NO KEY UPDATE, FOR UPDATE SKIP LOCKED, advisory locks
Likely follow-up: "Why should you prefer transaction-scoped advisory locks over session-scoped advisory locks when using a connection pool?"
Even a fast metadata-only ALTER TABLE can trigger an outage through lock queue blocking. Because ALTER TABLE needs ACCESS EXCLUSIVE, if a long report query holds ACCESS SHARE, the DDL queues—and PostgreSQL blocks every incoming SELECT and UPDATE behind it to prevent DDL starvation, exhausting connection pools within seconds. For zero-downtime migrations, I enforce four rules: set a short lock_timeout like two seconds with retries; create or drop indexes CONCURRENTLY outside transactions and clean up INVALID failures; add constraints as NOT VALID then run non-blocking VALIDATE CONSTRAINT; and use Expand-and-Contract for renames or column type rewrites.
Key terms:lock queue blocking, ACCESS EXCLUSIVE, lock_timeout, CREATE INDEX CONCURRENTLY, NOT VALID / Expand & Contract
Likely follow-up: "Why can CREATE INDEX CONCURRENTLY not run inside a standard transaction block, and what do you do if it fails halfway?"
追问2 个
CREATE INDEX CONCURRENTLY 为什么不能放在事务块里?
它内部需要分两个阶段扫描表并等待现有事务结束,必须独立提交多个内部事务,因此不能嵌套在显式 BEGIN ... COMMIT 中(Flyway/Liquibase 需配置非事务执行)。
怎么给大表已有列安全加上 NOT NULL 约束?
先加 CHECK (col IS NOT NULL) NOT VALID,再 VALIDATE CONSTRAINT;在 PG 12+ 上,已有合法的 CHECK (col IS NOT NULL) 后再执行 SET NOT NULL 优化器会直接复用该约束,无需再次扫全表。
SELECT
a.pid,
a.state,
now() - a.xact_start AS xact_age,
pg_blocking_pids(a.pid) AS blocked_by,
left(a.query, 120) AS query
FROM pg_stat_activity a
WHEREcardinality(pg_blocking_pids(a.pid)) >0OR a.state ='idle in transaction';
2. 止血命令区分:
函数
作用
影响
pg_cancel_backend(pid)
取消该连接当前正在执行的查询(柔和)
连接不断开;对 idle in transaction 无效
pg_terminate_backend(pid)
直接终止整个后端进程并回滚其未提交事务
立即释放所有锁;应用侧收到连接断开错误
3. 生产必配的三条安全超时:
参数
作用
常见线上值
statement_timeout
单条 SQL 最长执行时间,防止慢查询拖垮实例
5s–30s(按业务区分)
lock_timeout
等锁最长时间,防止锁队列雪崩
DDL 1s–3s;在线接口按需设置
idle_in_transaction_session_timeout
事务开启后空闲过久自动断开回滚,防止应用卡在外部 RPC 时一直占锁和卡住 VACUUM
30s–60s
4. 死锁与事务中止态:
deadlock_timeout 默认 1 秒:为了避免每次等锁都做昂贵的环检测,等满 1 秒才启动死锁检测器,确认成环则回滚其中一方(SQLState 40P01)。根治死锁靠统一多行加锁顺序(如按主键升序 ORDER BY id)。
PostgreSQL 事务中止态(25P02):在一个事务块里,如果任意一条语句报错(如唯一键冲突),整个事务会立刻进入 aborted 状态,后续所有语句都会直接报 current transaction is aborted, commands ignored until end of transaction block,必须 ROLLBACK 或提前设 SAVEPOINT 回滚到保存点。
When requests hang on locks, I query pg_stat_activity with pg_blocking_pids(pid) to pinpoint the root blocker and its state. If the blocker is running a slow SQL or DDL, try pg_cancel_backend(pid) first to cancel the query without dropping the connection. If its state is idle in transaction—often an app making a slow HTTP call inside a transaction—cancel won't work, so use pg_terminate_backend(pid) to roll back, free locks, and unpin VACUUM. For deadlocks, Postgres runs cycle detection after deadlock_timeout (default 1s), aborts one transaction with 40P01, and logs the cycle; fix by locking rows in consistent key order. Guard production with statement_timeout, lock_timeout, and idle_in_transaction_session_timeout.
Likely follow-up: "Why does an idle-in-transaction session hurt Autovacuum even if it holds no exclusive table locks, and why can't you just catch a DuplicateKeyException and keep executing SQL in the same Postgres transaction?"
追问2 个
为什么在 PostgreSQL 里用 Spring @Transactional 捕获了 DuplicateKeyException 后,继续执行下一条 SQL 还是报错?
PG 事务内单条语句失败会使整个事务进入 25P02 中止态,必须用 INSERT ... ON CONFLICT DO NOTHING/UPDATE(UPSERT)或 PROPAGATION_NESTED(Savepoint)处理。
线上全局找罪魁祸首,则从 pg_stat_statements 按总耗时排序揪出最吃资源的 Top SQL 逐个优化。
English PitchEnglish · ~55s
To debug slow PostgreSQL queries, I run EXPLAIN (ANALYZE, BUFFERS)—inside BEGIN and ROLLBACK for writes—to inspect real timings, actual row counts, and 8 KB buffer hits versus disk reads. I focus on four signals: large gaps between estimated and actual rows causing bad Nested Loops, fixed with ANALYZE or multi-column CREATE STATISTICS; unexpected Seq Scans or high Heap Fetches on Index-Only Scans signaling overdue VACUUM; total buffer reads as a cache-independent cost metric; and Sort or Hash spills to disk when work_mem is too small. In production, I start from pg_stat_statements sorted by total execution time to fix the heaviest workload queries first.
PostgreSQL relies on Write-Ahead Logging: modifications append sequentially to WAL before data pages flush, powering crash recovery, PITR, and replication. Checkpoints periodically flush dirty shared_buffers pages to bound recovery time, and full_page_writes logs full 8 KB images on first post-checkpoint edits to prevent torn pages. Replication streams this WAL in two modes. Physical streaming replication replays raw WAL bytes instance-wide—low-lag, auto-replicates DDL, read-only standby, same major version—ideal for HA and read scaling. Logical replication decodes WAL into per-table row changes, enabling writable subscribers, CDC (Debezium), and cross-major-version upgrades, though DDL isn't replicated automatically. Always cap replication slots with max_slot_wal_keep_size so stalled replicas never exhaust primary disk.
Likely follow-up: "Why do standby read queries occasionally fail with 'canceling statement due to conflict with recovery', and what is the trade-off of enabling hot_standby_feedback?"
追问2 个
备库读查询为什么偶尔报 canceling statement due to conflict with recovery?
PostgreSQL especially needs PgBouncer because it runs one OS process per connection—thousands of microservice connections from per-Pod HikariCP pools burn RAM, context switches, and snapshot overhead even when mostly idle. PgBouncer multiplexes them onto tens of real backend processes across three modes. Session mode keeps a backend until disconnect: full compatibility, low reuse. Statement mode releases after every SQL statement, breaking multi-statement transactions and rarely used. Transaction mode—the production standard—returns the backend on every commit or rollback for huge multiplexing. Its trade-off is no cross-transaction session state: use SET LOCAL and pg_advisory_xact_lock, skip LISTEN/NOTIFY, and handle server-side prepared statements via PgBouncer 1.21+ or JDBC prepareThreshold=0.
Likely follow-up: "Once you deploy PgBouncer in front of PostgreSQL, do Java services still need HikariCP, and what breaks if you use SET search_path in Transaction mode?"
单表达数千万行、索引装不下内存或需定期清理历史数据时,适合用声明式表分区(常见按时间 RANGE 分区)。两大核心收益:带分区键查询触发分区裁剪跳过无关子表;删旧数据直接 DETACH 并 DROP 子表,秒级完成且零膨胀。生产调优重点管好内存参数、Autovacuum、连接数和 pg_stat_statements。
正式解释
1. 声明式分区(Declarative Partitioning):
支持 RANGE(按月/天时间流水,最常见)、LIST(按地区/租户枚举)、HASH(按 ID 均匀打散)。
收益:
数据生命周期管理:删一年前的日志只需 ALTER TABLE logs DETACH PARTITION logs_2025_01 CONCURRENTLY 再 DROP TABLE,毫秒级完成、不产生死元组、不触发海量 VACUUM。