Postgres MVCC
Postgres MVCC
allow concurrent access to the database without locking, ensuring data consistency
while minimizing conflicts. Here's a simplified breakdown of how MVCC works in
PostgreSQL:
1. Snapshot Isolation
PostgreSQL uses MVCC to provide snapshot isolation. Each transaction works with its
own snapshot of the database, which means that it only sees the data as it was at
the start of the transaction, even if other transactions are modifying the same
data simultaneously.
3. Visibility Rules
A transaction can see a row if:
The row's xmin is less than or equal to the current transaction's ID (meaning the
row was committed before the transaction started).
The row's xmax is either not set (row is still active) or set to a value greater
than the current transaction's ID (meaning the row has not been deleted by any
transaction that is active or committed before the current transaction).
This allows different transactions to work with different versions of the same row,
depending on their snapshot.
Example:
Transaction A inserts a row with the value 1 into a table.
Transaction B begins and reads the value from that row. It sees the inserted value
1 since it was committed before Transaction B started.
Transaction A updates the row to 2. A new tuple is created with the value 2, and
its xmin is set to Transaction A's ID.
Transaction B reads the row again. It will still see the old version (with value 1)
because it started before Transaction A's update was committed.
If Transaction A commits, the old version of the row still exists but will be
marked as obsolete once all transactions that started before it have finished.
This process helps PostgreSQL provide concurrent access while maintaining
consistency and isolation, making sure that transactions don't interfere with each
other.