PostgreSQL Locking and Concurrency Control
Understand PostgreSQL MVCC, row and table locks, advisory locks, deadlocks, lock inspection, and safe transaction retries with practical SQL examples.
PostgreSQL uses MVCC for ordinary reads and locks to coordinate writes, explicit locking reads, and schema changes. This guide separates row, table, and advisory locks, walks through a two-transaction deadlock, and shows how to inspect blockers and retry a failed transaction safely.
PostgreSQL Locking and Concurrency Control
PostgreSQL uses multiversion concurrency control (MVCC) for ordinary reads, alongside locks that coordinate writes, locking reads, and schema changes. Knowing which operation holds which lock helps explain why some queries wait while others can read a previously committed row version.
Introduction
PostgreSQL uses MVCC so each statement reads a consistent snapshot of committed data. Ordinary reads do not take row locks that conflict with writers. Explicit row locks coordinate transactions that need to prevent another transaction from changing selected rows, and table locks protect relations from incompatible operations such as some schema changes.
Row-level locking reads and writes
PostgreSQL has several table-level lock modes and four row-level lock modes. The word “shared” or “exclusive” alone is not enough to describe what an operation blocks; the lock level and mode matter.
Shared Locks
SELECT ... FOR SHARE takes a shared row-level lock. Multiple transactions can hold this lock on the same row, but it conflicts with updates, deletes, and stronger row-locking reads on that row. A plain SELECT does not need this lock: it reads a visible committed version through MVCC.
-- Transaction 1
SELECT balance FROM accounts WHERE id = 1 FOR SHARE;
-- Transaction 2 can also read
SELECT balance FROM accounts WHERE id = 1 FOR SHARE;
-- Success: both can read simultaneously
Row-level write locks
UPDATE takes a row-level lock on each row it changes. Another transaction that tries to update or lock that same row may wait. A plain SELECT normally continues using its statement snapshot; only a conflicting operation such as SELECT ... FOR UPDATE, or a table-level ACCESS EXCLUSIVE lock, blocks an ordinary read.
-- Transaction 1
UPDATE accounts SET balance = 900 WHERE id = 1;
-- Takes a row-level lock on the updated row
-- Transaction 2 can read the last committed version
SELECT balance FROM accounts WHERE id = 1;
-- A plain SELECT does not wait for the row-level write lock
FOR SHARE vs FOR UPDATE
SELECT ... FOR SHARE and SELECT ... FOR UPDATE acquire row-level locks. FOR UPDATE conflicts with other row-locking operations and writes on the same row; it does not block a plain SELECT under MVCC.
-- Row-level shared lock: another locking read can share it; writers wait
SELECT * FROM accounts WHERE id = 1 FOR SHARE;
-- Strong row-level lock: other writers and locking reads on this row wait
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;
Use FOR SHARE when another transaction must not update or delete the selected rows before your transaction ends. Use FOR UPDATE when the transaction will modify them or needs to exclude other row lockers. For less restrictive locking, PostgreSQL also provides FOR NO KEY UPDATE and FOR KEY SHARE.
Lock Escalation
Some database engines escalate many row locks into a table lock. PostgreSQL does not escalate row-level locks this way. A statement that updates many rows keeps row-level locks on those rows and also holds its ordinary table-level lock mode. Locking a row marks tuple state on disk, so a large update still has I/O, WAL, and transaction-duration costs.
-- PostgreSQL keeps row-level locks for the rows this statement changes.
-- It does not convert them into a table-level lock by escalation.
UPDATE orders SET processed = true WHERE status = 'pending';
This does not mean a large transaction is free of contention: writers and locking reads of those rows can wait until commit or rollback. Keep batches bounded when that reduces lock duration or rollback work.
Deadlocks
flowchart LR
subgraph T1["Transaction A"]
A1["Locks account 1"]
A2["Waits for account 2"]
end
subgraph T2["Transaction B"]
B1["Locks account 2"]
B2["Waits for account 1"]
end
A1 --> A2
B1 --> B2
A2 -.->|"Row 2 held by B"| B1
B2 -.->|"Row 1 held by A"| A1
A deadlock happens when transactions wait in a cycle. In this example, each transaction holds one account row and requests the row held by the other. PostgreSQL detects the cycle and aborts one transaction, allowing the other to continue. The victim is not predictable, so applications should not depend on which transaction gets aborted. PostgreSQL documents row-level deadlocks and automatic detection.
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1; -- Locks account 1
-- Session B, run concurrently
BEGIN;
UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- Locks account 2
-- Back in Session A: waits for Session B's account 2 lock
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- Back in Session B: completes the cycle by waiting for account 1
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- PostgreSQL detects the deadlock and aborts one session with SQLSTATE 40P01.
After an error, the failed transaction is aborted; roll it back before reusing the connection. Applications should test the SQLSTATE code, not parse localized error text. PostgreSQL assigns 40P01 to deadlock_detected (error code reference).
Preventing Deadlocks
Consistent lock ordering prevents this two-row cycle. Keep transactions short, and acquire multiple rows in the same order across code paths.
For example, lock both account IDs in ascending order before updating either row:
-- Both transactions lock the same set of account IDs in ascending order
BEGIN;
SELECT id FROM accounts
WHERE id = ANY (ARRAY[1, 2])
ORDER BY id
FOR UPDATE;
-- Apply the transfer updates, then commit.
Ordering reduces this class of deadlock, but other code paths and lock types can still form cycles. The application must handle the deadlock error too.
Handling Deadlocks in Application Code
If a transaction fails with 40P01, retry the complete transaction from the beginning, with a small bounded backoff. Do not retry unrelated database errors. This example uses Psycopg 3; conn.transaction() exits by rolling back if a statement raises, so each retry starts with a fresh transaction. Keep external side effects outside the retry block or make them idempotent.
import random
import time
import psycopg
def transfer_funds(conn, from_account, to_account, amount):
account_ids = sorted({from_account, to_account})
if len(account_ids) != 2:
raise ValueError("source and destination must be different accounts")
for attempt in range(4):
try:
with conn.transaction():
with conn.cursor() as cursor:
cursor.execute(
"SELECT id FROM accounts WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
(account_ids,),
)
if [row[0] for row in cursor.fetchall()] != account_ids:
raise ValueError("both accounts must exist")
cursor.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, from_account),
)
cursor.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, to_account),
)
return
except psycopg.Error as exc:
if exc.sqlstate != "40P01" or attempt == 3:
raise
time.sleep(min(0.05 * (2**attempt), 0.4) + random.uniform(0, 0.025))
For SERIALIZABLE transactions, PostgreSQL can also report 40001 (serialization_failure); handle that separately if the application uses that isolation level. The database does not automatically replay application logic. See PostgreSQL’s guidance on retrying transactions.
Optimistic vs Pessimistic Concurrency Control
There are two philosophical approaches to concurrency control.
Pessimistic Concurrency Control
Assume conflicts will happen, so prevent them with locks before any work begins.
When Transaction A runs SELECT ... FOR UPDATE, PostgreSQL holds a row-level lock until the transaction ends. Another transaction that tries to update, delete, or take a conflicting row lock on that row waits. A plain SELECT can still read the last committed version through MVCC.
Pessimistic locking can make the critical section easier to reason about, but it does not eliminate all transaction failures. Under contention, transactions may wait, time out, or deadlock. If many transactions lock the same row, they make progress one at a time for that row.
The NOWAIT variant returns an error immediately if a conflicting row lock is held rather than waiting. Your application can then try another resource or report that the row is busy.
-- Attempt lock without waiting
SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "accounts"
Use explicit locking when a transaction must reserve or validate specific rows before changing them, such as inventory allocation or seat reservation. Keep the locked part short.
Optimistic Concurrency Control
Optimistic concurrency control reads without reserving a row first, then checks whether the version still matches when writing. The UPDATE still takes ordinary PostgreSQL row and table locks while it runs; the version predicate detects that an earlier read is stale.
-- Read current version
SELECT balance, version FROM accounts WHERE id = 1;
-- balance=1000, version=5
-- Update with version check
UPDATE accounts
SET balance = balance - 100, version = version + 1
WHERE id = 1 AND version = 5;
-- If version changed, update affects 0 rows -> retry
This pattern detects a conflict when the update affects zero rows. The application can then re-read and recompute, return a conflict to the caller, or apply another product-specific policy. It does not eliminate database locks or guarantee higher throughput; contention, transaction shape, and retry cost determine whether it helps.
When to Use Each
Explicit row locks can fit short transactions that must reserve rows before calculating a change. Version checks can fit short transactions where conflicts are uncommon and the application can safely recompute. Neither approach guarantees ordering or throughput by itself.
A practical choice depends on the cost of waiting, the cost of retrying, and what correctness requires. For a balance transfer, a single SQL update such as balance = balance + delta or a short transaction that locks both rows in a consistent order is safer than reading balances into application memory and later writing computed values. A like count may use an atomic SQL increment rather than a read-modify-write cycle.
Optimistic vs Pessimistic: Trade-off Summary
| Aspect | Explicit row lock (FOR UPDATE) |
Version check (UPDATE ... WHERE version = ...) |
|---|---|---|
| Conflict signal | Waits for a conflicting row lock, or may deadlock | Update affects zero rows if the expected version changed |
| Work after a conflict | Continue after lock, or handle a transaction error | Re-read and recompute, or return a conflict |
| Database locks | Yes | Yes, during the update |
| Main trade-off | Waiting and lock ordering | Conflict handling and retry policy |
Row-Level vs Page-Level vs Table-Level Locks
PostgreSQL has separate row-level and table-level locks. Row-level locks coordinate access to individual tuples. Table-level locks protect a relation from incompatible operations; the mode names below refer to table locks, even when they contain the word ROW.
Table-level lock modes
These are table-level modes acquired by common commands, not a hierarchy of row-lock strength:
ACCESS SHARE— acquired by ordinarySELECT; conflicts only withACCESS EXCLUSIVE.ROW SHARE— acquired bySELECT ... FOR UPDATE,FOR NO KEY UPDATE,FOR SHARE, orFOR KEY SHARE.ROW EXCLUSIVE— acquired byINSERT,UPDATE,DELETE, andMERGE; compatible with otherROW EXCLUSIVElocks.SHARE UPDATE EXCLUSIVE— used byVACUUM(withoutFULL),ANALYZE, andCREATE INDEX CONCURRENTLY.SHARE— acquired byCREATE INDEXwithoutCONCURRENTLY.SHARE ROW EXCLUSIVEandEXCLUSIVE— used by some DDL or maintenance operations and conflict with progressively more modes.ACCESS EXCLUSIVE— acquired by commands such asTRUNCATE,DROP TABLE,VACUUM FULL, and manyALTER TABLEoperations; it conflicts with every table-level mode, including theACCESS SHAREused by ordinary reads.
-- Acquires a table-level ROW EXCLUSIVE lock and row-level locks
UPDATE accounts SET balance = 900 WHERE id = 1;
-- Acquires ACCESS EXCLUSIVE on the table
ALTER TABLE accounts ADD COLUMN new_col TEXT;
ROW EXCLUSIVE is compatible with another ROW EXCLUSIVE table lock, so concurrent inserts and updates are not blocked by that table lock alone. Their row-level locks can still conflict on the same tuple. See the PostgreSQL table-lock compatibility table.
Advisory Locks
PostgreSQL provides advisory locks for application-level locking needs.
When to Use Advisory Locks
Use advisory locks when you need to coordinate an application-defined resource that does not map naturally to a row. For short operations, transaction-level advisory locks are often easier to manage because PostgreSQL releases them automatically at commit or rollback.
BEGIN;
-- Acquire a transaction-level advisory lock
SELECT pg_advisory_xact_lock(12345);
-- Do work
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT; -- Releases the transaction-level advisory lock
Advisory Lock Functions
pg_advisory_lock(key)— exclusive advisory lockpg_advisory_lock_shared(key)— shared advisory lockpg_try_advisory_lock(key)— non-blocking exclusive lockpg_try_advisory_lock_shared(key)— non-blocking shared lockpg_advisory_unlock(key)— release exclusive lockpg_advisory_unlock_all()— release all locks held by sessionpg_advisory_xact_lock(key)— exclusive lock released at transaction endpg_advisory_xact_lock_shared(key)— shared lock released at transaction end
Session-level locks such as pg_advisory_lock remain held until explicitly unlocked or the session ends, even if the transaction that acquired them rolls back. Transaction-level locks such as pg_advisory_xact_lock follow commit and rollback automatically. Advisory locks do not enforce access rules by themselves; all cooperating application code must use the same key and locking convention. See the PostgreSQL advisory lock documentation.
Monitoring Locks
Viewing Active Locks
SELECT
l.locktype,
l.relation::regclass AS relation_name,
l.mode,
l.granted,
l.virtualxid,
l.transactionid,
p.pid,
p.usename,
p.state,
p.wait_event_type,
p.wait_event,
p.query
FROM pg_locks l
JOIN pg_stat_activity p ON l.pid = p.pid
WHERE NOT l.granted
ORDER BY p.query_start;
pg_locks shows requested and granted locks. A waiting row lock may appear as a wait on a transaction ID rather than a tuple lock, so the locktype and relation_name columns need context. For a direct blocked-session to blocker mapping, use pg_blocking_pids with pg_stat_activity:
Understanding the output:
pid— the process ID of the waiting session. Use this to identify and terminate if needed.locktype— kind of object requested: for example,relation(table),transactionid(transaction),tuple(tuple), oradvisory(application-defined lock).mode— the lock mode requested, such asAccessExclusiveLockorRowShareLock.relation::regclass— the table or index being locked, shown as a readable name.query— the currently executing query in that session. If it showsidle in transaction, the session is open but not doing anything, a common source of lock problems.
-- Find lock waits with relation names and query details
SELECT
l.locktype,
l.relation::regclass AS table_name,
l.mode,
l.granted,
l.virtualxid,
l.transactionid,
p.pid,
p.usename,
p.query,
p.state,
p.query_start
FROM pg_locks l
JOIN pg_stat_activity p ON l.pid = p.pid
WHERE NOT l.granted
AND NOT l.pid = pg_backend_pid()
ORDER BY p.query_start;
pg_blocking_pids returns the process IDs blocking a given session. This query lists each blocked session and its blocker:
-- Find what's blocking a specific waiting session
SELECT
blocked.pid AS blocked_pid,
blocked.query AS blocked_query,
blocker.pid AS blocking_pid,
blocker.query AS blocking_query
FROM pg_stat_activity blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS blockers(pid) ON true
JOIN pg_stat_activity blocker ON blocker.pid = blockers.pid
WHERE blocked.wait_event_type = 'Lock'
ORDER BY blocked.query_start;
See the PostgreSQL pg_locks view and pg_blocking_pids function for details.
Killing a Blocking Process
-- Get the pid from the queries above
SELECT pg_terminate_backend(12345);
-- This rolls back the transaction and releases locks
Use pg_cancel_backend(pid) to cancel the current statement or pg_terminate_backend(pid) to end a session and roll back its open transaction. Inspect the query and confirm the operational impact before terminating a backend. Both functions require suitable privileges.
Version checks and row locks
An application can use a version column to detect that a row changed since it was read. This is often called optimistic locking, but the SQL UPDATE still acquires PostgreSQL row and table locks while it executes. If concurrent updates touch the same row, one may wait; if the version predicate no longer matches, the update affects zero rows and the application can decide whether to recompute or report a conflict.
Common Production Failures
Deadlock victim retry not implemented: A write transaction can fail with SQLSTATE 40P01 when PostgreSQL detects a deadlock and aborts it. If the operation is safe to retry, roll back and replay the complete transaction from the beginning with a bounded retry policy. Consistent lock ordering reduces deadlocks but cannot rule out every cycle.
Long-running transaction and old snapshot: A report query that keeps a transaction open while generating a PDF does not block row updates if it uses plain SELECT, but its old snapshot can delay vacuum cleanup of dead row versions. Keep the transaction short and generate the PDF after reading the needed results.
Version conflict is ignored: A version-guarded update affects zero rows because the stored version changed. Check the row count, then recompute and retry if the operation is safe to replay, or return a conflict to the caller.
FOR UPDATE on a scan that returns many rows: SELECT ... FOR UPDATE locks every matching row; PostgreSQL does not escalate those locks into a table-level lock. Other writers or locking reads of those rows can wait until the transaction ends. Limit the rows or split the operation into bounded transactions when that fits the task.
SELECT FOR SHARE blocking writes: SELECT ... FOR SHARE holds shared row-level locks and blocks conflicting updates and deletes of those rows. A plain SELECT uses MVCC and does not block row updates. Use a locking read only when the transaction needs to prevent the selected rows from changing.
Session advisory lock not released: pg_advisory_lock remains held after a transaction rolls back and lasts until explicit unlock or session end. For transaction-scoped work, use pg_advisory_xact_lock; PostgreSQL releases it on commit or rollback.
Quick Recap Checklist
- PostgreSQL uses MVCC for plain reads; row locks coordinate writers and locking reads
- PostgreSQL does not escalate many row locks into a table-level lock
- Deadlocks are resolved by PostgreSQL rolling back one transaction automatically
- Prevent deadlocks by locking rows in consistent order across transactions
- A failed transaction can be retried from the beginning for
40P01when the operation is safe to replay FOR SHAREandFOR UPDATEare row-level locks;ROW SHAREandROW EXCLUSIVEare table-level modes- Advisory locks can be session-scoped or transaction-scoped
- Long-running transactions can hold old snapshots and delay vacuum cleanup
- Connection pools must satisfy: pool_size × instances <= max_connections
Common Problems and Fixes
| Problem | Fix |
|---|---|
| Deadlock victim not retried | Retry the complete transaction on 40P01 when safe to replay |
| Long-running transaction | Keep it short; old snapshots can delay vacuum cleanup |
| Version check returns zero rows | Re-read and recompute, or return a conflict |
| FOR UPDATE on a large scan | Bound selected rows or split work into transactions |
| FOR SHARE blocks row updates | Use plain SELECT unless rows must be protected from changes |
| Session advisory lock survives rollback | Use pg_advisory_xact_lock for transaction-scoped work |
Interview Questions
Under READ COMMITTED, two plain SELECT statements can both read 1000. If each application then writes a computed literal value of 1100, the second update can overwrite the first. Prefer an atomic expression such as UPDATE accounts SET balance = balance + 100 WHERE id = 1 when it fits the operation. Or select the row FOR UPDATE before computing: a second SELECT ... FOR UPDATE waits and then returns the current row version. A plain SELECT does not wait for that row lock; it reads the committed version visible to its statement snapshot.
SELECT ... FOR UPDATE over 50,000 pending orders. Which operations can wait, and does PostgreSQL escalate those row locks into a table lock?The query takes row-level locks on all matching rows, along with a table-level ROW SHARE lock. PostgreSQL does not escalate those row locks into a table-level lock. Writers and conflicting locking reads on the selected rows can wait; ordinary SELECT statements can still read committed row versions through MVCC. A bounded batch can reduce lock duration, rollback work, and the number of concurrently reserved rows.
Explicit row locking reserves selected rows before the application makes a change. Version checks detect that a row changed since it was read. Both approaches still use PostgreSQL locks while writing, and neither guarantees ordering by itself. Choose based on whether waiting or recomputing after a conflict is simpler and safe for the operation.
pg_advisory_lock is session-level, so rolling back its surrounding transaction does not release the lock. It remains held until an explicit unlock or the session ends. For work scoped to one transaction, use pg_advisory_xact_lock; PostgreSQL releases it automatically on commit or rollback. Advisory locks only coordinate code that follows the same locking convention.
If the report uses SELECT ... FOR UPDATE, conflicting updates and row-locking reads wait on the selected rows until the transaction ends. A plain SELECT does not hold row locks and does not block updates, but a long-running transaction can keep an old snapshot that delays vacuum cleanup. Read the rows in a short transaction, then generate the PDF after the transaction closes.
A version-guarded update that matches no row reports the conflict through its affected-row count. The application should check that count and then either re-read and recompute the update or return a conflict to the caller. Retrying blindly without recomputing can overwrite a newer value.
If both transactions hold FOR SHARE on the same row and then request FOR UPDATE, each stronger lock conflicts with the other transaction's existing lock. PostgreSQL detects the resulting wait cycle and aborts one transaction with SQLSTATE 40P01 (deadlock_detected). If the transaction will update the row, acquire FOR UPDATE before doing the work that depends on it.
A single transaction locking 5 million rows holds enormous lock pressure and creates a massive write-ahead log footprint. If the transaction fails midway, the rollback takes as long as the original execution. Long-running transactions also prevent autovacuum from cleaning dead tuples, causing bloat. The chunked approach: use LIMIT with an ORDER BY id in a cursor, processing, say, 10,000 rows per transaction. Each chunk commits quickly, releases locks, and allows vacuum to clean up. The trade-off is you need idempotency in case a chunk fails and you need to restart — the processed chunks should not be re-processed.
BEGIN; SELECT ... FOR UPDATE; UPDATE ...; COMMIT;. Under what conditions does the FOR UPDATE lock get released before COMMIT?The row lock is normally held until the transaction ends, either by COMMIT or ROLLBACK. It blocks conflicting writes and row-locking reads on the same row; a plain SELECT can still read a committed version through MVCC. Locks acquired after a savepoint are released if the transaction rolls back to that savepoint, but this usually is not a substitute for keeping transactions short.
PostgreSQL advisory locks exist only within one database server instance. A dedicated lock row can coordinate transactions that write to the same primary database, but a row lock cannot be acquired on a read-only replica and does not coordinate independent primaries. If work spans independent database instances, choose a coordinator whose failure and consistency behavior fits the system; do not assume a PostgreSQL advisory lock is distributed.
max_connections = 100 but after deploying 20 application instances with pool_size=10 each, you start getting connection errors. The math says 20 x 10 = 200 but max_connections is 100. What happens and how do you solve it?The math fails: 20 x 10 = 200 required backend connections but PostgreSQL only allows 100. Each application instance holds 10 connections, but with 20 instances all wanting connections simultaneously, you need 200. The solution is pgBouncer in transaction mode deployed as a sidecar to each application instance. Each application connects to its local pgBouncer (10 connections per pgBouncer), and all pgBouncers multiplex down to a small number of actual PostgreSQL backend connections (say, 20-30). This breaks the N x pool_size dependency on max_connections. Without pgBouncer, you either need to reduce pool_size, reduce instance count, or increase max_connections (but increasing max_connections increases memory pressure on PostgreSQL).
wait_event = Lock for a specific table. What queries do you run to identify which sessions are waiting and which are holding the lock?Use pg_blocking_pids to map blocked sessions to blockers, and inspect the lock rows for details:
SELECT
blocked.pid AS blocked_pid,
blocked.query AS blocked_query,
blocker.pid AS blocking_pid,
blocker.query AS blocking_query
FROM pg_stat_activity AS blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS blockers(pid) ON true
JOIN pg_stat_activity AS blocker ON blocker.pid = blockers.pid
WHERE blocked.wait_event_type = 'Lock';
Then inspect pg_locks for each PID, including ungranted requests. Check what the blocking session is doing before canceling its statement or terminating the session. See the PostgreSQL documentation for pg_locks and pg_blocking_pids.
The lock is automatically released when the database connection terminates — PostgreSQL rolls back any uncommitted transactions. When the application process dies without calling ROLLBACK, the TCP connection closes and PostgreSQL detects the session loss, then performs cleanup including releasing all locks held by that session. This is why connection poolers can safely recycle connections after application crashes — the database guarantees lock cleanup.
pg_advisory_lock and pg_try_advisory_lock? When would you use each?pg_advisory_lock waits for a session-level lock; pg_try_advisory_lock returns immediately with true or false. Use pg_advisory_xact_lock or pg_try_advisory_xact_lock when the coordination should end with the current transaction. A lock key is application-defined, so every worker for the same resource must agree on it.
INSERT acquires a table-level ROW EXCLUSIVE lock and row-level locks as needed. Multiple inserts can hold that table mode concurrently. It conflicts with table modes such as SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE; by contrast, VACUUM and CREATE INDEX CONCURRENTLY use SHARE UPDATE EXCLUSIVE, which is compatible with ROW EXCLUSIVE.
TRUNCATE a table that has uncommitted changes from another transaction?TRUNCATE requires an AccessExclusiveLock which blocks all concurrent access — including other transactions reads and writes. If another transaction is running on the table, TRUNCATE waits. If the other transaction is uncommitted and holding a lock, TRUNCATE will wait for it to commit or rollback. TRUNCATE is not recommended on tables with long-running active transactions because it blocks all access until the lock is acquired.
A plain SELECT acquires table-level ACCESS SHARE, not ROW SHARE. That mode conflicts only with ACCESS EXCLUSIVE, so it does not wait on ordinary row updates. It can wait if a conflicting ACCESS EXCLUSIVE request is already queued, for example from TRUNCATE or some ALTER TABLE operations. A SELECT ... FOR SHARE adds row-level locks that conflict with updates and deletes. Use pg_blocking_pids() to identify the blocker.
Zero rows affected means no row matched the ID and expected version. Another transaction may have changed it since the read. Check the affected-row count and either re-read and recompute the change, or return a conflict to the caller. Do not report success when the update matched no row.
lock_timeout aborts a statement that waits too long for any lock; statement_timeout aborts a statement that runs too long for any reason. Deadlocks are detected separately after PostgreSQL waits for deadlock_timeout; a lock timeout is not a deadlock detector. Set timeouts according to the application's latency policy, and retry a timed-out operation only when it is safe to replay. See PostgreSQL timeout settings and deadlock_timeout.
SELECT ... FOR UPDATE NOWAIT and gets an error immediately instead of waiting. What happened?NOWAIT makes the row-locking part fail immediately if a selected row cannot be locked, instead of waiting. It does not change how a plain SELECT behaves, and it does not guarantee the rest of the transaction cannot wait for a different lock. This is useful when the application wants immediate feedback that a row is busy. The error is a lock-not-available condition, not a deadlock; PostgreSQL detects deadlocks when transactions wait in a cycle.
Further Reading
- PostgreSQL 18 explicit locking documentation — table, row, advisory locks, and deadlocks
- PostgreSQL 18 advisory lock functions — advisory lock API reference
- PostgreSQL 18 MVCC introduction — visibility rules for concurrent reads
pg_locksview documentation — inspect outstanding lock requests- PostgreSQL 18 transaction isolation — isolation levels and concurrent updates
Conclusion
PostgreSQL uses MVCC for ordinary reads and row locks when a transaction needs to coordinate changes to specific tuples. Table locks protect relations from incompatible commands, while advisory locks coordinate application-defined resources. Consistent lock ordering reduces deadlocks; when PostgreSQL aborts a transaction with 40P01, retry the whole transaction only if its work is safe to replay.
For more on keeping transactions safe, see Transaction Isolation and Relational Databases.
Category
Related Posts
Isolation Levels: READ COMMITTED Through SERIALIZABLE
Understand READ COMMITTED, REPEATABLE READ, and SERIALIZABLE isolation levels, read vs write anomalies, and SET TRANSACTION syntax.
Database Capacity Planning: A Practical Guide
Plan database capacity from measured growth, retention, workload, and provisioning time. Includes a storage forecast and PostgreSQL-specific memory guidance.
Connection Pooling: HikariCP, pgBouncer, and ProxySQL
Learn connection pool sizing, HikariCP, pgBouncer, and ProxySQL, timeout settings, idle management, and when pooling helps or hurts performance.