Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 20 min · revision 3

Finding Blockers and Untangling Deadlocks

Catch a hanging UPDATE in pg_stat_activity, name its blocker with pg_blocking_pids, fail fast with lock_timeout, reproduce a deadlock and its 40P01 victim, then prevent both with lock order and session timeouts.

Contentsand lesson path

What you will learn

  • Diagnose lock waits and deadlocks with pg_stat_activity and pg_locks, and restructure transactions to avoid them.

Prerequisites: SQL Fundamentals

01. Goal and setup

Deployments freeze, checkouts hang, error rates spike — and the database is "slow". Often the database is fine; one session is holding a lock and a queue has formed behind it. This lab gives you the two-step reflex for that incident: look in pg_stat_activity for who is waiting, then call pg_blocking_pids() to name who is holding. Then it reproduces the louder failure, a deadlock, and prevents it.

You need: the throwaway container from the anomalies lab still running on port 55436, plus psycopg in the uv environment. The lab script connects three sessions tagged ti-a, ti-b and ti-monitor — tagging connections with application_name at connect time is what makes the monitoring output readable, in the lab and in production. Here is the whole script; it recreates a two-row accounts table each run, then plays the five steps below in order (run it with python blockers.py; each step's output is shown with its explanation):

Python · blockers.py
"""Lab driver: blockers, lock_timeout, a deadlock, lock ordering, idle timeout."""
import os
import threading
import time

import psycopg

DSN = os.environ.get("DSN", "postgresql://lab:lab@localhost:55436/tilab")


def session(name: str) -> psycopg.Connection:
    # autocommit: every BEGIN below is explicit; application_name tags the session
    return psycopg.connect(DSN, autocommit=True, application_name=name)


def in_thread(fn):
    t = threading.Thread(target=fn)
    t.start()
    return t


def reset(mon):
    mon.execute("DROP TABLE IF EXISTS accounts")
    mon.execute("CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL)")
    mon.execute("INSERT INTO accounts VALUES (1, 100), (2, 100)")


def step1(a, b, mon):
    a.execute("BEGIN")
    a.execute("UPDATE accounts SET balance = balance + 1 WHERE id = 1")
    blocked = in_thread(lambda: b.execute(
        "UPDATE accounts SET balance = balance + 1 WHERE id = 1"))
    time.sleep(0.5)
    print("monitor> app        state               waiting on")
    for app, state, wtype, wevent in mon.execute(
            "SELECT application_name, state, wait_event_type, wait_event"
            " FROM pg_stat_activity WHERE datname = current_database()"
            " AND application_name LIKE 'ti-%' ORDER BY application_name"):
        print(f"monitor> {app:<10} {state:<19} {wtype or '-'}:{wevent or '-'}")
    holders = mon.execute("SELECT pg_blocking_pids(%s)", (b.info.backend_pid,))
    pids = holders.fetchone()[0]
    same = pids == [a.info.backend_pid]
    print(f"monitor> pg_blocking_pids(B) is [pid of ti-a]: {same}")
    for locktype, mode, granted in mon.execute(
            "SELECT locktype, mode, granted FROM pg_locks"
            " WHERE pid = %s AND NOT granted", (b.info.backend_pid,)):
        print(f"monitor> pg_locks, B waits for: {locktype} {mode} granted={granted}")
    time.sleep(2.5)
    print(f"B still waiting after 3s: {blocked.is_alive()}")
    a.execute("ROLLBACK")
    blocked.join()
    print("B finished once A rolled back")


def step2(a, b):
    a.execute("BEGIN")
    a.execute("UPDATE accounts SET balance = balance + 1 WHERE id = 1")
    b.execute("SET lock_timeout = '1s'")
    t0 = time.monotonic()
    try:
        b.execute("UPDATE accounts SET balance = balance + 1 WHERE id = 1")
    except psycopg.errors.LockNotAvailable as err:
        print(f"B gave up after at least 1s: {time.monotonic() - t0 >= 1.0}")
        print(f"  SQLSTATE {err.sqlstate} - {err.diag.message_primary}")
    b.execute("RESET lock_timeout")
    a.execute("ROLLBACK")


def crossing_updates(a, b, ordered: bool):
    ok = {}

    def run(conn, name, first, second):
        try:
            conn.execute("BEGIN")
            if ordered:  # lock both rows in ascending id order, then work
                t0 = time.monotonic()
                conn.execute("SELECT id FROM accounts WHERE id IN (1, 2)"
                             " ORDER BY id FOR UPDATE")
                waited = time.monotonic() - t0 > 0.5
                print(f"{name}> locked rows 1 and 2, waited for the other: {waited}")
            conn.execute("UPDATE accounts SET balance = balance + 1"
                         " WHERE id = %s", (first,))
            time.sleep(1.0)  # let the other session take its first lock
            conn.execute("UPDATE accounts SET balance = balance + 1"
                         " WHERE id = %s", (second,))
            conn.execute("COMMIT")
            ok[name] = True
        except psycopg.errors.DeadlockDetected as err:
            conn.execute("ROLLBACK")
            print(f"{name} was the deadlock victim: {err.sqlstate} "
                  f"{err.diag.message_primary}")
            ok[name] = False

    ta = in_thread(lambda: run(a, "A", 1, 2))
    time.sleep(0.2)
    tb = in_thread(lambda: run(b, "B", 2, 1))
    ta.join()
    tb.join()
    print(f"A committed: {ok['A']}  B committed: {ok['B']}")


def step5(a, b, mon):
    a.execute("SET idle_in_transaction_session_timeout = '2s'")
    a.execute("BEGIN")
    a.execute("UPDATE accounts SET balance = balance + 1 WHERE id = 1")
    print("A> BEGIN; UPDATE ... id=1; then the application goes quiet ...")
    time.sleep(3)
    try:
        a.execute("SELECT 1")
    except psycopg.Error as err:  # the server closed the session
        print("A> next use of the connection:")
        print(f"  SQLSTATE {err.sqlstate} - {err.diag.message_primary}")
    n = b.execute("UPDATE accounts SET balance = balance + 1 WHERE id = 1").rowcount
    print(f"B> UPDATE ... id=1 -> {n} row")


mon, a, b = session("ti-monitor"), session("ti-a"), session("ti-b")
reset(mon)
print("== step 1"); step1(a, b, mon)
print("== step 2"); step2(a, b)
DEADLOCKS = "SELECT deadlocks FROM pg_stat_database WHERE datname = current_database()"
before = mon.execute(DEADLOCKS).fetchone()[0]
print("== step 3"); crossing_updates(a, b, ordered=False)
time.sleep(1.5)  # sessions report their statistics about once a second
after = mon.execute(DEADLOCKS).fetchone()[0]
print(f"pg_stat_database.deadlocks grew by {after - before}")
print("== step 4"); crossing_updates(a, b, ordered=True)
print("== step 5"); step5(a, b, mon)

02. Step 1: the blocked UPDATE and its blocker

Session A updates account 1 and — exactly like a request handler that crashed, or a developer's open psql — never ends its transaction. Session B then updates the same row and waits, because row locks are held until COMMIT or ROLLBACK, not until the statement finishes. The monitor connection watches:

SQL · the two questions worth asking in an incident
SELECT application_name, state, wait_event_type, wait_event
FROM pg_stat_activity
WHERE datname = 'tilab' AND application_name LIKE 'ti-%';

SELECT pg_blocking_pids(<pid of ti-b>);   -- who holds the lock?

SELECT locktype, mode, granted FROM pg_locks  -- what is B waiting for?
WHERE pid = <pid of ti-b> AND NOT granted;
Expected output
monitor> app        state               waiting on
monitor> ti-a       idle in transaction Client:ClientRead
monitor> ti-b       active              Lock:transactionid
monitor> ti-monitor active              -:-
monitor> pg_blocking_pids(B) is [pid of ti-a]: True
monitor> pg_locks, B waits for: transactionid ShareLock granted=False
B still waiting after 3s: True
B finished once A rolled back

Read the row for ti-a: idle in transaction — the session has no query running but its transaction, and every lock in it, is still alive. ti-b is active and waiting on Lock:transactionid, and pg_blocking_pids returns exactly A's pid. The script compares the pids instead of printing them, because pids change on every run; in an incident you would print them, or join them back to pg_stat_activity to get the application name. The pg_locks row shows the wait itself: B asked for a ShareLock on A's transaction id and has not been granted it. PostgreSQL records a row lock on the row, not in a lock table, so a waiter queues on the transaction id of whoever locked the row, which is why the wait event reads Lock:transactionid. That single pg_blocking_pids call converts "the database is slow" into "session 383, application ti-a, has held a transaction open since 12:04". The remedy follows: end that transaction. In the lab A rolls back after three seconds, which is precisely when B finishes.

03. Step 2: refuse to queue — lock_timeout

B's three-second wait was gentle. Without a timeout it is infinite, and behind B grows a queue of everyone who touches that row. The same fail-fast defence the schema migrations skill applies to DDL works for data: bound the wait. SET lock_timeout = '1s' on B's session turns the hang into an error after one second:

Expected output
B gave up after at least 1s: True
  SQLSTATE 55P03 - canceling statement due to lock timeout

The statement is cancelled and, like any error, it aborts the transaction: further statements fail with "current transaction is aborted" until you roll back. Roll back to a savepoint taken before the statement, or roll back the whole transaction, and retry with backoff. Set it per session, for the operations that must not queue — not server-wide in postgresql.conf, where it would also cut off legitimate long waits such as batch jobs and migrations.

04. Step 3: the deadlock, and its victim

A deadlock is a cycle: A holds row 1 and wants row 2; B holds row 2 and wants row 1. Neither can ever proceed. PostgreSQL does not prevent this — it detects it: after a waiter has waited deadlock_timeout (one second by default, to keep the expensive cycle-check off the fast path), it searches the waits-for graph, finds the loop, and cancels one transaction to break it:

Expected output
A was the deadlock victim: 40P01 deadlock detected
A committed: False  B committed: True
pg_stat_database.deadlocks grew by 1

The victim gets SQLSTATE 40P01 and its entire transaction is rolled back; B proceeds and commits. Two facts to carry away. First, 40P01 is retryable, exactly like the 40001 from the lost-updates lesson: replay the whole transaction, and the second attempt usually wins because the other party is gone. Second, deadlocks are counted: pg_stat_database.deadlocks is how you notice a deadlock problem you are not yet feeling. The counter covers every deadlock since the statistics were last reset, so the script prints how much it grew during step 3, after a short pause, because each session passes its counts to the shared statistics in batches, at most about once a second.

Why A? In this script A starts waiting 0.2 s before B, so A's wait reaches deadlock_timeout first, A runs the check, finds the cycle and cancels its own transaction. That is what this schedule does on an idle machine, not a promise: the PostgreSQL documentation says which transaction is aborted is hard to predict and must not be relied on, so retry logic has to work whichever side loses.

05. Step 4: the fix — one lock order everywhere

A cycle needs two sessions acquiring the same rows in different orders. Remove the difference and you remove the deadlock, whatever the timing. The transfer workers in the previous lesson already did this with ORDER BY id FOR UPDATE; here it is as a standalone habit:

SQL · lock the pair in ascending id, then work
BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
UPDATE accounts SET balance = balance + 1 WHERE id = 2;
COMMIT;
Expected output · same interleaving that deadlocked before
A> locked rows 1 and 2, waited for the other: False
B> locked rows 1 and 2, waited for the other: True
A committed: True  B committed: True

B waited under a second — until A committed — instead of deadlocking: queued, not cancelled. A cycle cannot form because every session in the system takes the rows in ascending id order, so the waits-for graph is a straight line. The order itself is arbitrary — ascending primary key is just the easiest convention to hold everywhere, and "everywhere" is the point: one worker that locks 2-then-1 puts the cycle back.

06. Step 5: the safety net for forgotten transactions

The blocker in Step 1 was an accident waiting to be noticed. PostgreSQL can end such accidents by itself: idle_in_transaction_session_timeout closes any transaction left idle longer than the limit. Session A sets it to two seconds, updates, and goes quiet:

Expected output
A> BEGIN; UPDATE ... id=1; then the application goes quiet ...
A> next use of the connection:
  SQLSTATE 25P03 - terminating connection due to idle-in-transaction timeout
B> UPDATE ... id=1 -> 1 row

The server terminated A's transaction and its connection; B's next update, which A's lock had been blocking, succeeds. Set it for application roles to a value far above your intended transaction length — seconds for an API, minutes for a batch job — and treat a firing timeout as a bug report about a connection that forgot to commit, not as an annoyance to silence.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Incident reflexes

Three decisions from the moment things hang.

Q1. In step 3, A started waiting 0.2 s before B, and A was the deadlock victim. Why A, and can the retry code count on the session that waits first always losing?
Q2. Why tag each connection with application_name (ti-a, ti-b, ti-monitor) at connect time, as this lab does?
Q3. Why set lock_timeout on particular sessions rather than once for the whole server in postgresql.conf?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

Take the incident tooling further:

  1. Rewrite the monitor as a one-shot script your team could paste into a terminal during an incident: waiting sessions, their blockers, the blocked query, and the age of each blocking transaction (now() - xact_start).
  2. Run the 1,000-transfer workload from the previous lesson while polling pg_stat_activity once a second, and plot how many sessions sit in wait_event_type = 'Lock' under each fix.
  3. Add statement_timeout alongside lock_timeout on B's session and explain, in one sentence each, the different thing the two limits bound.

10. Review prompt

Without looking back: which two questions — one view, one function — diagnose any "who is blocking whom" incident? What does the state idle in transaction tell you that active with wait_event_type = 'Lock' does not? What error code and what rollback does a deadlock victim get, and what does the application do with it? Why does one global lock order prevent deadlocks, why is deadlock_timeout one second rather than one millisecond, and which timeout is the safety net for forgotten transactions?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check