Transactions & Concurrency

A database serves many users at once, and each of them expects to see consistent data and to have their changes either fully applied or not at all. Transactions provide that guarantee; isolation levels and locks decide how concurrent transactions interact. This lesson explains the guarantees, the anomalies they prevent, and how to handle conflicts in practice. Examples use PostgreSQL; differences in other engines are noted.

ACID Guarantees

A transaction is a group of statements that the database treats as one unit of work. The classic properties of a transaction are summarized as ACID.

The Four Properties

PropertyGuaranteeMechanism
AtomicityAll statements take effect, or none do.Undo on rollback or crash.
ConsistencyEach transaction moves the database between states that satisfy every declared constraint.Constraints checked at statement or commit time.
IsolationConcurrent transactions do not see each other's partial work, to the degree the isolation level promises.MVCC snapshots and locks.
DurabilityOnce committed, a change survives a crash.Write-ahead log flushed to disk at commit.

Transaction Boundaries

Clients run in autocommit mode by default: each statement is its own transaction. Group statements that must succeed together — such as a transfer between two accounts — in an explicit transaction:

BEGIN;

UPDATE account SET balance = balance - 100 WHERE id = 1;
UPDATE account SET balance = balance + 100 WHERE id = 2;

-- Both updates become visible to others at the same instant, or neither does.
COMMIT;

Keep transactions short. A transaction that stays open while waiting for user input or a remote API call holds locks and, in PostgreSQL, prevents VACUUM from cleaning up old row versions across the whole database. Watch for sessions in state idle in transaction, and set idle_in_transaction_session_timeout as a safety net.

Isolation Levels and Anomalies

Perfect isolation — every transaction behaving as if it ran alone — costs throughput. The SQL standard defines four isolation levels by the anomalies each one permits.

The Anomalies

  • Dirty read: seeing another transaction's uncommitted change, which may later be rolled back.
  • Non-repeatable read: reading the same row twice and getting different values because another transaction committed in between.
  • Phantom read: rerunning a query and getting new rows that another transaction inserted and committed.
  • Serialization anomaly: a result that no serial ordering of the transactions could have produced — for example, two doctors both going off call because each saw the other still on call.

The Four Levels

LevelDirty readNon-repeatable readPhantomSerialization anomaly
Read uncommittedAllowed by standard; not in PostgreSQLPossiblePossiblePossible
Read committedPreventedPossiblePossiblePossible
Repeatable readPreventedPreventedAllowed by standard; not in PostgreSQLPossible
SerializablePreventedPreventedPreventedPrevented

The standard sets minimum guarantees, and engines often exceed them. PostgreSQL treats read uncommitted as read committed, and its repeatable read is snapshot isolation, which also prevents phantoms. Read committed is the default in PostgreSQL, Oracle and SQL Server; MySQL's InnoDB defaults to repeatable read.

Snapshots and MVCC

PostgreSQL and Oracle use multi-version concurrency control: an update writes a new row version instead of overwriting the old one, and each transaction reads from a snapshot of committed versions. As a result, readers never block writers and writers never block readers. Under read committed, each statement gets a fresh snapshot; under repeatable read and serializable, the whole transaction uses the snapshot taken at its first statement. Old versions are cleaned up later — by VACUUM in PostgreSQL, by undo segments in Oracle.

Locking and Conflicts

MVCC removes reader–writer conflicts, but two transactions that write the same row still conflict. The second writer waits for the first to commit or roll back.

The Lost Update Problem

A classic bug under read committed is the read-modify-write pattern done in application code:

-- Session A and session B both run this concurrently:
SELECT stock FROM product WHERE id = 7;          -- both read 10
-- ...application computes 10 - 1 = 9...
UPDATE product SET stock = 9 WHERE id = 7;       -- both write 9: one sale is lost

Fix it by letting the database do the arithmetic atomically, or by locking the row when you read it:

-- Option 1: an atomic update with a guard; check the affected row count.
UPDATE product SET stock = stock - 1 WHERE id = 7 AND stock > 0;

-- Option 2: pessimistic locking for multi-step logic.
BEGIN;
SELECT stock FROM product WHERE id = 7 FOR UPDATE;  -- B waits here until A commits
UPDATE product SET stock = stock - 1 WHERE id = 7;
COMMIT;

Optimistic Concurrency

When conflicts are rare and transactions span user think-time (a web form open for minutes), hold no locks. Instead, add a version column and make the update conditional on the version the user saw:

UPDATE customer
   SET full_name = 'Ana Pop', version = version + 1
 WHERE id = 42
   AND version = 3;        -- the version read when the form was loaded
-- 0 rows updated means someone else changed the row: reload and ask the user.

Work Queues with SKIP LOCKED

Several workers taking jobs from one table would normally queue behind the same locked row. FOR UPDATE SKIP LOCKED (PostgreSQL 9.5+, Oracle, MySQL 8) lets each worker claim a different row without waiting:

BEGIN;
SELECT id, payload
  FROM job
 WHERE status = 'pending'
 ORDER BY created_at
 LIMIT 1
   FOR UPDATE SKIP LOCKED;
-- process the job, then:
UPDATE job SET status = 'done' WHERE id = :claimed_id;
COMMIT;

Deadlocks and Retries

Conflicts are not bugs to eliminate entirely; they are a normal outcome of concurrency that applications must handle.

Deadlocks

A deadlock occurs when transaction A waits for a lock held by B while B waits for a lock held by A. The database detects the cycle (in PostgreSQL after deadlock_timeout, one second by default) and aborts one transaction with SQLSTATE 40P01. Prevent most deadlocks by acquiring locks in a consistent order — for example, always updating accounts in ascending id order — and by keeping transactions short.

Serializable Transactions Must Retry

PostgreSQL implements serializable isolation with serializable snapshot isolation: transactions run without extra blocking, and if their combination could produce an anomaly, one of them fails with SQLSTATE 40001 (serialization_failure). The correct response is to retry the whole transaction from the beginning. Code the retry once, in a helper, as in this Python sketch using the psycopg driver:

import psycopg
from psycopg import errors

RETRYABLE = (errors.SerializationFailure, errors.DeadlockDetected)


def run_serializable(conn, work, attempts=5):
    """Run work(cur) in a SERIALIZABLE transaction, retrying on conflicts."""
    conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
    for attempt in range(1, attempts + 1):
        try:
            with conn.transaction():          # commits on success, rolls back on error
                with conn.cursor() as cur:
                    return work(cur)
        except RETRYABLE:
            if attempt == attempts:
                raise                          # give up after the last attempt

Retries are only safe if the transaction has no side effects outside the database, such as sending an e-mail; perform those after a successful commit.

Diagnose Blocking

When the application hangs, find out who is waiting on whom:

SELECT pid,
       pg_blocking_pids(pid) AS blocked_by,
       state,
       now() - xact_start    AS xact_age,
       left(query, 60)       AS query
  FROM pg_stat_activity
 WHERE cardinality(pg_blocking_pids(pid)) > 0;

Set lock_timeout for sessions that run DDL on busy tables, so a migration fails fast instead of queuing behind a long transaction while blocking every query that arrives after it.

Practice Lab

Open two terminal sessions to the same database, labelled A and B, and run the steps interleaved.

Observe Isolation Levels

  1. In A, start a read committed transaction and read a row; in B, update and commit it; read it again in A and note the change.
  2. Repeat with BEGIN ISOLATION LEVEL REPEATABLE READ in A and note that the second read is unchanged.
  3. Reproduce the lost-update problem, then fix it with an atomic update and with FOR UPDATE.

Provoke and Handle Conflicts

  1. Create a deadlock by updating two rows in opposite orders in A and B; read the error and the server log entry.
  2. Reproduce the on-call doctors anomaly under repeatable read, then show that serializable makes one transaction fail with 40001.
  3. Write a retry helper in your application language and show that the retried transaction sees the other's commit and makes a correct decision (at least one doctor stays on call).