Transactions, Isolation & MVCC

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A transaction groups statements so that they succeed or fail together and are isolated from concurrent work. The SQL-standard theory (ACID, the four isolation levels, the classic anomalies) is in SQL Transactions. This page shows how PostgreSQL implements it: multiversion concurrency control (MVCC), what each isolation level really guarantees here, the locks involved, and how to see and resolve contention. The row-version mechanics (xmin, xmax, vacuum) are in Architecture.

The demonstrations run two or three real psql sessions at the same time against PostgreSQL 18.6. A transcript line starts with the session that issued it (A>, B>, C>), followed by that statement’s real output; a statement that blocks shows nothing until the session it waits for finishes, and its result is printed at the moment it returns. Tables live in a scratch schema lab.

Transactions and autocommit

Outside an explicit transaction, every statement is its own transaction (autocommit). BEGIN (or START TRANSACTION) opens a block that ends with COMMIT or ROLLBACK. A failed statement inside a block puts the whole transaction in an aborted state in which everything but ROLLBACK is refused, a behaviour that differs from some other databases (see Savepoints below). Utilities such as CREATE INDEX CONCURRENTLY and VACUUM cannot run inside a block. Unlike many databases, DDL is transactional: CREATE TABLE, ALTER TABLE and DROP roll back with the transaction, which makes schema migrations atomic (see Evolving the Database Model).

Snapshots and visibility

Under MVCC each query sees a snapshot: the set of transactions whose effects are visible, taken at a moment in time. A row version is visible if the transaction that created it (xmin) is in the snapshot as committed and the one that deleted it (xmax), if any, is not. The isolation level determines when the snapshot is taken: at the start of every statement (READ COMMITTED) or at the first statement of the transaction (REPEATABLE READ and SERIALIZABLE).

sequenceDiagram participant A as session A participant B as session B participant DB as database A->>DB: BEGIN, first query takes snapshot S1 B->>DB: UPDATE row, COMMIT (new row version) A->>DB: second query Note over A,DB: READ COMMITTED takes a new snapshot S2 and sees the change Note over A,DB: REPEATABLE READ keeps S1 and does not

pg_current_snapshot() prints a snapshot as xmin:xmax:xip_list: transactions below xmin are finished and visible, those at or above xmax have not started, and the listed ones were in progress. PostgreSQL supports three distinct levels: READ UNCOMMITTED is accepted but behaves as READ COMMITTED, because dirty reads are impossible with MVCC.

Level Dirty read Non-repeatable read Phantom read Serialization anomaly

READ COMMITTED (default)

no

possible

possible

possible

REPEATABLE READ

no

no

no (snapshot isolation)

possible (write skew)

SERIALIZABLE

no

no

no

no (SSI aborts a transaction)

READ COMMITTED

The default level takes a new snapshot for each statement. A statement never sees uncommitted data, but two statements in one transaction can see different committed data, a non-repeatable read:

A> BEGIN;
BEGIN
A> SELECT balance FROM accounts WHERE id = 1;
 balance
---------
  100.00
(1 row)
B> UPDATE accounts SET balance = balance + 50 WHERE id = 1;
UPDATE 1
A> SELECT balance FROM accounts WHERE id = 1;
 balance
---------
  150.00
(1 row)
A> COMMIT;
COMMIT

Writers do not lose updates though. When a READ COMMITTED UPDATE or DELETE meets a row that another open transaction has already changed, it waits, and when the other transaction commits it re-reads the new row version and re-evaluates its WHERE clause against it before applying the change. Two concurrent increments both take effect:

A> BEGIN;
BEGIN
A> UPDATE accounts SET balance = balance + 50 WHERE id = 1;
UPDATE 1
B> UPDATE accounts SET balance = balance + 25 WHERE id = 1;
A> COMMIT;
COMMIT
B> (the earlier, blocked statement now returns)
UPDATE 1
A> SELECT balance FROM accounts WHERE id = 1;
 balance
---------
  175.00
(1 row)

The final balance is 175, not 125 or 150. This works because the update is expressed as balance = balance + 25, evaluated at write time. A read-modify-write cycle in the application (SELECT, compute, UPDATE accounts SET balance = 175) would lose an update; guard such cycles with SELECT ... FOR UPDATE, an optimistic version column, or a higher isolation level.

REPEATABLE READ

REPEATABLE READ takes one snapshot at the first statement and keeps it, so the transaction sees a frozen view and no phantom rows (this is snapshot isolation, stronger than the standard requires). If it then tries to modify a row that was changed and committed by a transaction that started after its snapshot, it cannot proceed and fails with SQLSTATE 40001:

A> BEGIN ISOLATION LEVEL REPEATABLE READ;
BEGIN
A> SELECT balance FROM accounts WHERE id = 1;
 balance
---------
  100.00
(1 row)
A> SELECT pg_current_snapshot();
 pg_current_snapshot
---------------------
 1824:1824:
(1 row)
B> UPDATE accounts SET balance = balance + 50 WHERE id = 1;
UPDATE 1
A> SELECT balance FROM accounts WHERE id = 1;
 balance
---------
  100.00
(1 row)
A> UPDATE accounts SET balance = balance - 10 WHERE id = 1;
ERROR:  could not serialize access due to concurrent update
A> ROLLBACK;
ROLLBACK

A’s second read still shows 100.00 even though B committed 150.00, which is the repeatable read. A’s update would have been based on a stale value, so PostgreSQL aborted it with could not serialize access due to concurrent update. The application must catch the error (SQLSTATE 40001), roll back, and run the whole transaction again. Any code that uses REPEATABLE READ or SERIALIZABLE needs this retry loop.

SERIALIZABLE and write skew

Snapshot isolation still permits an anomaly called write skew: two transactions each read an overlapping set of rows, then each writes a different row, based on what it read, and the combination violates a rule that neither broke alone. The classic example is an on-call rota that must always have one doctor on duty:

-- both doctors are on call; each transaction checks that at least two are, then goes off call
A> BEGIN ISOLATION LEVEL REPEATABLE READ;
BEGIN
B> BEGIN ISOLATION LEVEL REPEATABLE READ;
BEGIN
A> SELECT count(*) FROM doctors WHERE on_call;
 count
-------
     2
(1 row)
B> SELECT count(*) FROM doctors WHERE on_call;
 count
-------
     2
(1 row)
A> UPDATE doctors SET on_call = false WHERE name = 'alice';
UPDATE 1
B> UPDATE doctors SET on_call = false WHERE name = 'bob';
UPDATE 1
A> COMMIT;
COMMIT
B> COMMIT;
COMMIT
A> SELECT * FROM doctors ORDER BY name;
 name  | on_call
-------+---------
 alice | f
 bob   | f
(2 rows)

Both commits succeeded and nobody is on call. Neither transaction wrote a row the other wrote, so there was no write-write conflict to detect. SERIALIZABLE closes the gap with Serializable Snapshot Isolation (SSI): PostgreSQL tracks read-write dependencies between concurrent transactions with predicate locks (SIReadLock entries in pg_locks), and when it finds a dangerous cycle it aborts one transaction. The same script at SERIALIZABLE:

A> BEGIN ISOLATION LEVEL SERIALIZABLE;
BEGIN
B> BEGIN ISOLATION LEVEL SERIALIZABLE;
BEGIN
A> SELECT count(*) FROM doctors WHERE on_call;
 count
-------
     2
(1 row)
B> SELECT count(*) FROM doctors WHERE on_call;
 count
-------
     2
(1 row)
A> UPDATE doctors SET on_call = false WHERE name = 'alice';
UPDATE 1
B> UPDATE doctors SET on_call = false WHERE name = 'bob';
UPDATE 1
A> COMMIT;
COMMIT
B> COMMIT;
ERROR:  could not serialize access due to read/write dependencies among transactions
DETAIL:  Reason code: Canceled on identification as a pivot, during commit attempt.
HINT:  The transaction might succeed if retried.
A> SELECT * FROM doctors ORDER BY name;
 name  | on_call
-------+---------
 alice | f
 bob   | t
(2 rows)

B’s COMMIT failed with SQLSTATE 40001: the first committer wins, and B’s transaction was rolled back, so Bob remains on call. Serialization failures are not bugs; they are the cost of correctness, and the contract is that the application retries the transaction from the beginning. Retried, B now sees one doctor on call and its own check refuses to go off duty:

B> BEGIN ISOLATION LEVEL SERIALIZABLE;
BEGIN
B> SELECT count(*) FROM doctors WHERE on_call;
 count
-------
     1
(1 row)
B> COMMIT;
COMMIT

A correct retry loop re-executes the whole transaction, including its reads, because the decision may depend on them. Pseudocode (shown as an outline, not executed here):

repeat up to N times:
    BEGIN ISOLATION LEVEL SERIALIZABLE
    read, decide, write
    COMMIT
    if the error is SQLSTATE 40001 (serialization_failure) or 40P01 (deadlock_detected):
        ROLLBACK, wait a short random delay, retry
    else:
        stop

Guidelines: keep serializable transactions short; do read-only work in READ ONLY DEFERRABLE transactions (they wait for a safe snapshot and are then never aborted); expect more failures with a large number of concurrent transactions touching the same data, and add indexes so SSI’s predicate locks stay at row or page granularity rather than escalating to the whole relation (max_pred_locks_per_transaction). Alternatives that avoid isolation-level changes are explicit locks, covered next, and constraints (a unique or exclusion constraint turns many write-skew patterns into an immediate conflict; see Indexing).

Row-level locks

An UPDATE or DELETE locks the rows it touches until the transaction ends. SELECT ... FOR UPDATE takes the same lock without changing the row, which makes read-then-write sequences safe: the second session waits, then sees the committed result. Related modes are FOR NO KEY UPDATE (what an ordinary UPDATE of non-key columns takes, and compatible with foreign-key checks), FOR SHARE and FOR KEY SHARE (taken on referenced rows by foreign-key checks). Two modifiers control waiting: NOWAIT fails at once if the row is locked, and SKIP LOCKED ignores locked rows. A third control, lock_timeout, bounds the wait for any lock.

A> BEGIN;
BEGIN
A> SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
 id | owner | balance
----+-------+---------
  1 | ada   |  100.00
(1 row)
B> BEGIN;
BEGIN
B> SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;
ERROR:  could not obtain lock on row in relation "accounts"
B> ROLLBACK;
ROLLBACK
B> BEGIN; SELECT * FROM accounts ORDER BY id FOR UPDATE SKIP LOCKED;
BEGIN
 id | owner | balance
----+-------+---------
  2 | alan  |  100.00
(1 row)
B> ROLLBACK;
ROLLBACK
B> BEGIN; SET LOCAL lock_timeout = '500ms'; UPDATE accounts SET balance = 0 WHERE id = 1;
BEGIN
SET
ERROR:  canceling statement due to lock timeout
CONTEXT:  while updating tuple (0,1) in relation "accounts"
B> ROLLBACK;
ROLLBACK
A> COMMIT;
COMMIT

A holds the lock on row 1. NOWAIT raised an error immediately, SKIP LOCKED returned only the unlocked row 2, and a plain UPDATE gave up after the 500 ms lock_timeout. SKIP LOCKED is the basis of a work queue in a table: many workers each claim a different pending job, with no waiting and no double processing:

A> BEGIN;
BEGIN
B> BEGIN;
BEGIN
A> UPDATE jobs SET state = 'running'
   WHERE id = (SELECT id FROM jobs WHERE state = 'pending' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
   RETURNING id, payload;
 id | payload
----+---------
  1 | job 1
(1 row)

UPDATE 1
B> UPDATE jobs SET state = 'running'
   WHERE id = (SELECT id FROM jobs WHERE state = 'pending' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
   RETURNING id, payload;
 id | payload
----+---------
  2 | job 2
(1 row)

UPDATE 1
A> COMMIT;
COMMIT
B> COMMIT;
COMMIT
A> SELECT id, state FROM jobs ORDER BY id;
 id |  state
----+---------
  1 | running
  2 | running
  3 | pending
  4 | pending
  5 | pending
(5 rows)

Each worker claimed a different job (1 and 2) even though both ran before either committed; without SKIP LOCKED the second would have waited for the first. If a worker crashes, its transaction rolls back and the job returns to pending automatically.

Table-level locks

Every statement also takes a lock on each table it touches, in one of eight modes. Most of the time the modes are compatible: an ordinary SELECT takes ACCESS SHARE, and INSERT, UPDATE and DELETE take ROW EXCLUSIVE, which do not conflict with each other. The dangerous ones come from DDL:

Mode Taken by Conflicts with

ACCESS SHARE

SELECT

ACCESS EXCLUSIVE only

ROW SHARE

SELECT ... FOR UPDATE and similar

EXCLUSIVE, ACCESS EXCLUSIVE

ROW EXCLUSIVE

INSERT, UPDATE, DELETE, MERGE

SHARE and stronger

SHARE UPDATE EXCLUSIVE

VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY, some ALTER TABLE

itself and stronger

SHARE

CREATE INDEX (non-concurrent)

ROW EXCLUSIVE and stronger (blocks writes)

ACCESS EXCLUSIVE

Most ALTER TABLE, DROP TABLE, TRUNCATE, VACUUM FULL, CLUSTER, LOCK TABLE by default

everything, including SELECT

Locks are held until the end of the transaction. The hazard is the lock queue: a lock request waits behind the holders it conflicts with, and requests that arrive later queue behind it even if they would be compatible with the current holders. A DDL statement waiting for a long-running reader therefore blocks every new reader:

A> BEGIN; SELECT count(*) FROM accounts;
BEGIN
 count
-------
     2
(1 row)
B> ALTER TABLE accounts ADD COLUMN note text;
C> SELECT count(*) FROM accounts;
D> SELECT a.application_name AS session, l.mode, l.granted FROM pg_locks l JOIN pg_stat_activity a USING (pid) WHERE l.relation = 'accounts'::regclass AND a.application_name IN ('A','B','C') ORDER BY l.granted DESC, a.application_name;
 session |        mode         | granted
---------+---------------------+---------
 A       | AccessShareLock     | t
 B       | AccessExclusiveLock | f
 C       | AccessShareLock     | f
(3 rows)
A> COMMIT;
COMMIT
B> (the earlier, blocked statement now returns)
ALTER TABLE
C> (the earlier, blocked statement now returns)
 count
-------
     2
(1 row)

Session A merely read the table and stayed open. B’s ALTER TABLE wanted ACCESS EXCLUSIVE, which conflicts with A’s ACCESS SHARE, so it waited (granted = f). C’s plain SELECT is compatible with A, yet it queued behind B and was also blocked until A committed. This is why production migrations set a short lock_timeout (and retry) before DDL, and why an open transaction can take a site down; see Evolving the Database Model.

Observing locks and waits

Two views answer "who is waiting for whom". pg_stat_activity shows each session’s state, its current statement and, for a waiting one, wait_event_type and wait_event. pg_locks lists every held and awaited lock, and pg_blocking_pids(pid) returns the sessions blocking a given one.

A> BEGIN;
BEGIN
A> UPDATE accounts SET balance = balance - 1 WHERE id = 1;
UPDATE 1
B> UPDATE accounts SET balance = balance + 1 WHERE id = 1;
D> SELECT application_name AS session, state, wait_event_type, wait_event, left(query, 38) AS query FROM pg_stat_activity WHERE application_name IN ('A','B') ORDER BY application_name;
 session |        state        | wait_event_type |  wait_event   |                 query
---------+---------------------+-----------------+---------------+----------------------------------------
 A       | idle in transaction | Client          | ClientRead    | UPDATE accounts SET balance = balance
 B       | active              | Lock            | transactionid | UPDATE accounts SET balance = balance
(2 rows)
D> SELECT a.application_name AS session, l.locktype, l.mode, l.granted FROM pg_locks l JOIN pg_stat_activity a USING (pid) WHERE a.application_name IN ('A','B') AND l.locktype IN ('relation', 'transactionid', 'tuple') ORDER BY a.application_name, l.locktype, l.mode;
 session |   locktype    |       mode       | granted
---------+---------------+------------------+---------
 A       | relation      | RowExclusiveLock | t
 A       | relation      | RowExclusiveLock | t
 A       | transactionid | ExclusiveLock    | t
 B       | relation      | RowExclusiveLock | t
 B       | relation      | RowExclusiveLock | t
 B       | transactionid | ExclusiveLock    | t
 B       | transactionid | ShareLock        | f
 B       | tuple         | ExclusiveLock    | t
(8 rows)
D> SELECT a.application_name AS waiting, b.application_name AS blocked_by FROM pg_stat_activity a, LATERAL unnest(pg_blocking_pids(a.pid)) AS blocker(pid) JOIN pg_stat_activity b ON b.pid = blocker.pid WHERE a.application_name = 'B';
 waiting | blocked_by
---------+------------
 B       | A
(1 row)
A> COMMIT;
COMMIT
B> (the earlier, blocked statement now returns)
UPDATE 1

B waits with wait_event_type = Lock and wait_event = transactionid: a row-level conflict is implemented as a wait for the other transaction’s id to finish (the ShareLock on A’s transactionid with granted = f). A holds RowExclusiveLock on the table and its index, and B holds the tuple lock that serializes the queue for that row. The last query names the blocker. When A, which is idle in transaction here, finished, B continued. For a real incident, the query to keep handy is the last one, joined to pg_stat_activity.query, together with pg_terminate_backend(pid) to end a runaway blocker. Further monitoring views are in Administration.

Advisory locks

Advisory locks are locks whose meaning is defined by the application: PostgreSQL manages them in the lock table but never takes them itself. They coordinate things that are not rows, such as "only one instance runs the nightly report". The key is a bigint (or two int values). A session-level lock stays until released or the connection ends; a transaction-level lock (..._xact_lock) is released at commit or rollback and cannot leak.

A> SELECT pg_try_advisory_lock(42) AS got_it;
 got_it
--------
 t
(1 row)
B> SELECT pg_try_advisory_lock(42) AS got_it;
 got_it
--------
 f
(1 row)
D> SELECT l.locktype, l.objid, l.mode, l.granted, a.application_name AS holder FROM pg_locks l JOIN pg_stat_activity a USING (pid) WHERE l.locktype = 'advisory';
 locktype | objid |     mode      | granted | holder
----------+-------+---------------+---------+--------
 advisory |    42 | ExclusiveLock | t       | A
(1 row)
A> SELECT pg_advisory_unlock(42);
 pg_advisory_unlock
--------------------
 t
(1 row)
B> SELECT pg_try_advisory_lock(42) AS got_it;
 got_it
--------
 t
(1 row)
B> SELECT pg_advisory_unlock_all();
 pg_advisory_unlock_all
------------------------

(1 row)
A> BEGIN; SELECT pg_try_advisory_xact_lock(hashtext('nightly-report')) AS got_it;
BEGIN
 got_it
--------
 t
(1 row)
B> SELECT pg_try_advisory_xact_lock(hashtext('nightly-report')) AS got_it;
 got_it
--------
 f
(1 row)
A> COMMIT;
COMMIT
B> SELECT pg_try_advisory_xact_lock(hashtext('nightly-report')) AS got_it;
 got_it
--------
 t
(1 row)

The try variants return immediately with true or false; the plain pg_advisory_lock waits. hashtext('nightly-report') turns a name into a numeric key. Session-level advisory locks do not mix well with connection pooling in transaction mode (the lock belongs to a server connection that another client may inherit), so prefer the transaction-level form there.

Deadlocks

A deadlock is a cycle of sessions each waiting for a lock another holds. PostgreSQL does not time out; after deadlock_timeout (1 s by default) a waiting session runs the detector, and if it finds a cycle it aborts one transaction with SQLSTATE 40P01, letting the others proceed.

flowchart LR A["session A holds row 1, wants row 2"] -->|waits for| B["session B holds row 2, wants row 1"] B -->|waits for| A
A> BEGIN;
BEGIN
B> BEGIN;
BEGIN
A> UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE 1
B> UPDATE accounts SET balance = balance - 10 WHERE id = 2;
UPDATE 1
A> UPDATE accounts SET balance = balance + 10 WHERE id = 2;
B> UPDATE accounts SET balance = balance + 10 WHERE id = 1;
UPDATE 1
A> (the earlier, blocked statement now returns)
ERROR:  deadlock detected
DETAIL:  Process 3432 waits for ShareLock on transaction 1856; blocked by process 3429.
Process 3429 waits for ShareLock on transaction 1855; blocked by process 3432.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,2) in relation "accounts"
A> ROLLBACK;
ROLLBACK
B> COMMIT;
COMMIT

Each transfer locked its source row first, then tried the other. A waited for B, B then asked for A’s row, and about a second later the detector aborted A (deadlock detected), after which B’s statement completed. The DETAIL shows the cycle. The cure is a consistent lock order: always touch rows in the same order (for example, lower id first, or SELECT ... ORDER BY id FOR UPDATE at the start of the transaction), keep transactions short, and retry on 40P01 like on 40001. log_lock_waits logs any wait longer than deadlock_timeout, which helps find the contended statements.

Savepoints

A savepoint marks a point inside a transaction to which you can roll back without abandoning the whole transaction. Without one, any error aborts the entire block, as the next transcript shows; with one, the failed part is undone and the transaction continues:

A> BEGIN;
BEGIN
A> INSERT INTO accounts VALUES (3, 'grace', 50);
INSERT 0 1
A> SAVEPOINT before_risky;
SAVEPOINT
A> INSERT INTO accounts VALUES (3, 'duplicate', 1);
ERROR:  duplicate key value violates unique constraint "accounts_pkey"
DETAIL:  Key (id)=(3) already exists.
A> SELECT 1;
ERROR:  current transaction is aborted, commands ignored until end of transaction block
A> ROLLBACK TO SAVEPOINT before_risky;
ROLLBACK
A> INSERT INTO accounts VALUES (4, 'linus', 75);
INSERT 0 1
A> COMMIT;
COMMIT
A> SELECT * FROM accounts ORDER BY id;
 id | owner | balance
----+-------+---------
  1 | ada   |  100.00
  2 | alan  |  100.00
  3 | grace |   50.00
  4 | linus |   75.00
(4 rows)

The duplicate key error put the transaction in the aborted state (commands ignored until end of transaction block); ROLLBACK TO SAVEPOINT restored it, row 3 from before the savepoint survived, and the commit kept both valid inserts. Drivers use this pattern implicitly: JDBC’s autosave setting, or an ORM’s nested transaction, issue a savepoint per statement or block. A savepoint costs a subtransaction id; hundreds of them per transaction, or a long-lived transaction with many, can slow visibility checks, so do not create one per row in a bulk loop. PL/pgSQL EXCEPTION blocks also create a subtransaction.

Idle in transaction

A session that has issued BEGIN and then does nothing is idle in transaction. It is the single most common cause of mysterious contention in applications: it keeps its row locks, it holds table locks that block DDL (see the lock queue above), and, less obviously, its snapshot prevents VACUUM from removing any row version deleted after that snapshot, so the table bloats while the transaction sits there. pg_stat_activity.backend_xmin shows the oldest snapshot a session holds:

A> BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM churn;
BEGIN
 count
-------
 20000
(1 row)
B> DELETE FROM churn WHERE id <= 15000;
DELETE 15000
B> VACUUM (VERBOSE, INDEX_CLEANUP OFF) churn;
tuples: 0 removed, 20000 remain, 15000 are dead but not yet removable
removable cutoff: 1864, which was 16 XIDs old when operation ended
VACUUM
-- output trimmed to the main table
D> SELECT application_name AS session, state, backend_xmin, now() - xact_start AS open_for FROM pg_stat_activity WHERE application_name = 'A';
 session |        state        | backend_xmin |    open_for
---------+---------------------+--------------+-----------------
 A       | idle in transaction |         1864 | 00:00:05.226956
(1 row)
A> COMMIT;
COMMIT
B> VACUUM (VERBOSE, INDEX_CLEANUP OFF) churn;
tuples: 15000 removed, 1142 remain, 0 are dead but not yet removable
removable cutoff: 1880, which was 1 XIDs old when operation ended
VACUUM
-- output trimmed to the main table

While A’s snapshot was open the first VACUUM reported the 15,000 deleted rows as dead but not yet removable: it could not reclaim them, because A might still need to see them. After A committed, the second vacuum removed them. The remedies are operational: set idle_in_transaction_session_timeout (and transaction_timeout, new in PostgreSQL 17) so that the server ends sessions that forget to commit, and fix application code that opens a transaction before a slow external call.

A> SET idle_in_transaction_session_timeout = '2s';
SET
A> BEGIN; SELECT 1;
BEGIN
 ?column?
----------
        1
(1 row)
A> SELECT 2;
FATAL:  terminating connection due to idle-in-transaction timeout
server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.
connection to server was lost

After two seconds idle inside the transaction the server terminated the session (FATAL), which is far preferable to leaving the transaction holding locks and a snapshot. Set the timeout per role or database for application users, not for maintenance roles.

Summary: choosing an approach

Need Use

Simple correct updates

Atomic statements such as SET balance = balance + 25; the default READ COMMITTED.

Read, decide, then write on the same rows

SELECT ... FOR UPDATE (or FOR NO KEY UPDATE), or an optimistic version column.

Consistent multi-statement reads (reports)

REPEATABLE READ, ideally READ ONLY, accepting that long ones hold back vacuum.

Rules spanning several rows (write skew)

SERIALIZABLE with a retry loop, or a constraint that makes the rule explicit.

Job queues and "claim next"

FOR UPDATE SKIP LOCKED.

Run-once coordination

Advisory locks, preferably transaction-level.

Safe DDL on a busy table

Short lock_timeout plus retry; CREATE INDEX CONCURRENTLY.

For the isolation theory shared by every engine see SQL Transactions; for how the row versions behind all of this are stored see Architecture. Monitoring and cancelling sessions is in Administration, and the configuration of timeouts and checkpoints in Performance Tuning. For comparison, MongoDB’s multi-document transactions are in Multi-document ACID Transactions, and pooling and failover effects on long transactions are in Replication & High Availability.