architecture-postgresql-internals
Use when the user asks about Postgres MVCC, the write-ahead log (WAL), table bloat, autovacuum, dead tuples, transaction ID wraparound, checkpoints, HOT…
от j4flmao★ 47 звёзд на GitHub
Установить architecture-postgresql-internals в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
PostgreSQL Internals
Purpose
Most PostgreSQL production issues (bloat, sudden slowdowns, replication lag, wraparound emergencies, bad plans) are direct consequences of how MVCC, VACUUM, WAL, and the planner work. This skill explains those mechanisms precisely and maps each one to the queries and settings used to diagnose and tune it.
Agent Protocol
Trigger
"MVCC", "bloat", "autovacuum", "VACUUM FULL", "dead tuples", "xid wraparound", "WAL", "checkpoint", "HOT update", "fillfactor", "shared_buffers", "EXPLAIN ANALYZE", "slow query".
Input Context
- PostgreSQL major version, hardware/managed service, workload (OLTP/analytics, write rate).
- Symptoms with timestamps;
pg_stat_*output; slow query plans. - Long-running transactions or replication slots in use.
Output Artifact
Diagnosis with evidence queries, root cause tied to the mechanism, and concrete setting/schema changes.
Response Format
Symptom: {what}
Mechanism: {MVCC|VACUUM|WAL|checkpoint|planner|buffer}
Evidence: {query + key numbers}
Fix: {setting/table option/query change} (reload|restart required)
Verify: {metric to watch}
Completion Criteria
- Root cause supported by catalog/statistics evidence.
- Changes state whether they need reload or restart.
- Long transactions, idle-in-transaction sessions, and stale replication slots checked.
MVCC
- Every row version (tuple) stores
xmin(creating transaction) andxmax(deleting/locking transaction). UPDATE= insert a new version + setxmaxon the old one.DELETEsetsxmax. Old versions stay in the heap.- A snapshot decides visibility: a tuple is visible if
xmincommitted before the snapshot andxmaxis unset, aborted, or not yet committed for that snapshot. Readers never block writers and vice versa; writers on the same row block each other. - HOT (heap-only tuple) updates: if no indexed column changes and the page has free space, the new version stays on the same page and indexes are not updated. Lower
fillfactor(e.g. 80-90) on update-heavy tables to leave room.
VACUUM
- Removes dead tuples no snapshot can see anymore, marks space reusable (does not shrink the file), updates the visibility map (enables index-only scans) and free space map, and freezes old tuples.
VACUUM FULLrewrites the table to return space to the OS but takes anACCESS EXCLUSIVElock; preferpg_repackonline.- What blocks cleanup: long-running or idle-in-transaction sessions, abandoned replication slots, old prepared transactions,
hot_standby_feedbackfrom lagging replicas. Dead tuples newer than the oldest snapshot cannot be removed. - Autovacuum trigger: dead tuples >
autovacuum_vacuum_threshold(50) +autovacuum_vacuum_scale_factor(0.2) × reltuples. On large tables 20% is far too late; set per-table scale factors.
ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.01,
autovacuum_analyze_scale_factor = 0.02,
fillfactor = 90);
Transaction ID Wraparound
XIDs are 32-bit and compared modulo 2^32, so tuples must be frozen before they are ~2 billion transactions old. Autovacuum forces an anti-wraparound vacuum when age(relfrozenxid) exceeds autovacuum_freeze_max_age (default 200 million). If freezing cannot keep up, PostgreSQL eventually refuses new XIDs to protect data.
SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC;
SELECT relname, age(relfrozenxid) AS xid_age, pg_size_pretty(pg_total_relation_size(oid))
FROM pg_class WHERE relkind IN ('r','m','t') ORDER BY 2 DESC LIMIT 10;
WAL and Checkpoints
- Changes are written to the write-ahead log before data pages are flushed; on commit the WAL is flushed (with
synchronous_commit = on), which gives durability. Data pages are written later by the background writer and checkpointer. - Checkpoint: flushes all dirty pages so recovery can start from that point. Triggered by
checkpoint_timeout(default 5 min) or WAL volume reachingmax_wal_size(default 1 GB). Frequent size-triggered checkpoints cause I/O spikes and extra full-page writes (first change to a page after a checkpoint logs the whole page). - Tune: raise
max_wal_sizeso checkpoints are time-triggered;checkpoint_completion_target = 0.9(default since PG 14) spreads I/O. - WAL also feeds physical streaming replication and logical decoding (
wal_level = logicalfor CDC). synchronous_commit = offtrades a small window of possible loss of recent commits (not corruption) for lower commit latency; can be set per transaction.
Memory and Planner
| Setting | Role | Starting point |
|---|---|---|
shared_buffers |
PostgreSQL buffer cache (default 128 MB) | ~25% of RAM on a dedicated server |
effective_cache_size |
Planner hint for OS + PG cache | 50-75% of RAM |
work_mem |
Per sort/hash node, per operation | Small globally; raise per session for reports |
| `maintenance_work_m |
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл architecture-postgresql-internals?
Use when the user asks about Postgres MVCC, the write-ahead log (WAL), table bloat, autovacuum, dead tuples, transaction ID wraparound, checkpoints, HOT updates, EXPLAIN ANALYZE or why Postgres is slow. Produces diagnosis queries and tuning settings. Not for schema design (use data-relational-database) or sharding (use architecture-database-scaling).
Как установить скилл architecture-postgresql-internals?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл architecture-postgresql-internals запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…