All posts

Eliminating PostgreSQL's MVCC Count Penalty

a group of colorful objects sitting on top of a white surface
Photo by Nayam (https://unsplash.com/@nayamamarshe) on Unsplash (https://unsplash.com/photos/a-group-of-colorful-objects-sitting-on-top-of-a-white-surface-AZgddRGgQlY)

In PostgreSQL, executing an unqualified COUNT(*) on a large table remains one of the fastest ways to exhaust disk I/O and degrade database throughput. While developers coming from systems with fixed-size tables often expect row counts to be an $O(1)$ metadata lookup, PostgreSQL routinely falls back to sequential scans or index scans that degrade linearly with table size.

The bottleneck is not an oversight in the optimizer. It is a direct consequence of Multi-Version Concurrency Control (MVCC). Understanding why this scan penalty exists, and how modern index extensions avoid it without breaking transactional guarantees, is critical for backend engineers scaling analytical queries within PostgreSQL.

The MVCC Visibility Trap

Under PostgreSQL’s MVCC model, multiple physical versions of a row (tuples) can exist concurrently inside the table’s heap pages. Each tuple carries transaction metadata headers, specifically xmin (the transaction that inserted the row) and xmax (the transaction that deleted or updated it).

When a query runs, PostgreSQL takes a snapshot of the database state. A tuple is only visible to that query if its xmin committed before the snapshot began and its xmax is either unset, aborted, or committed after the snapshot.

Because row visibility is relative to the calling transaction’s snapshot, the database cannot simply store a global row counter in table metadata. At any given moment:

A global counter would inevitably expose dirty reads or phantom rows. Consequently, PostgreSQL must evaluate the visibility of every candidate tuple against the active snapshot.

The optimizer can use an Index-Only Scan to satisfy a count, but this still requires checking visibility. PostgreSQL uses a Visibility Map (VM) file that tracks which heap pages contain only tuples committed and visible to all current and future transactions. If a page’s bit in the visibility map is not set, the index scan must still read the heap page to verify tuple headers. On write-heavy workloads where pages are frequently dirtied, visibility maps quickly lose coverage, forcing count queries to perform random reads against the heap.

Reconciling External Index Formats with MVCC

To circumvent heap scanning entirely, alternative indexing engines, such as inverted index structures derived from Tantivy and Lucene, decouple data retrieval from the standard PostgreSQL heap layout. As detailed by ParadeDB’s technical deep dive, standalone analytical and search engines maintain their own segment files, metadata dictionaries, and pre-calculated document counts. In a standalone environment, counting matching records requires reading segment metadata or counting bits in an index bitset.

Integrating these high-performance index structures directly into PostgreSQL introduces the core challenge: the external engine does not natively understand PostgreSQL transaction snapshots.

As highlighted in community discussions on search engine integration in PostgreSQL, embedding specialized engines requires bridging the gap between immutable index segments and PostgreSQL’s row-level visibility rules. If an external index simply returns its internal document count, it violates PostgreSQL’s ACID guarantees by counting rows that may be uncommitted or deleted in the caller’s snapshot.

Bypassing the Scan Penalty

Modern database extensions bridge this gap by binding segment-level tracking directly to PostgreSQL’s transaction manager:

  1. Deterministic Document-to-Item Mapping: External engine indexes map PostgreSQL tuple identifiers (ItemPointer / ctid) to internal document identifiers. When records are committed, updated, or marked dead, the extension tracks these state changes using internal bitsets (unverified: precise segment file format changes documented in part 2).
  2. Snapshot-Aware Bitmasking: Instead of traversing table pages or checking row headers tuple by tuple, the extension evaluates transaction visibility at the segment or batch level. Visibility conditions are translated into a filter mask applied to the index’s internal posting lists or bitsets.
  3. Metadata-Driven Aggregation: When an index segment is fully committed and older than the oldest active transaction, all of its non-deleted records are guaranteed visible to every incoming snapshot. In these scenarios, the engine skips tuple verification entirely and returns precomputed document counts directly from the index metadata.

By moving visibility validation from individual heap tuples into index bitset operations, these extensions eliminate the need to touch the underlying table pages during analytical counts. Backend systems achieve the aggregate performance characteristic of dedicated search and analytical engines while retaining PostgreSQL as the primary transactional store.