Sobes.tech
Junior

Tell me about the MVCC concept in PostgreSQL: how it works, bloat, vacuum, and its relation to transaction isolation levels.

sobes.tech AI

Answer from AI

MVCC (Multi-Version Concurrency Control) in PostgreSQL is a concurrency control mechanism that allows transactions to see a consistent view of data without read locks.

How it works:

  • Each row in a table stores version information: xmin (ID of the transaction that created the row) and xmax (ID of the transaction that deleted the row).
  • A transaction only sees rows that were created before it started and not deleted by the time it began.
  • Thus, reading does not block writing and vice versa.

Bloat:

  • Due to MVCC, deleted or updated rows are not immediately removed but remain as "dead" versions.
  • This leads to an increase in table size (bloat), which reduces performance.

Vacuum:

  • The VACUUM command cleans up these "dead" rows, freeing space.
  • There is a regular VACUUM (releases space for reuse) and VACUUM FULL (physically compresses the table).

Relation to isolation levels:

  • MVCC provides the isolation levels READ COMMITTED and REPEATABLE READ.
  • READ COMMITTED sees data confirmed at the time of each query.
  • REPEATABLE READ sees data confirmed at the start of the transaction, ensuring read stability.

Example: a transaction reads data while another transaction updates rows — thanks to MVCC, the first sees the old version, the second — the new one, without locks.