Skip to content

Concurrency control: MVCC, snapshots and VACUUM

View as Markdown

When many users read and change the same data at the same time, the database must keep each transaction's view of the data consistent and prevent changes from being applied in the wrong order. How strictly transactions are separated from each other is the isolation level: a higher level means less interference, a lower level more concurrency.

The SQL standard defines isolation in terms of three read anomalies:

Anomaly What happens
Dirty read Transaction T2 reads a change that T1 has not committed yet.
Non-repeatable read T1 reads a row twice and gets different values, because T2 updated or deleted it and committed in between.
Phantom read T1 runs the same query twice and gets additional rows, because T2 inserted them and committed in between.

CoraDB supports three isolation levels. The number in parentheses can be used instead of the name:

CoraDB isolation level Dirty read Non-repeatable read Phantom read Schema change of a table being read
READ COMMITTED (4), default no Possible Possible no
REPEATABLE READ (5) no no no no
SERIALIZABLE (6) no no no no

Thanks to snapshot isolation, REPEATABLE READ also prevents phantom reads, but it allows write skew, so it is not fully serializable; SERIALIZABLE currently behaves like REPEATABLE READ. Set the level with SET TRANSACTION ISOLATION LEVEL or the system parameter isolation_level.

CoraDB uses multiversion concurrency control (MVCC). Instead of overwriting a row in place, an update creates a new version of the row and keeps the old one for as long as some transaction may still need it. As a result:

  • Readers never wait for writers, and writers never wait for readers. A query reads the version that is valid for it, without locking rows.
  • Writers still take an exclusive lock on each row they change, so two transactions cannot modify the same row at the same time. See Locking.
  • Each transaction (or, under READ COMMITTED, each statement) works on a consistent snapshot of the database. This is snapshot isolation.

Old versions that no transaction can see any more are removed later by VACUUM.

Row versions. Every transaction that writes gets a unique, increasing identifier, its MVCCID. Each row version records the MVCCID of the transaction that inserted it and, once deleted, of the transaction that deleted it:

  • Insert. T1 inserts a row; the version carries insert MVCCID = T1. Until T1 commits, other transactions see that the inserter is still active and ignore the row.
  • Delete. T2 deletes the row: it locks it exclusively and adds delete MVCCID = T2, but leaves the version in place so that others can still read it.
  • Update. T2 updates the row: the heap now holds the new version (insert MVCCID = T2) with a link to the previous version, which is kept in the log. Older versions form a chain through the log.

Visibility. Whether a transaction can see a version depends only on the state of its inserter and deleter when the snapshot was taken. Changes committed after that moment, and versions created after it, are ignored. All visible versions together form the transaction's snapshot, which therefore does not change while it is in use.

A snapshot is defined by the lowest MVCCID still active and the highest committed MVCCID, plus the list of MVCCIDs that were active in between. Anything below the lower bound is committed and visible; anything above the upper bound started later and is invisible.

To read a row, CoraDB checks the newest version first and walks back through older versions in the log until it finds one that is visible:

Insert MVCCID Delete MVCCID Result
Not visible to the snapshot — Version too new. Check the previous version, or ignore the row if there is none.
Visible (committed before the snapshot) None, or not visible This version is read.
Visible Visible The row was deleted before the snapshot; it is ignored.

The examples use two or three sessions in REPEATABLE READ, which keeps one snapshot for the whole transaction (under READ COMMITTED each statement takes a new snapshot). In every session run first:

-- corasql: ;autocommit off
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

Steps are executed in order, top to bottom. Product 1618 (Gobi HeatTec Tee) costs 29.00.

Example 1: inserting a row

Step Session 1 Session 2 Result
1 INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (9001, 'Trail Socks', 'Merino socks', 9.90, 120);
2 SELECT name FROM product WHERE id = 9001; Trail Socks: a transaction sees its own changes.
3 SELECT name FROM product WHERE id = 9001; No rows: the insert is not committed.
4 COMMIT;
5 SELECT name FROM product WHERE id = 9001; Still no rows: Session 2's snapshot is older than the commit.
6 COMMIT; then SELECT name FROM product WHERE id = 9001; Trail Socks: the new transaction has a new snapshot.

Example 2: Deleting a row (continues Example 1)

Step Session 1 Session 2 Result
1 DELETE FROM product WHERE id = 9001;
2 SELECT name FROM product WHERE id = 9001; No rows.
3 SELECT name FROM product WHERE id = 9001; Trail Socks: the delete is not committed.
4 COMMIT;
5 SELECT name FROM product WHERE id = 9001; Still Trail Socks: the old snapshot still sees the row.
6 COMMIT; then SELECT name FROM product WHERE id = 9001; No rows.

Example 3: updating a row

Step Session 1 Session 2 Result
1 UPDATE product SET unit_price = 34.00 WHERE id = 1618;
2 SELECT unit_price FROM product WHERE id = 1618; 34.00: the new version.
3 SELECT unit_price FROM product WHERE id = 1618; 29.00: the last committed version.
4 COMMIT;
5 SELECT unit_price FROM product WHERE id = 1618; Still 29.00.
6 COMMIT; then SELECT unit_price FROM product WHERE id = 1618; 34.00.

Example 4: different transactions see different versions

Three sessions; product 1618 costs 29.00 again at the start.

Step Session 1 Session 2 Session 3 Result
1 SELECT unit_price FROM product WHERE id = 1618; 29.00; Session 2's snapshot is taken.
2 UPDATE product SET unit_price = 34.00 WHERE id = 1618; then COMMIT;
3 SELECT unit_price FROM product WHERE id = 1618; 34.00; Session 3's snapshot is taken after the commit.
4 UPDATE product SET unit_price = 39.00 WHERE id = 1618; Session 1 sees 39.00 (uncommitted).
5 SELECT unit_price FROM product WHERE id = 1618; 29.00
6 SELECT unit_price FROM product WHERE id = 1618; 34.00

Three versions of the same row are visible at the same time, one to each transaction. To restore the sample data afterwards, roll back Session 1 and set the price back: UPDATE product SET unit_price = 29.00 WHERE id = 1618; COMMIT;.

Because updates and deletes keep old versions, the database would grow without limit if nothing removed them. Each version goes through these stages:

  1. Inserted, not committed: visible only to its inserter.
  2. Committed: invisible to transactions that started before, visible to later ones.
  3. Deleted, not committed: still visible to other transactions, invisible to the deleter.
  4. Delete committed: still visible to transactions that started before, invisible to later ones.
  5. Invisible to all active transactions.
  6. Removed from the database.

VACUUM moves versions from stage 5 to stage 6 and makes their space reusable. It runs automatically in the background of the database server. It is designed to be:

  • Correct and complete: it never removes a version that some transaction can still see, and it misses no obsolete version.
  • Discreet: it interferes as little as possible with running transactions. It does not use locks.
  • Fast: it must keep up with the workload, otherwise the database grows and performance degrades.

VACUUM does not scan the database. It reads the recovery log, which already records the address of every heap and index change together with its MVCCID. Each transaction knows the oldest MVCCID it still considers active; the smallest of these over all transactions is the vacuum horizon. Everything logged by MVCCIDs below the horizon is invisible to everyone and can be cleaned.

  • Parallel execution. The log is divided into fixed-size blocks. When all operations in a block are below the horizon, the vacuum master creates a job for it, and vacuum workers execute the jobs in parallel.
  • Vacuum data. Information about pending log blocks is kept in the persistent vacuum data file, so no work is lost if the server stops. After a crash a job may run twice, which is harmless; a job is never skipped.
  • Jobs. A worker prefetches the log pages of its block, cleans index entries immediately, collects the heap rows (OIDs) to clean, then cleans them and marks the job complete.
  • Dropped tables and indexes. Because VACUUM uses no locks, a dropped file is destroyed only after the dropping transaction commits and VACUUM has been notified. Log entries that belong to a dropped file are skipped from then on.

Long-running transactions hold back the vacuum horizon: versions they might still see cannot be removed. Commit or roll back transactions promptly, especially in applications that keep connections open.

You normally do not need to run VACUUM yourself. A manual vacuum is only available in stand-alone mode, that is with the database server stopped:

coradb server stop mydb
coradb vacuumdb -S mydb

In stand-alone corasql (corasql -S), the statement VACUUM; does the same (see vacuumdb). In client-server mode both are rejected:

VACUUM;
ERROR: Manual vacuum is disabled for client-server mode.

The background vacuum is tuned with the system parameters described in Other parameters. The size of the log buffer also matters, because MVCC and VACUUM read old versions from the log; see log_buffer_size.