Sub topic 2
Locks last until the end of the transaction
This chapter assumes you can write basic SQL and use BEGIN, COMMIT and ROLLBACK. It also assumes you can run two psql sessions side by side. You should know what a primary key is. The previous chapter explained why MVCC (multiversion concurrency control) lets readers and writers work without blocking each other. This chapter covers the other half: what PostgreSQL does lock, and how long it keeps those locks.
The rule that explains most lock problems
PostgreSQL acquires most locks automatically as statements run. It releases them in one place only: when the transaction ends, by COMMIT or ROLLBACK. There is no UNLOCK command for table locks or row locks. The statement that took a lock finishing does not release it.
A transaction that has finished its useful work but has not yet committed still holds every lock it took. Most real lock problems follow from this: long transactions, "idle in transaction" sessions, and application code that does slow work between statements.
A first demonstration
This is the same two-account setup used throughout the tutorial. Run the setup, then the sessions in the order shown by the comments.
CREATE TABLE accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100);
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session B (blocks until session A commits or rolls back)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- Session A
COMMIT;Session A's UPDATE finished instantly, but session B waits anyway. Session A still holds the row lock on id = 1. B's statement returns the moment A commits. If A had run ROLLBACK, B would also proceed, and it would see the original balance of 100.
What kinds of locks exist
Lock scope describes what a lock protects. PostgreSQL has three scopes you will meet in practice.
| Scope | Protects | Taken by | Released |
|---|---|---|---|
| Table-level | A whole table (or index, view and similar objects) | Nearly every statement, `LOCK TABLE`, DDL | End of transaction |
| Row-level | Individual rows | `UPDATE`, `DELETE`, `SELECT ... FOR ...` | End of transaction |
| Advisory | An application-chosen number | `pg_advisory_lock()` and variants | Depends on the variant (see below) |
The next chapters cover table-level modes and row-level locks in detail. For now, remember two facts.
- Every statement takes a table-level lock, even a plain
SELECT. ASELECTtakesACCESS SHARE, which conflicts only withACCESS EXCLUSIVE, the lock that mostALTER TABLEforms need. This is why a stuck migration can block even simple reads. - Row-level locks are stored differently from table locks. PostgreSQL records them in the row itself (in its header, as the ID of the locking transaction) rather than in shared memory. This means a transaction can lock millions of rows without exhausting a lock table. It also means row locks do not appear as one entry per row in
pg_locks.
Seeing the locks your own transaction holds
You can ask PostgreSQL what the current session holds. pg_backend_pid() returns the process ID of your own session.
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT locktype, relation::regclass AS relation, mode, granted
FROM pg_locks
WHERE pid = pg_backend_pid()
ORDER BY locktype, relation::text;You should see rows like these (the exact set can vary slightly by version and by which pg_locks row belongs to the query itself):
| locktype | relation | mode | granted |
|---|---|---|---|
| relation | accounts | RowExclusiveLock | t |
| relation | accounts_pkey | RowExclusiveLock | t |
| transactionid | (null) | ExclusiveLock | t |
| virtualxid | (null) | ExclusiveLock | t |
Read this output carefully.
- The
UPDATEtookRowExclusiveLockon the table and on the primary key index. The name is misleading: it is a table-level lock mode, and it does not mean "a row is locked". - No row lock is listed. The locked row is recorded inside the table itself.
- The
transactionidentry is the key to blocking. Every transaction that modifies data holds an exclusive lock on its own transaction ID. When session B waits for A's row, B is really waiting to acquire a share lock on A's transaction ID. That wait ends when A's transaction ends. This is the mechanism behind "locks last until the end of the transaction".
Run ROLLBACK; before continuing so this demonstration does not keep its locks.
Autocommit: each statement is its own transaction
In psql, a statement outside BEGIN runs in its own implicit transaction. Its locks are released when the statement finishes. This is why single UPDATE statements rarely cause trouble: the lock lives for milliseconds.
The danger starts when you open an explicit transaction. Many drivers and ORMs do this for you. In several of them, the default is to issue BEGIN before your first statement and keep the transaction open until you call commit(). If you forget to commit, or if your code does something slow before committing, the locks stay.
Partial release with savepoints
A savepoint marks a point inside a transaction that you can roll back to without abandoning the whole transaction.
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1; -- locks row 1
SAVEPOINT before_second;
UPDATE accounts SET balance = balance - 10 WHERE id = 2; -- locks row 2
ROLLBACK TO SAVEPOINT before_second; -- releases the lock on row 2
-- the lock on row 1 is still held
COMMIT; -- releases everything elseROLLBACK TO SAVEPOINT releases locks acquired after the savepoint. It does not release locks taken before it. Savepoints are the only way to give back locks before the transaction ends, and they work by undoing the work that took the locks.
Application code that holds locks too long
The most common real-world cause of lock pile-ups is not SQL at all. It is slow work placed inside a transaction. This Python example uses psycopg 3.
import psycopg
import requests
def charge_holding_lock(conn: psycopg.Connection, account_id: int) -> None:
# Problem: the row lock on this account is held while we wait for
# a remote service that may take up to 30 seconds.
with conn.transaction():
conn.execute(
"UPDATE accounts SET balance = balance - 10 WHERE id = %s",
(account_id,),
)
requests.post("https://payments.example.com/charge", timeout=30)
def charge_short_lock(conn: psycopg.Connection, account_id: int) -> None:
# Better: do the slow call first, then take the lock and commit quickly.
requests.post("https://payments.example.com/charge", timeout=30)
with conn.transaction():
conn.execute(
"UPDATE accounts SET balance = balance - 10 WHERE id = %s",
(account_id,),
)In the first function, every other session that touches that account waits for the HTTP call. If the call hangs, they all hang.
The second function has its own trade-off. If the commit fails after the charge succeeds, you have charged without recording it. Reordering the steps does not make the work atomic. Real payment code needs idempotency keys or a record of the intent. The general rule is still sound: do slow, non-database work outside the transaction, or accept the lock duration knowingly.
Idle in transaction
A session that has run BEGIN and some statements, and is now waiting for the client to send the next command, shows up as idle in transaction. It uses no CPU, but it holds all its locks. You can find such sessions like this:
SELECT pid,
state,
now() - xact_start AS transaction_age,
now() - state_change AS idle_for,
left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start;xact_start is when the transaction began. query shows the last statement the session ran, not what it is doing now. A session with an old xact_start and a state of idle in transaction is usually a client that forgot to commit, crashed without disconnecting, or is waiting on something slow.
A server-side safety net is the idle_in_transaction_session_timeout setting, which terminates sessions that stay idle in a transaction longer than the limit. A later chapter covers the timeout settings.
SET idle_in_transaction_session_timeout = '30s';Advisory locks are the exception
Advisory locks have two forms, and they differ in lifetime.
pg_advisory_xact_lock(key)andpg_try_advisory_xact_lock(key)are released automatically at transaction end, like other locks.pg_advisory_lock(key)andpg_try_advisory_lock(key)are session-level. They surviveCOMMITandROLLBACK. They are released only bypg_advisory_unlock(key)or when the session ends.
Session-level advisory locks surprise people who use connection pools. The lock belongs to the connection, and the pool hands that connection to another request after you "finish". If you forgot to unlock, the next user of the connection still holds the lock. Prefer the _xact_ variants unless you have a specific reason not to.
Other things that keep locks alive
- Prepared transactions (
PREPARE TRANSACTION) keep their locks after the session disconnects, untilCOMMIT PREPAREDorROLLBACK PREPARED. A forgotten prepared transaction can block a table indefinitely. Checkpg_prepared_xacts. - A failed statement inside a transaction puts the transaction into an aborted state. The transaction still holds its locks until you send
ROLLBACK. Do not leave a failed transaction sitting open. LOCK TABLEoutside a transaction block is an error, because the lock would be released immediately.
Common mistakes
- Starting a transaction early in a request handler and committing at the end, with network calls in between.
- Running an interactive
psqlsession withBEGIN, then going to lunch. - Assuming a
SELECTis lock-free and therefore harmless to leave open. It holdsACCESS SHAREon the table, which blocksALTER TABLEforms that needACCESS EXCLUSIVE. - Using session-level advisory locks behind a connection pool.
- Expecting a savepoint release (
RELEASE SAVEPOINT) to free locks. It only discards the savepoint marker. OnlyROLLBACK TO SAVEPOINTreleases locks, and it does so by undoing the work.
Practice
Exercise
Session A runs BEGIN and UPDATE accounts SET balance = balance - 10 WHERE id = 1, then stops and waits for input. Session B runs UPDATE accounts SET balance = 0 WHERE id = 2. Does B wait? Then B runs UPDATE accounts SET balance = 0 WHERE id = 1. Does it wait now, and what ends the wait?
Show answer
The first statement does not wait, because A only holds a row lock on id = 1 and B is updating a different row. The second statement waits because A holds the row lock on id = 1. The wait ends when A's transaction ends, by COMMIT or ROLLBACK. Finishing A's UPDATE statement does not release the lock.
Exercise
A transaction takes a row lock on row 1, sets SAVEPOINT s, updates row 2, runs RELEASE SAVEPOINT s, and has not yet committed. Which row locks does it hold? How would the answer change if it ran ROLLBACK TO SAVEPOINT s instead of RELEASE?
Show answer
With RELEASE SAVEPOINT s, it holds the locks on both row 1 and row 2, because releasing a savepoint only removes the marker and keeps the work and its locks. With ROLLBACK TO SAVEPOINT s, the update to row 2 is undone and its lock is released, so only the lock on row 1 remains.
Exercise
Your application uses a connection pool and calls pgadvisorylock(42) at the start of a job and COMMIT at the end, with no call to pgadvisoryunlock. Why can other jobs stay blocked after the job finishes, and what is the simplest fix?
Show answer
pgadvisorylock is a session-level lock, so COMMIT does not release it. The pooled connection keeps the lock after the job ends, and other jobs that request key 42 wait. The simplest fix is to use pgadvisoryxactlock(42) or pgtryadvisoryxact_lock(42) inside the transaction, which releases the lock at commit or rollback.