Checking Locks and Blocking

When a query suddenly hangs or response time grows while CPU and I/O sit idle, lock waits are the first suspect. All three databases have a column or function that shows whom a waiting session is waiting for. The key is to follow it up to the session at the front of the chain (the head blocker). The head blocker is usually not running; it is a session sitting idle with a transaction open.

Deadlocks do not last, because the database detects them and fails one side. Check them afterwards in logs or event records instead.

Oracle

Required privileges: SELECT on V$SESSION, V$LOCK, and DBA_OBJECTS (SELECT_CATALOG_ROLE).

Blocked and blocking sessions

SELECT s.sid, s.serial#, s.username, s.status, s.event,
       s.blocking_session, s.blocking_instance, s.final_blocking_session,
       s.wait_time_micro / 1e6 AS wait_sec, s.sql_id
FROM v$session s
WHERE s.blocking_session IS NOT NULL
ORDER BY s.wait_time_micro DESC;
  • blocking_session is the session directly blocking this one; final_blocking_session (11gR2+) is the session at the front of the chain.
  • An event of enq: TX - row lock contention means a row lock wait, and enq: TM - contention means a table lock wait. TM waits often occur when a foreign key column has no index.

Blocking chain as a tree

SELECT LPAD(' ', 2 * (LEVEL - 1)) || s.sid AS sid_tree,
       s.serial#, s.username, s.status, s.event, s.sql_id, s.last_call_et
FROM v$session s
WHERE s.blocking_session IS NOT NULL
   OR s.sid IN (SELECT blocking_session FROM v$session)
START WITH s.blocking_session IS NULL
CONNECT BY PRIOR s.sid = s.blocking_session;

The top row is the head blocker. If its status is INACTIVE and last_call_et is large, it is a session sitting idle without committing. To kill it, see Viewing and Killing Sessions.

Waited row and object

SELECT s.sid, o.owner, o.object_name, o.object_type,
       s.row_wait_file#, s.row_wait_block#, s.row_wait_row#,
       DBMS_ROWID.ROWID_CREATE(1, o.data_object_id, s.row_wait_file#,
                               s.row_wait_block#, s.row_wait_row#) AS waited_rowid
FROM v$session s
JOIN dba_objects o ON o.object_id = s.row_wait_obj#
WHERE s.blocking_session IS NOT NULL
  AND s.row_wait_obj# <> -1;

Run SELECT * FROM <table> WHERE ROWID = '...' with waited_rowid to see the contended row.

Locks held by sessions

SELECT l.sid, l.type, l.id1, l.id2, l.lmode, l.request, l.block, l.ctime,
       o.owner, o.object_name
FROM v$lock l
LEFT JOIN dba_objects o ON l.type = 'TM' AND o.object_id = l.id1
WHERE l.type IN ('TM', 'TX')
ORDER BY l.id1, l.request;
  • lmode is the mode held and request is the mode requested (0 means none). block = 1 means this lock is blocking someone. ctime is the number of seconds in that state.
  • To see only who holds DML locks on which table, joining V$LOCKED_OBJECT with DBA_OBJECTS is simpler.

Past blocking history (ASH)

Blocking that has already cleared can be seen in ASH. A Diagnostics Pack license is required.

SELECT sample_time, session_id, blocking_session, event, sql_id
FROM v$active_session_history
WHERE blocking_session IS NOT NULL
  AND sample_time > SYSTIMESTAMP - INTERVAL '30' MINUTE
ORDER BY sample_time;

ASH in memory usually covers an hour or two. For earlier periods, use DBA_HIST_ACTIVE_SESS_HISTORY (sampled every 10 seconds).

Checking deadlocks

When a deadlock occurs, one session's statement fails with ORA-00060, an entry is written to the alert log, and the details (sessions involved, SQL, lock graph) go to a trace file.

-- 12.2+: read the alert log with SQL
SELECT originating_timestamp, message_text
FROM v$diag_alert_ext
WHERE message_text LIKE '%ORA-00060%'
ORDER BY originating_timestamp DESC;

Find the trace file location with SELECT value FROM v$diag_info WHERE name = 'Diag Trace';. In the trace's Deadlock graph, look at the sessions and statements that waited on each other.

PostgreSQL

Required privileges: pg_read_all_stats to see other users' query text. Anyone can view pg_locks.

Blocked and blocking sessions

SELECT pid, usename, state, wait_event_type, wait_event,
       pg_blocking_pids(pid) AS blocked_by,
       now() - query_start AS waiting_for,
       left(query, 80) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
ORDER BY query_start;
  • pg_blocking_pids (9.6+) returns an array of the pids blocking that session. For lock waits, wait_event_type is Lock.
  • This function briefly takes the lock manager, so do not use it in monitoring that polls at short intervals.

Finding the head blocker

SELECT a.pid, a.usename, a.state, now() - a.xact_start AS xact_age,
       left(a.query, 80) AS last_query
FROM pg_stat_activity a
WHERE a.pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)
  AND cardinality(pg_blocking_pids(a.pid)) = 0;

These are sessions that block others but are not blocked themselves. If state is idle in transaction, the application has often forgotten to commit.

Waiting locks and target objects

SELECT l.pid, l.locktype, l.mode, l.granted,
       l.relation::regclass AS relation, l.transactionid, l.page, l.tuple,
       l.waitstart                                  -- PostgreSQL 14+
FROM pg_locks l
WHERE NOT l.granted
ORDER BY l.waitstart;
  • locktype = 'relation' means a table or index lock (DDL, LOCK TABLE, and so on).
  • A row lock wait usually appears as transactionid. It means waiting for the transaction that changed the row to finish; the row itself is not shown directly. If another session is already waiting for the same row first, a tuple lock also appears.

Logging lock waits

ALTER SYSTEM SET log_lock_waits = on;    -- logs waits longer than deadlock_timeout (default 1s)
SELECT pg_reload_conf();

The log records the lock waited on and the blocking pid, as in still waiting for ShareLock on transaction .... On the application side, prevent unbounded waits with SET lock_timeout = '5s';.

Checking deadlocks

SELECT datname, deadlocks, stats_reset
FROM pg_stat_database
WHERE datname = current_database();

deadlocks is a cumulative count. The details are in the server log, in the DETAIL under ERROR: deadlock detected, which lists each process's wait relationship and statement. Deadlock detection runs only after a lock has been waited on for deadlock_timeout.

SQL Server

Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+).

Blocked requests

SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time AS wait_ms,
       r.wait_resource, DB_NAME(r.database_id) AS db, r.command,
       SUBSTRING(t.text, r.statement_start_offset / 2 + 1,
                 (CASE r.statement_end_offset WHEN -1 THEN DATALENGTH(t.text)
                       ELSE r.statement_end_offset END - r.statement_start_offset) / 2 + 1) AS stmt
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.blocking_session_id <> 0
ORDER BY r.wait_time DESC;
  • For lock waits, wait_type starts with LCK_M_ (LCK_M_X, LCK_M_S, LCK_M_U, and so on).
  • wait_resource examples: KEY: 7:72057594045595648 (a1b2c3...), OBJECT: 7:245575913:0, PAGE: 7:1:2048.

Finding the head blocker

SELECT s.session_id, s.login_name, s.host_name, s.program_name, s.status,
       s.open_transaction_count, s.last_request_end_time, t.text AS last_sql
FROM sys.dm_exec_sessions s
JOIN sys.dm_exec_connections c ON c.session_id = s.session_id
OUTER APPLY sys.dm_exec_sql_text(c.most_recent_sql_handle) t
WHERE s.session_id IN (SELECT blocking_session_id FROM sys.dm_exec_requests WHERE blocking_session_id <> 0)
  AND s.session_id NOT IN (SELECT session_id FROM sys.dm_exec_requests WHERE blocking_session_id <> 0);

If status is sleeping and open_transaction_count > 0, the session is idle with a transaction open. last_sql is the last batch sent; the statement that took the lock may be an earlier one.

Waiting locks and target objects

SELECT l.request_session_id, l.resource_type, l.request_mode, l.request_status,
       DB_NAME(l.resource_database_id) AS db,
       CASE WHEN l.resource_type = 'OBJECT'
            THEN OBJECT_NAME(l.resource_associated_entity_id, l.resource_database_id)
            ELSE OBJECT_NAME(p.object_id) END AS object_name,
       l.resource_description
FROM sys.dm_tran_locks l
LEFT JOIN sys.partitions p ON p.hobt_id = l.resource_associated_entity_id
WHERE l.request_status = 'WAIT'
   OR l.request_session_id IN (SELECT blocking_session_id FROM sys.dm_exec_requests);
  • For OBJECT locks, resource_associated_entity_id is the object_id; for KEY, PAGE, and RID locks it is the hobt_id. sys.partitions shows only the current database, so run this in that database.
  • request_status: GRANT (held), WAIT (waiting), CONVERT (waiting to upgrade the mode).

Recording blocking automatically

EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'blocked process threshold (s)', 20; RECONFIGURE;

A blocked_process_report event is raised for every request blocked longer than 20 seconds. You must create an Extended Events (XE) session that captures this event for anything to be recorded.

WARNING This changes a server-wide setting. A value below 5 seconds makes the monitoring task run often and produces many events. To turn it off, set it back to 0.

Checking deadlocks

The system_health Extended Events session, which is on by default, records deadlock graphs (xml_deadlock_report).

SELECT CAST(event_data AS xml).value('(event/@timestamp)[1]', 'datetime2') AS utc_time,
       CAST(event_data AS xml).query('(event/data/value/deadlock)[1]') AS deadlock_graph
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)
WHERE object_name = 'xml_deadlock_report'
ORDER BY utc_time DESC;
  • Save deadlock_graph as an .xdl file to view it as a diagram in SSMS. victim-list is the side that failed, and process-list holds each session's statement.
  • system_health files have a size limit, so the oldest records are deleted first. Times are in UTC.