PostgreSQL VACUUM and MVCC Explained
Every UPDATE writes a new tuple. VACUUM removes dead ones, HOT updates avoid index churn, and freezing prevents transaction ID wraparound.
In this chapter
PostgreSQL MVCC: tuple versions, VACUUM, HOT and wraparound
More on PostgreSQL
Keep learning
Overview
autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor Vacuum after 50 + 20% of the table is dead. Fine for small tables, far too late for a 500 GB one: lower the factor per table. How often the launcher looks for work. Rarely worth changing. Tables vacuumed at once. More workers share the same cost budget. autovacuum_vacuum_cost_limit / cost_delay Throttle that protects I/O. Too low and vacuum never catches up on a busy table. fillfactor (table) Free room per page for HOT updates, paid for with a larger table. 200 million Age that forces an anti-wraparound vacuum, even with autovacuum off. 1.6 billion Age at which vacuum drops throttling and index cleanup to finish freezing fast. 0 (off) Kills sessions that sit inside an open transaction and pin the horizon. n_live_tup, n_dead_tup, n_tup_hot_upd, last_autovacuum: is vacuum keeping up? What a running vacuum is doing right now, phase by phase. old data updated 1 s ago new insert Index-only scan over six heap pages. Pages 0, 1, 3 and 5 are marked all-visible in the visibility map, so the scan answers from the index alone. Pages 2 and 4 changed recently, are not all-visible, and need a heap fetch. index entries (key → heap page) · index-only scan walks these VM: all-visible ✓ + frozen ✓ yes no heap visit heap fetch EXPLAIN ANALYZE shows the misses as “Heap Fetches: N”. The visibility map answers one question per page: can the index entry be trusted without reading the tuple’s xmin and xmax? chapters · postgresql PostgreSQL MVCC: tuple versions, VACUUM, HOT and wraparound PostgreSQL keeps old row versions in the table itself. That makes reads simple and rollback free, and it makes cleanup a job someone has to do.
1. An UPDATE writes a new tuple
Every tuple header carries xmin (creator), xmax (deleter or updater) and ctid (where the next version is). An UPDATE is a DELETE plus an INSERT inside one transaction, so the old version stays in the heap until VACUUM.
2. Dead tuples, VACUUM and autovacuum
Autovacuum vacuums a table once n_dead_tup > 50 + 0.2 × reltuples. On a 100-million-row table that is 20 million dead tuples before anything happens, so big tables get a per-table setting.
Marks space reusable
Runs beside reads and writes (SHARE UPDATE EXCLUSIVE). Removes dead tuples and their index entries, updates the visibility map. The file keeps its size, except empty pages at the very end.
Rewrites the table
Copies live tuples into a new file and rebuilds indexes. Gives space back to the OS, but holds ACCESS EXCLUSIVE: nothing can even read the table meanwhile. Needs room for the copy. For online compaction people use the pg_repack extension. The same cleanup problem in general terms is covered in update internals and delete internals.
3. HOT updates and fillfactor
A heap-only tuple (HOT) update puts the new version in the same page and links it from the old one. Indexes keep pointing at the old line pointer, so no index is touched, and later page pruning cleans the chain without VACUUM.
4. The visibility map and index-only scans
Indexes in PostgreSQL hold no visibility information. An index-only scan therefore asks the visibility map first, and only pages marked all-visible can skip the heap. That is why a freshly loaded or busy table shows many heap fetches until VACUUM runs. The same map lets VACUUM skip all-visible pages, and all-frozen pages are skipped even by anti-wraparound vacuums.
5. Freezing and transaction-id wraparound
Transaction ids are 32 bits and compared on a circle: about 2 billion ids are “the past”, the other 2 billion “the future”. A tuple older than that would suddenly look like it comes from the future and vanish. VACUUM prevents this by freezing old tuples: a header bit that says “visible to everyone, ignore xmin”. It can only freeze tuples older than the xmin horizon, and three things hold the horizon back: a long or idle-in-transaction session, a replication slot (or a standby with hot_standby_feedback), and a forgotten prepared transaction.
Reference: settings and views
Defaults are PostgreSQL 16/17 Setting or view What it trades Compare: MySQL. InnoDB updates the row in place and keeps the old version in the undo log, cleaned by purge instead of VACUUM: see MySQL MVCC and purge.
Recap
Dead tuples stay until VACUUM. Autovacuum fires at 50 + 20% dead by default, too late for big tables: tune per table. Index-only scans only skip the heap on pages the visibility map marks all-visible. Freezing keeps 32-bit xids from wrapping. Long transactions, abandoned slots and prepared transactions block it: find and end them.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.