postgres-performance
Tune Postgres runtime performance — pg_stat_statements, vacuum/bloat/HOT, index types, locks, pooling. Not server config (audit-pg-config).
- License 许可
- MIT
- 最近更新
- 2026-10-29
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- postgres-performance
- description
- Tune Postgres runtime performance — pg_stat_statements, vacuum/bloat/HOT, index types, locks, pooling. Not server config (audit-pg-config).
02 资源文件 1
- 参考文档references/catalog-queries.md3.6 KB
03 SKILL.md 正文
postgres-performance
Postgres performance is MVCC economics: every update writes a new row version, and vacuum, indexes, and long transactions decide whether that stays cheap. Measure with the catalog, then change one thing.
Mode: analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked [TBD] or [VERIFY], never filled in.
When to use
- A Postgres workload is slow, bloated, lagging replicas, or burning IO/CPU and you need Postgres-specific causes and fixes.
- Designing a high-write or large-table Postgres schema (queue table, event log, time series) for performance.
- Following
polymath-database:db-performance-triageonce the engine is confirmed as Postgres.
Not this when: you only need the server parameters sanity-checked — polymath-backend:audit-pg-config. For reading one plan — polymath-data:sql-optimize; for lock review of a schema change — polymath-backend:review-migration.
Inputs
- Postgres version (features differ:
pg_stat_ioandMERGEneed 15–16+,INCLUDEindexes 11+, partition pruning improved through 12–14), managed/self-hosted, RAM/vCPU/storage. - Output of the catalog queries in references/catalog-queries.md for the affected window;
pg_stat_statementsmust be enabled or say so. - The workload shape: OLTP / queue / append-only / analytics, write rate, table sizes, and the pooler in front (PgBouncer mode).
Read-only. SELECT/SHOW/EXPLAIN only; EXPLAIN ANALYZE of writes inside BEGIN … ROLLBACK and preferably on a replica. Never run VACUUM FULL, REINDEX, ALTER SYSTEM, or pg_terminate_backend from this skill — recommend; the owner applies.
Procedure
- Find the load. Rank
pg_stat_statementsbytotal_exec_timeand bycalls; for the top few notemean_exec_time,rows,shared_blks_read,temp_blks_written. Samplepg_stat_activitywait events repeatedly (IO:DataFileRead,LWLock:*,Lock:transactionid,Client:ClientRead,IPC:*).Client:ClientReaddominating means the app, network, or an idle-in-transaction pattern — not the database. - Read plans the Postgres way.
EXPLAIN (ANALYZE, BUFFERS, SETTINGS): actual vs estimated rows (an order-of-magnitude drift means stats or correlation problems),Rows Removed by Filter,Heap Fetcheson an Index Only Scan (stale visibility map),Sort Method: external merge,Batches > 1on hash (spill), nested loop with highloops. Fixes in order:ANALYZE; raise per-columnSTATISTICSor add extended statistics (CREATE STATISTICS … (dependencies, ndistinct, mcv)) for correlated columns; then index/query changes. Never leaveenable_seqscan = offin place. - Index kind and shape. B-tree default; partial indexes for queue/status predicates;
INCLUDEfor covering hot reads; GIN for JSONB/array/FTS (gin_pending_listandfastupdatetrade write latency for throughput); BRIN for huge append-only, time-correlated tables;pg_trgmforLIKE '%x%'. Build withCREATE INDEX CONCURRENTLY; check for leftoverINVALIDindexes. Full design inpolymath-database:index-strategy. - MVCC, vacuum, bloat.
- Dead tuples accumulate on every
UPDATE/DELETE; autovacuum reclaims them if nothing pins the xmin horizon. The usual blockers: long transactions,idle in transaction, forgotten replication slots,hot_standby_feedbackwith long replica queries, orphaned prepared transactions. Find the oldest xmin holder before touching vacuum settings. - Lower
autovacuum_vacuum_scale_factor(and setautovacuum_vacuum_insert_scale_factorfor append-only tables — freezes and the visibility map need it) per large table; raiseautovacuum_vacuum_cost_limitif autovacuum can't keep pace on fast storage. - HOT updates avoid index writes when no indexed column changes and the page has room: set
fillfactor70–90 on hot-update tables and don't index frequently updated columns. Checkn_tup_hot_upd / n_tup_updinpg_stat_user_tables. - Transaction ID wraparound: monitor
age(datfrozenxid)/relfrozenxid; anti-wraparound vacuums are not cancellable and not optional.
- Dead tuples accumulate on every
- Queue/hot-row patterns. A table used as a queue churns dead tuples — use
FOR UPDATE SKIP LOCKEDwith a partial index on the pending predicate, delete/archive in batches, and vacuum aggressively (or partition and drop). Counters and "latest" rows serialize on one tuple: shard the counter, append-and-aggregate, or move to a cache. - Partitioning. Declarative range/list partitioning helps when (a) queries filter on the partition key so pruning works, (b) you drop old data by detaching/dropping partitions instead of
DELETE, (c) vacuum/index builds on a monolith hurt. It does not speed up queries that don't prune, and partition counts in the thousands slow planning. Seepolymath-database:partitioning-sharding. - Connections and pooling. Each backend is a process; > a few hundred active connections thrash. Put PgBouncer in
transactionmode (no session state: prepared statements,SET, advisory locks,LISTENneed care), size the server pool to roughly cores × 2–4 for active work, and keepmax_connectionsmodest. Fix the app's pool size before raising server limits. - Locks and contention.
pg_blocking_pids,log_lock_waits,deadlock_timeout. Common causes: long transactions holding row locks,ALTER TABLEqueued behind a long query (and blocking everything behind it — setlock_timeout), foreign-key checks on unindexed referencing columns,SELECT … FOR UPDATEon hot parents. Index every foreign key's referencing column unless you've shown it unneeded. - WAL, checkpoints, replicas.
pg_stat_wal/checkpointer stats for checkpoint pressure (max_wal_size,checkpoint_timeout,wal_compression); replicareplay_lagand recovery conflicts; inactive replication slots retaining WAL (max_slot_wal_keep_size). Offload read-only reporting to replicas only after accounting for lag and feedback bloat. - Memory knobs, last.
work_memis per sort/hash node per connection — raise per session for the job that needs it, not globally;effective_cache_sizeinforms the planner but allocates nothing;shared_buffers~25% RAM is the usual start;maintenance_work_memspeeds index builds and vacuum. Server-level audit ispolymath-backend:audit-pg-config. - Change one thing, re-measure with the same queries and reset deltas (
pg_stat_statements_reset()only on a system you own; otherwise diff two snapshots).
Output
Postgres performance review: ledger-db (PG 15, 32 vCPU / 256 GB, PgBouncer transaction mode)
Load (pg_stat_statements, 24 h)
#1 UPDATE accounts SET balance … WHERE id=$1 38% total · 9k calls/s · mean 1.1 ms · HOT ratio 4%
#2 SELECT … FROM entries WHERE account_id=$1 AND posted_at > $2 27% total · 6k/s · mean 2.0 ms · heap fetches 61%
Waits: 44% IO:DataFileRead, 18% LWLock:WALWrite, 9% Lock:transactionid
Findings
1. accounts is updated on an indexed column (updated_at in accounts_updated_idx) → HOT 4%; every update rewrites 4 indexes.
Fix: drop accounts_updated_idx (0 reads); set fillfactor 80 via a table rewrite in a maintenance window; expect HOT ratio > 80%.
2. entries index-only scan does heap fetches 61% → visibility map stale; autovacuum_vacuum_insert_scale_factor is default.
Fix: per-table autovacuum_vacuum_insert_scale_factor = 0.02; verify Heap Fetches → ~0.
3. Oldest xmin holder: replication slot "bi_etl" inactive 3 d, pinning 220 GB WAL and vacuum.
Fix: confirm the consumer is gone, drop the slot; set max_slot_wal_keep_size.
Not the cause (checked): connections (active 31), checkpoints (timed 96%), planner estimates (within 2×).
Order: 3 → 2 → 1 (risk ascending; 1 needs a rewrite window).
Verify: accounts HOT ratio, entries Heap Fetches, WAL retained, p99 of #1 and #2.
Unknowns: [VERIFY: bi_etl slot is truly abandoned — ask its owner before dropping].
Quality bar
- Findings cite catalog evidence (a
pg_stat_*view, a plan field, a wait event), not folklore. - The xmin horizon is checked before any vacuum or bloat remedy is proposed.
- Fixes name the verification metric; destructive steps (
REINDEX, rewrite, slot drop) carry a rollback or owner-confirmation note. - Version-dependent features are stated with the version needed.
- Connection pooling constraints (transaction mode vs session state) are respected in recommendations.
Anti-patterns to avoid
- Raising
max_connectionsorwork_memglobally as the first move. - Disabling autovacuum "for now", or running
VACUUM FULLon a hot table (it takes anACCESS EXCLUSIVElock and rewrites it). - Adding an index to a high-write table without checking HOT impact and write cost.
- Using
enable_*planner switches, or hints, as the permanent fix instead of fixing statistics. - A long-lived
idle in transactionsession, or an unbounded transaction around a batch job. - Partitioning a table whose queries never filter on the partition key.
04 同仓库更多 Skills
runbook
Write or refresh an operational runbook for an alert/symptom; structured as TL;DR + Pre-checks + Steps + Verification + Rollback + Escalation.
rfc
Draft a lightweight design RFC to docs/rfcs/<slug>.md; Summary, Motivation, Detailed design, Drawbacks, Alternatives, Unresolved questions. A proposal to debate, not a recorded decision (adr).
editorial-pass
Review and tighten prose in a Markdown artifact for a target tone (terse, formal, friendly) without dropping information; preserve quotations and load-bearing constraints.
architecture-review-facilitation
Run an architecture review as a process — entry criteria, reviewer checklist, decision log, and follow-up actions — pairing the design artifact with a red-team pass.
architecture-doc
Write a C4-style architecture document; System Context + Containers (+ Components when interesting) with mermaid diagrams. Describes structure, not a decision (adr) or proposal (rfc).
adr
Write an Architecture Decision Record (Michael Nygard format) to docs/adrs/NNNN-<slug>.md; frontmatter validated by the ADR artifact schema. Records a made decision, not a proposal to debate (rfc).