What is MVCC in PostgreSQL: Explanation and Example
MVCC (Multi-Version Concurrency Control) is a technique that allows multiple transactions to access the database concurrently without locking conflicts. It works by keeping multiple versions of data rows, so readers see a consistent snapshot while writers can update data without blocking readers.How It Works
Imagine a busy library where many people want to read and update books at the same time. Instead of making everyone wait for one person to finish, the library keeps multiple copies of each book. Readers get their own copy to read without interruption, while writers can update another copy. PostgreSQL uses a similar idea with MVCC.
When you read data, PostgreSQL shows you a snapshot of the database as it was at the start of your transaction. If someone else updates the data while you read, you still see the old version, so your reading is never blocked. When you update data, PostgreSQL creates a new version of the row instead of overwriting it immediately. Old versions are cleaned up later.
This system helps avoid delays and conflicts, making the database fast and reliable even with many users working at once.
Example
This example shows how two transactions can work with the same data without blocking each other using MVCC.
BEGIN; SELECT * FROM accounts WHERE id = 1; -- Transaction 1 reads -- In another session: BEGIN; UPDATE accounts SET balance = balance + 100 WHERE id = 1; -- Transaction 2 updates COMMIT; -- Back to Transaction 1: SELECT * FROM accounts WHERE id = 1; -- Still sees old balance COMMIT;
When to Use
Use MVCC in PostgreSQL whenever you want to allow many users to read and write data at the same time without waiting for locks. It is especially useful in web applications, financial systems, and any environment with high concurrency.
MVCC helps keep your application responsive by avoiding delays caused by locking. It also ensures that readers always see consistent data, even if others are updating the database.
Key Points
- MVCC keeps multiple versions of data rows to allow concurrent access.
- Readers see a consistent snapshot without waiting for writers.
- Writers create new row versions instead of overwriting immediately.
- Old versions are cleaned up later by a process called vacuuming.
- This improves performance and reduces locking conflicts in PostgreSQL.