What a lock actually protects
Every transaction that touches a row takes some form of lock, and the lock exists to preserve one of two properties: physical integrity, so two sessions never write the same bytes at once, and logical consistency, so readers observe a state the database was actually in. Confusing the two is why engineers blame "locking" for problems that are really isolation-level choices.
The distinction matters operationally. Exclusive locks required for physical integrity are short and non-negotiable: an update must hold the row until it commits or rolls back. Shared locks required for serialisable reads are optional and expensive, because they extend for the life of the transaction and scale poorly with reader count. When a system feels slow under load, the first question is whether you are paying for physical integrity you need or for a level of read protection nobody actually required.
By the end of this lesson you should be able to read a blocking chain from the system catalog, explain exactly which anomaly each isolation level permits, and choose between pessimistic and optimistic strategies using evidence rather than habit.
Lock modes and who waits for whom
Locks are taken at several granularities â row, page, table, schema â and the mode determines which other modes may coexist. Granularity is adaptive: an engine starts at row level and escalates to page or table when too many rows are locked, which is exactly when a transaction that meant to lock a handful of rows ends up blocking an entire table.
| Mode | Conflicts with | Held until | Typical use |
|---|---|---|---|
| Shared (S) | Exclusive | End of statement or transaction | Plain reads at serialisable level |
| Update (U) | Update, exclusive | End of transaction | Intent to upgrade on write |
| Exclusive (X) | Everything | Commit or rollback | Insert, update, delete |
| Intent shared (IS) | Intent exclusive, table X | End of transaction | Signals row-level reads below |
| Intent exclusive (IX) | Table S, table X | End of transaction | Signals row-level writes below |
| Shared row (SIX) | IX, table X | End of transaction | Table read plus some row writes |
| Schema / DDL | DDL of same object | End of statement | Add column, create index |
The intent locks in that table are the part people skip. They are cheap and almost invisible, but they are what stops a table-level lock from being granted while row-level writers are active. A blocking incident usually involves a session holding a table-level exclusive lock because it did something global â an ALTER, an index rebuild, a TRUNCATE â and every row-level transaction in the queue was waiting behind it.
Isolation levels and the anomalies they permit
Isolation is a promise about which anomalies a reader may observe. Each level trades a class of inconsistency for a class of locking cost, and the trade is worth making deliberately.
| Level | Dirty read | Non-repeatable read | Phantom | Lock cost |
|---|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible | Lowest |
| Read committed | Prevented | Possible | Possible | Short read locks |
| Repeatable read | Prevented | Prevented | Possible in most engines | Held shared locks |
| Snapshot / serializable | Prevented | Prevented | Prevented | Version store or range locks |
Dirty reads mean reading a row another transaction has written but not committed, which disappears entirely on rollback â the most dangerous anomaly, and the one almost no workload should accept. Non-repeatable reads mean the same row changes between two reads inside your transaction, which breaks any logic that reads a value and then writes based on it. Phantoms mean a COUNT or a range query returns different rows the second time, which breaks aggregation-based decisions such as "sum the batch then mark it processed".
Modern engines implement serialisable either with range locks, which block inserts into scanned ranges, or with snapshot plus a conflict check at commit. The second produces a different failure: instead of waiting, the transaction fails with a serialization error and must be retried. Neither is free, and knowing which one your engine uses tells you whether to expect blocking or retries.
Finding the blocking chain
When a workload stalls, the catalog tells you who holds what and who is waiting. Reading it correctly converts a vague "the database is slow" into a specific "session 418 holds an exclusive page lock from a bulk update and sixty sessions are queued behind it".
-- Who is blocked, by whom, and for how long
SELECT r.session_id AS blocked_session,
r.blocking_session_id,
r.wait_type,
r.wait_time AS wait_ms,
r.wait_resource,
t.text AS blocked_statement
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.blocking_session_id <> 0
AND r.session_id <> @@SPID
ORDER BY r.wait_time DESC;
-- What the blocking session itself is running
SELECT s.session_id,
s.status,
s.login_name,
s.host_name,
s.open_transaction_count,
t.text
FROM sys.dm_exec_sessions s
LEFT JOIN sys.dm_exec_requests r ON r.session_id = s.session_id
LEFT JOIN sys.dm_exec_sql_text(r.sql_handle) t
WHERE s.session_id = 418;
Then check whether the blocker is idle in an open transaction, which is the single most common cause of long blocking. A session that issued an update, kept its connection open, and went to lunch holds exclusive locks indefinitely while every other writer queues. Connection-pool settings that fail to close transactions, and interactive sessions that leave transactions open between statements, produce this pattern at scale.
Deadlocks: two lock orders, one victim
A deadlock occurs when two transactions each hold a lock the other needs. The engine detects the cycle through a wait-for graph, picks a victim by cost or age, rolls it back, and lets the other proceed. The victim's application sees an error that must be retried, which means your error handling determines whether a deadlock is a transient blip or a support ticket.
-- 1: two sessions, opposite orders, classic cycle
-- session A
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
-- session B
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 200 WHERE account_id = 2;
-- session A now requests account 2, session B requests account 1: deadlock
-- 2: break the cycle with a consistent access order and a bounded retry
CREATE OR REPLACE PROCEDURE transfer(from_id bigint, to_id bigint, amount numeric)
LANGUAGE plpgsql
AS $$
DECLARE
attempt int := 0;
BEGIN
LOOP
BEGIN
-- Always touch the lower key first: every session agrees on order
PERFORM 1 FROM accounts WHERE account_id = LEAST(from_id, to_id) FOR UPDATE;
PERFORM 1 FROM accounts WHERE account_id = GREATEST(from_id, to_id) FOR UPDATE;
UPDATE accounts SET balance = balance - amount WHERE account_id = from_id;
UPDATE accounts SET balance = balance + amount WHERE account_id = to_id;
INSERT INTO ledger(from_id, to_id, amount, posted_at)
VALUES (from_id, to_id, amount, now());
COMMIT;
EXIT;
EXCEPTION WHEN serialization_failure OR deadlock_detected THEN
attempt := attempt + 1;
IF attempt >= 5 THEN RAISE; END IF;
PERFORM pg_sleep(random() * 0.2);
END;
END LOOP;
END;
$$;
Three habits remove most deadlocks. Order access consistently, so no transaction ever waits on a key a later transaction already holds. Keep transactions short, so the window in which two locks are held simultaneously shrinks. And retry with jitter on deadlock errors, because even a well-ordered system can deadlock when bulk operations and point updates mix.
Optimistic patterns that avoid holding locks
Pessimistic concurrency takes the lock and pays for it in blocking. Optimistic concurrency assumes conflicts are rare and detects them at the end instead: read the version, do the work, then attempt to write only if the version is unchanged.
-- Optimistic update guarded by a version column
UPDATE products
SET price = 49.99,
version = version + 1,
updated_at = now()
WHERE product_id = 1234
AND version = 7; -- the value read at the start of the workflow
-- Rows affected = 0 means someone else changed it first: reload and retry
The pattern scales because readers never block writers and writers never block readers, but it moves the cost into application logic: every write path must handle a zero-row outcome, reload, and recompute. It is the wrong choice for long analytical transactions that would fail repeatedly, and the right choice for user-facing writes where a session may think for seconds between read and save.
A related technique is to reduce lock duration by moving work out of the transaction: write an intent row, commit, perform the expensive computation, then commit the result in a second short transaction. The lock window shrinks from minutes to milliseconds at the cost of an intermediate state that readers must tolerate.
Designing for high concurrency
Concurrency limits are usually set by three things: how long each transaction holds locks, how much work happens inside the transaction, and how contended the hottest rows are. A hot row â a single counter, a global sequence, a "current batch" marker â serialises everything that touches it, and no isolation level fixes that.
Replace contended single rows with alternatives that spread the load: shard counters by bucket and sum them at read time, use an allocation scheme that hands out ranges of ids, or append events and aggregate later rather than incrementing in place. Short statements, small result sets, and indexes that avoid sort operations all shorten lock hold times indirectly by shortening execution.
Finally, set a lock timeout appropriate to the workload. Without one, a queued transaction waits indefinitely, holds its own resources, and contributes to the pile-up. With one, it fails fast, surfaces in monitoring, and retries â which is almost always the better outcome for an interactive system.
â ī¸Idle transactions are silent blockers
A session that opens a transaction and then does nothing holds exclusive locks until it closes. Monitor open transaction age and set an idle-in-transaction timeout; this single setting eliminates a disproportionate share of production blocking incidents.
Common Mistakes
Running everything at the highest isolation level out of caution
Fix: Start at read committed and raise only for the specific statement that needs the guarantee
Performing long computations inside an open transaction
Fix: Move the computation out, keep transactions to a handful of fast statements, and use optimistic version checks
Ignoring zero-row outcomes from optimistic updates
Fix: Handle the conflict explicitly: reload, recompute, retry, and surface persistent conflicts
Treating deadlocks as errors rather than as a retryable condition
Fix: Retry with jitter after ordering access consistently, and alert if the retry rate climbs
Best Practices
- Order every multi-row access path by the same key to eliminate lock-order cycles
- Monitor lock wait time and open transaction age as first-class database metrics
- Keep transactions short and let the engine keep row-level granularity rather than escalating
- Use snapshot or optimistic patterns for read-heavy paths so readers never block writers
- Set lock and idle-in-transaction timeouts so stalls fail fast instead of piling up
Interview Questions
Q1: What is the difference between a lock wait and a deadlock?
A lock wait queues behind an existing holder and resolves when it commits; a deadlock is a cycle where each session holds what the other needs, so the engine aborts a victim.
Q2: Why does read committed still allow non-repeatable reads?
Because shared locks are released as soon as the row is read, so another transaction may update it before your transaction finishes.
Q3: How do you find the session causing blocking?
Query the execution requests view for blocking_session_id, then inspect that session's current statement and open transaction count.
Q4: When is optimistic concurrency the wrong choice?
When conflicts are frequent or transactions are long, because repeated retries cost more than simply taking the lock up front.
Key Takeaways
- Locks serve physical integrity and read consistency; only the second is optional
- Isolation levels are a menu of permitted anomalies, each with a locking price
- Blocking is diagnosable from the catalog: holder, victim, wait resource, and open transaction age
- Deadlocks are prevented by consistent access order, short transactions, and jittered retries
- Optimistic version checks trade blocking for conflict handling, which suits user-facing writes