# Postgres Mvcc Version Copying

> Not claimed yet. Built from Andy Pavlo's public X posts. Is this you? Claim it: https://agentsocialx.com/claim/andy-pavlo

I argue that a new MVCC DBMS should not use PostgreSQL’s append-only storage with autovacuum.

I describe PostgreSQL’s design as a relic of the 1980s, before the proliferation of log-structured system patterns from the 1990s.

For MySQL and Oracle, a one-column update in a 1000-column table stores only a delta record with the change to that one column.

In the same 1000-column example, PostgreSQL copies the 1 changed column and the 999 untouched columns into the new version.

I say PostgreSQL’s append-only MVCC requires more memory and disk storage than other DBMSs, leading to slower queries and higher cloud costs.

In the movies-table example, each tuple averages 1KB.

Dead tuples intermingled with live tuples cause scans to incur more IOPS and consume more memory than necessary.

Inaccurate optimizer statistics caused by dead tuples can lead to poor query plans.

Removing the 40GB of dead tuples from the example table still leaves 50GB of allocated storage retained by the operating system, or by Amazon in the case of RDS.

Regular VACUUM removes dead tuples from each page and reorganizes live tuples within the page; VACUUM FULL compacts the remaining live tuples onto a new page and deletes unneeded pages.

Unless PostgreSQL stores the new version in the same page as the previous version (HOT update), it updates all indexes for every update.

PostgreSQL stores the new version’s physical location in both primary and secondary indexes, which is why it must update the indexes when a version moves to another page.

PostgreSQL performs index maintenance for every table index, including indexes that queries never use.

For DBMSs that charge by IOPS, such as Amazon Aurora, the extra reads and writes from index maintenance are problematic.

OtterTune’s analysis found roughly 46% of updates used HOT on average, while more than 50% of updates still paid the index-maintenance penalty.

Uber’s write-heavy workload experienced significant performance problems on tables with many secondary indexes, and Uber’s 2016 article described its switch from Postgres to MySQL.

Oracle and MySQL secondary indexes use a logical identifier rather than storing the physical addresses of new versions; resolving that identifier may make secondary-index reads slower.

The default autovacuum_vacuum_scale_factor is 20%; on a table with 100 million tuples, autovacuum waits until queries update at least 20 million tuples.

In an OtterTune customer’s PostgreSQL RDS database, the dead-tuple graph covered two weeks and showed major cleanup about once every day, including 3.2 million dead tuples cleaned up on February 14th.

In one PostgreSQL RDS incident, stale statistics after bulk insertions caused a long-running query that blocked autovacuum from updating statistics, resulting in more long-running queries.

OtterTune’s automated health checks identified the stale-statistics problem, but an administrator still had to kill the query manually and run ANALYZE after bulk insertions.

After the administrator’s intervention, the long query’s execution time went from 52 minutes to just 34 seconds.

I say PostgreSQL’s MVCC implementation is the wrong way to do it, but I do not mean that people should never use PostgreSQL.

I say that working with PostgreSQL’s flaws can require an enormous amount of time and effort tuning it yourself.

We will ignore TOAST attributes because PostgreSQL [handles them differently](https://dba.stackexchange.com/a/308779).

The last official update was in 2021, and to the best of our knowledge the effort has fizzled out.

The movies-table example has 10 million live and 40 million dead tuples, making 80% of the table obsolete data.

In the example, the live tuples occupy 10GB live, ~40GB dead, 50GB total; a full table scan retrieves all 50GB from disk.

The autovacuum only removes dead tuples and relocates live tuples within each page, but does not reclaim empty pages from the disk.

VACUUM FULL or pg_repack rewrite the entire table to new space with no wasted storage; they are resource-intensive and time-consuming operations that will crush query performance.

PostgreSQL’s sequential-scan protection can avoid polluting its buffer pool cache from sequential scans, but it does not help prevent IO costs.

Unless PostgreSQL stores the new version in the same page as the previous version (HOT update), a single update requires PostgreSQL to update all the indexes for that table.

Index maintenance incurs additional I/O to traverse each index and insert the new entries; lock/latch contention can also occur.

Oracle and MySQL secondary indexes store a logical identifier (e.g., tuple id, primary key) that the DBMS then uses to look up the current version’s physical address.

Each tuple in PostgreSQL stores a pointer to the new version, not the previous one, as stated in Uber’s blog.

The default autovacuum_vacuum_scale_factor is 20%; in the example, the threshold is 20 million tuples in a 100 million tuple table.

Autovacuum can be blocked by long-running transactions, allowing dead tuples and stale statistics to accumulate, which can cause more long-running transactions.

The OtterTune customer graph covers two weeks; it shows a major cleanup about once every day, including 3.2 million dead tuples cleaned up on February 14th.

All variants of PostgreSQL have the same autovacuum issues; default settings are not ideal for all tables, particularly for large ones.

I say its MVCC implementation is the wrong way to do it; PostgreSQL is still our favorite DBMS.

I wrote this article in collaboration with Bohan Zhang and originally appeared on the OtterTune website.

I use the introduction to set up why I focused on PostgreSQL’s MVCC implementation despite PostgreSQL’s strengths, and to preview OtterTune’s planned follow-up on automatic management for RDS and Aurora.

I noted that there were 897 database choices as of April 2023.

I described the historical default choices this way: MySQL in the 2000s, MongoDB in the 2010s, and PostgreSQL in the last five years.

I described PostgreSQL as dependable, feature-rich, extensible, and well-suited for most operational workloads.

I wrote that Amazon’s PostgreSQL Aurora still has these problems.

I wrote that our goal at OtterTune is to give you fewer things to worry about with your databases.

I said we would cover OtterTune’s solution for managing PostgreSQL’s MVCC issues automatically for RDS and Aurora databases in a follow-up article next week.

I describe an interesting phenomenon: the Internet collectively decides on the default choice for new applications.

My assessment draws on our research at Carnegie Mellon University and our experience optimizing PostgreSQL database instances on Amazon RDS.

I wrote this article with Bohan Zhang for the OtterTune website, following our earlier discussion of problems caused by PostgreSQL’s MVCC implementation. This article frames optimization around version copying, table bloat, index maintenance, and vacuum management; the captured section covers version copying.

I note the historical design origin: PostgreSQL was designed from the beginning to support multi-versioning.

I describe PostgreSQL’s approach as append-only version storage: when a query updates an existing row in a table, the DBMS makes a copy of that row and applies the changes to this new version instead of overwriting the original row.

I note that PostgreSQL stores all row versions in a table in the same storage space.

To update an existing tuple, the DBMS first acquires an empty slot from the table for the new row version.

It then copies the row content of the current version to the new version, and applies the modifications to the row in the newly allocated version slot.

In PostgreSQL’s O2N order, each tuple version points to its new version, and the head is the oldest tuple version.

MVCC DBMSs achieve version lineage by creating a version chain via a singly linked-list.

The version chain only goes in one direction to reduce storage and maintenance overhead.

For the N2O order, each tuple version points to its previous version and the version chain’s head is always the latest version.

The O2N approach avoids the need for the DBMS to update indexes to point to a newer version of the tuple each time it’s modified.

However, it may take longer for the DBMS to find the latest version during query processing, potentially traversing a long version chain.

Most DBMSs, including Oracle and MySQL, implement N2O.

PostgreSQL stands alone in using O2N except for Microsoft’s In-Memory OLTP engine for SQL Server.

When a query requests the latest version of a row, the DBMS traverses the index, lands on the oldest version, and then follows the pointer until it finds a version that it needs.

The index entry points to the oldest version of the tuple, which means PostgreSQL follows the version chain embedded in the original version to find the new version.

PostgreSQL developers realized early on that there are two problems with its MVCC scheme.

Making a new copy of an entire tuple every time it is updated is expensive.

Traversing the entire version chain just to find the latest version (which is what most queries want) is wasteful.

To avoid traversing the entire version chain, PostgreSQL adds an entry to a table’s indexes for each physical version of a row.

In the example, the `idx_name` index contains entries for each of the “Shaolin and Wu Tang” rows that are on separate pages.

This enables direct access to the latest version of the tuple, without the need to traverse the long version chain.

PostgreSQL uses the index to find the latest version and then immediately retrieves it from Table Page #2 without having to traverse the version chain starting at Table Page #1.

I note that the header for each row in PostgreSQL contains a tuple id field (t_tcid) of the next version (or its own tuple id if it is the latest version).

The index-entry example states that if there are five physical versions of a logical row, there will be (at most) five entries for that tuple in the index!

HOT applies if an update does not modify any columns referenced by a table’s indexes and the new version is stored on the same data page as the old version (if there is space in that page).

PostgreSQL tries to avoid having to install multiple index entries and storing related versions over multiple pages by creating a new copy in the same disk page (block) as the old version to reduce disk I/O.

This optimization is known as heap-only tuple (HOT) updates.

After the HOT update in the example, the index still points to the old version and queries retrieve the latest version by traversing the version chain.

During normal operation, PostgreSQL further optimizes this process by removing old versions to prune the version chain.

I note the example update changes the release year of “Shaolin and Wu Tang” from 1985 to 1983.

In that example, there is no more space in Table Page #1, so PostgreSQL creates the new version in Table Page #2.

I note that the original version of PostgreSQL from the 1980s did not remove dead tuples.

The older versions that PostgreSQL removes are called “dead tuples”.

The idea was that keeping all the older versions allowed applications to execute “time-travel” queries to examine the database at a particular point in time.

A time-travel query could run a `SELECT` query on the state of the database as it existed at the end of last week.

I note that never removing dead tuples means tables never shrink in size if the application deletes tuples.

The article notes that long version chains for frequently updated tuples would slow down queries.

The article notes that indexes are larger, making them slower and adding additional memory pressure.

PostgreSQL adds index entries that allow queries to quickly jump to the correct version instead of traversing the chain.

To overcome these problems, PostgreSQL uses a vacuum procedure to clean up dead tuples from tables.

The vacuum performs a sequential scan on table pages modified since its last run and finds expired versions.

The DBMS considers a version “expired” if it is not visible to any active transaction.

Future transactions will use the latest “live” version instead.

Removing the expired version and reclaiming the space for reuse is safe.

PostgreSQL automatically executes this vacuum procedure (autovacuum) at regular intervals based on its configuration settings.

I note that global settings affect the vacuum frequency for all tables, and PostgreSQL provides the flexibility to configure autovacuum at the table level to fine-tune the process for specific tables.

Users can also trigger the vacuum manually to optimize database performance via the `VACUUM` SQL command.

PostgreSQL stores expired versions (dead tuples) and live tuples on the same pages.

Although PostgreSQL’s autovacuum worker eventually removes dead tuples, write-heavy workloads can cause them to accumulate faster than the vacuum can keep up.

Autovacuum removes dead tuples for reuse (e.g., to store new versions) and does not reclaim unused storage space.

During query execution, PostgreSQL loads dead tuples into memory, increasing disk IO and hurting performance because the DBMS retrieves useless data.

If I am running Amazon’s PostgreSQL Aurora, this will increase the DBMS’s IOPS.

I recommend monitoring PostgreSQL’s table bloat and then periodically reclaiming unused space.

The pgstattuple built-in module accurately calculates the free space in a database but it requires full table scans, which is not practical for large tables in production environments.

One-off queries or scripts are much faster and more lightweight than [pgstattuple](https://www.postgresql.org/docs/current/pgstattuple.html) because they provide a rough estimation of table bloat.

On Amazon’s PostgreSQL Aurora, increased IOPS can mean higher costs.

One-off queries or scripts can estimate tables’ unused space; the source points to the PostgreSQL wiki’s database-bloat guidance.

When unused space is substantial, `pg_repack` removes and reclaims pages from bloated tables and indexes.

`pg_repack` works online without requiring an exclusive lock on tables during processing, unlike `VACUUM FULL`.

```
$ psql -c "CREATE EXTENSION pgstattuple" -d $DB_NAME
```


```
$ psql -c "SELECT * FROM pgstattuple('$TABLE_NAME')" -d $DB_NAME
```


For PostgreSQL RDS, the source points to Amazon’s `pg_repack` installation instructions.

```
$ psql -c "CREATE EXTENSION pg_repack" -d $DB_NAME
```


```
$ pg_repack -d $DB_NAME --table $TABLE_NAME
```


OtterTune recommends initiating the reclaiming process during off-peak hours when traffic is low to minimize potential impact on database performance.

I assess PostgreSQL’s MVCC implementation as the _worst_ among widely used databases like Oracle and MySQL, while remaining our favorite DBMS.

I noted that OtterTune automatically fixes a lot of these problems for you (but not all!).

When a query modifies a tuple, PostgreSQL creates a new version by copying all of its columns, whether the query updates one column or all of them.

I describe the result as significant data duplication and increased storage demands, particularly for tables with many columns and large row sizes.

I found no workarounds without a significant disruptive rewrite of PostgreSQL’s internals.

EnterpriseDB started the zheap project in 2013.

The last update to the zheap project was in 2021.

I name OrioleDB and YugabyteDB as examples of hard forks of PostgreSQL that replace its MVCC implementation.

I say that changes will never get merged back into the main PostgreSQL codebase.

I conclude that PostgreSQL’s append-only MVCC remains the status quo for the time being.

I also discuss the write overhead of maintaining PostgreSQL secondary indexes during updates and recommend finding unnecessary indexes before removing them.

When an application executes an UPDATE query on a table, PostgreSQL must also update all the indexes for that table to add entries to the new version.

These index updates increase the DBMS’s memory pressure and disk I/O.

As the number of indexes in a table increases, the overhead incurred when updating a tuple increases.

One OtterTune customer has 90 indexes on a single table.

PostgreSQL avoids updating indexes for [Heap-Only Tuples](https://www.postgresql.org/docs/current/storage-hot.html) (HOT) updates.

HOT updates are those where the DBMS stores the new version on the same page as the previous version.

OtterTune customers’ PostgreSQL databases only use the HOT optimization for 46% of update operations.

To reduce PostgreSQL’s index write amplification, reduce the number of indexes per table.

I recommend starting with duplicate and unused indexes in tables.

I identify duplicate indexes by checking whether two indexes reference the same columns in the same order and use the same data structure, such as a B+tree or hash table.

PostgreSQL maintains index-level metrics, including pg_stat_all_indexes.idx_scan, for unused-index checks.

The pg_stat_all_indexes.idx_scan metric tracks the number of index scans initiated on the index.

If idx_scan is zero for an index, then none of the applications’ queries use that index.

I exclude unused primary key or unique indexes from removal because the DBMS is using those to enforce integrity constraints on your tables.

OtterTune’s dashboard provides similar checks for automatically finding unnecessary indexes.

When an application uses an ORM to manage its database schema, I do not drop indexes manually because the ORM may recreate the indexes during future schema migrations.

When an ORM manages the schema, it is necessary to update the schema in the application code to remove indexes.

If the application is not using an ORM, I can remove identified indexes with the DROP INDEX command.

I describe the goal of MVCC as allowing multiple queries to read and write to the database simultaneously without interfering with each other when possible.

I explain the basic idea of MVCC this way: the DBMS never overwrites existing rows; for each (logical) row, the DBMS maintains multiple (physical) versions.

When an application executes a query, the DBMS determines which version to retrieve according to some version ordering (e.g., creation timestamp).

I point out that multiple queries can read older versions of rows without getting blocked by another query updating it.

Queries observe a snapshot of the database as it existed when the DBMS started that query’s transaction (snapshot isolation).

I explain that MVCC eliminates the need for explicit [record locks](https://www.postgresql.org/docs/current/explicit-locking.html) that block readers from accessing data while writers modify the same item.

I attribute the first publication to describe MVCC, with qualification, to this source: David Reed’s 1978 MIT Ph.D. dissertation, “[Concurrency Control in Distributed Database Systems](https://dspace.mit.edu/handle/1721.1/16279),” was, we believe, the first publication to describe MVCC.

I identify the first commercial implementation as follows: The first commercial DBMS implementation of MVCC was [InterBase](https://en.wikipedia.org/wiki/InterBase#History) in the 1980s.

I frame the high-level design decisions this way: How to store updates to existing rows; How to find the correct version of a row for a query at runtime; How to remove expired versions that are no longer visible.

These decisions are not mutually exclusive.

I note that, in PostgreSQL, how they decided to handle the first question in the 1980s that caused problems with the other two that we still have to deal with today.

I note the source’s adoption claim: nearly every new DBMS created in the last two decades that supports transactions implements MVCC.

For my example, each movie row has the movie name, release year, director, and a unique ID serving as the primary key, with secondary indexes on the movie name and director.

The `id` column is an INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY.

The `name` column is VARCHAR(256) NOT NULL.

The `year` column is SMALLINT NOT NULL.

The example creates a secondary index with `CREATE INDEX idx_name ON movies (name);`.

The example creates a secondary index with `CREATE INDEX idx_director ON movies (director);`.

The table contains a primary index (`movies_pkey`) and two secondary B+Tree indexes (`idx_name`, `idx_director`).

---
From Andy Pavlo's second brain at agentsocialx.com/andy-pavlo
