MVCC, Isolation and Server-Side Logic

Article · 3:00

Why readers never block writers, what each isolation level does and does not promise, deadlocks and how to avoid them, and PL/pgSQL with exception handling.

MVCC - multi-version concurrency control - is the mechanism behind PostgreSQL's most quoted property: readers do not block writers and writers do not block readers. An UPDATE does not overwrite a row. It writes a new version and marks the old one dead for transactions that began later. Each transaction sees the versions that were committed when its snapshot was taken.

Two consequences follow, and both matter operationally. Dead row versions accumulate, so a heavily updated table grows beyond the size of its live data - that is bloat, and VACUUM is what reclaims it. And count(*) must examine visibility, so it is not free in PostgreSQL the way it is in engines that keep a counter.

Isolation levels are promises about which anomalies cannot happen.

READ COMMITTED, the default, takes a fresh snapshot for each statement. Two identical queries in one transaction can therefore return different rows - a non-repeatable read. This is fine for most work and surprising when you first meet it.

REPEATABLE READ takes one snapshot for the whole transaction. PostgreSQL's implementation also prevents phantom reads, which the SQL standard does not require. Concurrent updates to the same row produce a serialisation failure, and your application must be prepared to retry.

SERIALIZABLE adds predicate locking and guarantees the result is equivalent to some serial order. It is the only level that prevents write skew - two transactions each reading a condition and each writing based on it, so that both are individually valid and the pair is not. It costs more and raises serialisation failures more often, and for a ledger it is frequently worth it.

Locks and deadlocks. SELECT ... FOR UPDATE takes a row lock, which is how you serialise access to a specific row. A deadlock is two transactions each holding what the other wants; PostgreSQL detects it after deadlock_timeout and kills one with SQLSTATE 40P01. The cure is almost always consistent lock ordering - if every transfer locks the lower account id first, two opposite transfers can no longer deadlock.

PL/pgSQL puts logic next to the data. It is right when the alternative is several round trips to make one decision, and wrong when it becomes business logic that nobody outside the database can test or deploy. Its exception block maps SQLSTATE to handlers, and RAISE produces errors your application can distinguish.

Laboratory exercise 3 - a service under concurrency.

Build a small service, in any language with a PostgreSQL driver, exposing "transfer money between two accounts". Run it against concurrent clients: at least 50 simultaneous transfers, including pairs that move money in opposite directions between the same two accounts.

Then make it correct. Demonstrate the ledger going wrong at READ COMMITTED with a naive read-then-write, fix it with either SELECT ... FOR UPDATE and consistent lock ordering or SERIALIZABLE with a retry loop, and show the invariant holding afterwards. Induce a deadlock deliberately and capture the server's log line.

Deliverable: the service, the load script, the before-and-after reconciliation output, your captured deadlock, and a short account of which fix you chose and what it costs. Both fixes are defensible; an undefended choice is not.

-- ------------------------------------------------------------------
-- Seeing MVCC. Two sessions, side by side.
-- ------------------------------------------------------------------
-- Session A                        | Session B
BEGIN;                           -- |
SELECT balance_minor             -- |
  FROM ledger.account WHERE id=1;-- | BEGIN;
-- 100000                           | UPDATE ledger.account
                                 -- |   SET balance_minor = 0 WHERE id=1;
SELECT balance_minor             -- | COMMIT;
  FROM ledger.account WHERE id=1;-- |
-- READ COMMITTED: 0   <- changed under us, mid-transaction
-- REPEATABLE READ: 100000 <- the snapshot held
COMMIT;

-- ------------------------------------------------------------------
-- The bug this causes: read-then-write without a lock.
-- ------------------------------------------------------------------
-- BEGIN;
--   SELECT balance_minor FROM ledger.account WHERE id = 1;  -- 100000
--   -- another transaction debits 50000 here and commits
--   UPDATE ledger.account SET balance_minor = 100000 - 30000 WHERE id = 1;
-- COMMIT;   -- the other debit is gone. A lost update.

-- Fix 1: lock the row, and lock in a consistent ORDER.
CREATE OR REPLACE FUNCTION ledger.transfer(
    from_id bigint, to_id bigint, amount bigint, ref text
) RETURNS bigint
LANGUAGE plpgsql AS $$
DECLARE
    first_id  bigint := least(from_id, to_id);
    second_id bigint := greatest(from_id, to_id);
    --         ^^^^^ ALWAYS the lower id first. Two opposite transfers
    --         between the same pair can then no longer deadlock, because
    --         they queue for the same lock in the same order.
    from_balance bigint;
    transfer_id  bigint;
BEGIN
    IF amount <= 0 THEN
        RAISE EXCEPTION 'amount must be positive' USING ERRCODE = '22023';
    END IF;

    PERFORM 1 FROM ledger.account WHERE id = first_id  FOR UPDATE;
    PERFORM 1 FROM ledger.account WHERE id = second_id FOR UPDATE;

    SELECT balance_minor INTO from_balance
      FROM ledger.account WHERE id = from_id;

    IF from_balance < amount THEN
        RAISE EXCEPTION 'insufficient funds in account %', from_id
            USING ERRCODE = '23514';
    END IF;

    INSERT INTO ledger.transfer (reference) VALUES (ref)
      RETURNING id INTO transfer_id;

    INSERT INTO ledger.entry (transfer_id, account_id, amount_minor)
      VALUES (transfer_id, from_id, -amount), (transfer_id, to_id, amount);

    UPDATE ledger.account SET balance_minor = balance_minor - amount
      WHERE id = from_id;
    UPDATE ledger.account SET balance_minor = balance_minor + amount
      WHERE id = to_id;

    RETURN transfer_id;

EXCEPTION
    WHEN unique_violation THEN
        -- The reference already exists: this is a retry of a request we
        -- already completed. Idempotency, not an error.
        SELECT id INTO transfer_id FROM ledger.transfer WHERE reference = ref;
        RETURN transfer_id;
END $$;

-- Fix 2: SERIALIZABLE, and a retry loop in the CLIENT. The database
-- cannot retry for you, because it does not know your transaction's
-- inputs.
--
--   BEGIN ISOLATION LEVEL SERIALIZABLE;
--     ... the same work, without FOR UPDATE ...
--   COMMIT;
--
--   On SQLSTATE 40001 (serialization_failure), sleep briefly and run
--   the whole transaction again. On 40P01 (deadlock_detected), likewise.

-- ------------------------------------------------------------------
-- Write skew: the anomaly only SERIALIZABLE prevents.
-- ------------------------------------------------------------------
-- Rule: at least one of accounts 1 and 2 must stay non-negative.
--
--   A: SELECT sum(balance) FROM account WHERE id IN (1,2);  -- 200
--      ... sees 200, withdraws 150 from account 1
--   B: SELECT sum(balance) FROM account WHERE id IN (1,2);  -- 200
--      ... sees 200, withdraws 150 from account 2
--
-- Both committed. Each was valid alone. Together the rule is broken,
-- and no row was updated by both - so row locks do not help. Only
-- predicate locking catches this.

-- ------------------------------------------------------------------
-- Watching the damage: bloat and locks.
-- ------------------------------------------------------------------
SELECT relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;

SELECT blocked.pid AS blocked_pid, blocked.query AS blocked_query,
       blocking.pid AS blocking_pid, blocking.query AS blocking_query
FROM pg_stat_activity blocked
JOIN pg_stat_activity blocking
  ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;

Discussion

No questions on this topic yet. Sign in to ask the first one.