dataiotech Labs
Back to Performance Guide
[Oracle]RUNBOOKOracle 19c / 21c / 23ai22 minSenior DBA / SRE

[Oracle] RUNBOOK: Lock Diagnosis — Enqueue and Row Lock in 5 Minutes

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In Oracle this appears a bit differently than in other engines: With `enq: TX - row lock contention` waiting, `V$LOCK` and `V$SESSION` chains. In this guide you will learn how to recognize a lock problem in Oracle, how to find blocking and blocked sessions in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the Oracle leg of the Performance Pillar and the whole Performance Pillar.

Production Incident Scenario

Time is 14:07. The application team writes: Pages do not open, but database CPU usage is 15%. Disk is healthy, memory is enough, no slow query. Everything looks normal but nothing works. The DBA looks at `V$SESSION` and sees the truth: 40 sessions look active but all are in `enq: TX - row lock contention` waiting. So 40 queries are not working, they are waiting. All of them wait for one transaction. That transaction has been open for 2 hours, contains an `UPDATE`, its owner went to lunch. One open transaction locked the whole system. This runbook shows what to do at that moment.

Summary

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In Oracle this appears a bit differently than in other engines: With enq: TX - row lock contention waiting, V$LOCK and V$SESSION chains. In this guide you will learn how to recognize a lock problem in Oracle, how to find blocking and blocked sessions in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the Oracle leg of the Performance Pillar and the whole Performance Pillar.

Scenario

Time is 14:07. The application team writes: Pages do not open, but database CPU usage is 15%. Disk is healthy, memory is enough, no slow query. Everything looks normal but nothing works. The DBA looks at V$SESSION and sees the truth: 40 sessions look active but all are in enq: TX - row lock contention waiting. So 40 queries are not working, they are waiting. All of them wait for one transaction. That transaction has been open for 2 hours, contains an UPDATE, its owner went to lunch. One open transaction locked the whole system. This runbook shows what to do at that moment.

Concept: What Is a Lock, Why Does It Exist?

A lock is the mechanism the database uses to protect consistency. If two people update the same row at the same time, one must wait. Otherwise data corrupts. So a lock is not a bad thing. When used correctly, a lock protects the system.

The problem is a lock lasting longer than necessary. A short lock is normal, a long lock is a disaster.

Most common lock types in Oracle:

  • •TX — Transaction Lock: Row lock. If a transaction updates a row, it locks that row. Another transaction cannot update that row but can read it. Because in Oracle, reading does not wait for a lock. Reading reads the old version. This is Oracle's biggest difference.
  • •TM — Table Lock: Table lock. If a transaction does DML on a table, it takes a TM lock on the table. It prevents dropping the table.
  • •UL — User Lock: User lock. Application-level lock taken with DBMS_LOCK.
  • •TX — ITL Waiting: Interested Transaction List. If there is not enough ITL slot in a block, a new transaction waits. Related to INITRANS and MAXTRANS settings.
  • •Enqueue: In Oracle, locks are managed as enqueues. Enqueue is a queued lock request. enq: TX waiting means waiting in the TX enqueue queue.

There are 3 root causes of lock problems:

  1. 1Long transaction: As long as the transaction stays open, the lock stays open. If there is an HTTP call, sleep, user waiting inside the transaction, the lock lasts for hours.
  2. 2Wrong access order: If two transactions access the same tables in different order, deadlock occurs.
  3. 3Too many locked rows: An unindexed UPDATE locks 1 million rows instead of 1 row. Everyone waits.

Step 1: Is the System Locked? Understand in 60 Seconds

First check if anyone is waiting.

sql
SELECT event AS wait_event, COUNT(*) AS cnt, AVG(wait_time_micro / 1000000) AS avg_wait_sec, MAX(wait_time_micro / 1000000) AS max_wait_sec FROM v$session WHERE status = 'ACTIVE' AND type = 'USER' GROUP BY event ORDER BY cnt DESC;

▸How to Interpret the Output?

  • •If there is no enq: TX - row lock contention, you have no lock problem. Look elsewhere.
  • •If enq: TX count is low and short-lived, it is normal. Every system has momentary locks.
  • •If enq: TX count is over 10 and increasing, a lock crisis has started.
  • •If enq: TX count is over 30, you are already in crisis. Go to Step 2 immediately.

Interpret wait events:

WaitMeaning
enq: TX - row lock contentionWaiting for row lock, write waiting
enq: TM - contentionWaiting for table lock, DDL or DML conflict
enq: TX - allocate ITL entryWaiting for ITL slot, block full
enq: TX - index contentionIndex block contention, heavy inserts
buffer busy waitsBlock density, many accesses to same block

If you see enq: TM - contention, someone is changing table structure or using LOCK TABLE.

Step 2: Who Blocks Whom? Find the Blocking Chain

This is the main query of this runbook. It shows the chain between blocking and blocked.

sql
SELECT s.sid AS blocked_sid, s.serial# AS blocked_serial, s.username AS blocked_user, s.event AS wait_event, s.wait_time_micro / 1000000 AS wait_sec, s.blocking_session AS blocking_sid, bs.username AS blocking_user, bs.status AS blocking_status, SUBSTR(s.sql_text, 1, 120) AS blocked_query, SUBSTR(bs.sql_text, 1, 120) AS blocking_query FROM v$session s JOIN v$session bs ON bs.sid = s.blocking_session WHERE s.blocking_session IS NOT NULL AND s.type = 'USER' ORDER BY s.wait_time_micro DESC;

▸How to Read the Output?

The table tells you this:

  • •blocked_sid: Waiting session. Innocent, just waiting its turn.
  • •blocking_sid: Session holding the lock. Usually the real culprit.
  • •blocking_query: What the locking query is.

Most of the time when you look at the table you see 20 rows but blocking_sid is always the same. So 20 sessions wait for one session. If you solve that one session, 20 sessions are saved at once.

▸Find the Root Blocker — Head of the Chain

Sometimes the chain is long. A waits for B, B waits for C, C waits for D. The root blocker is D. Without finding D, the chain does not resolve.

sql
-- Find the root blocker: blocking_session = NULL but waited by others SELECT s.sid, s.serial#, s.username, s.status, s.event, s.sql_id, SUBSTR(s.sql_text, 1, 120) AS query_text FROM v$session s WHERE s.sid IN ( SELECT DISTINCT blocking_session FROM v$session WHERE blocking_session IS NOT NULL ) AND s.blocking_session IS NULL AND s.type = 'USER';

▸Look at Lock Details

Which table, which lock mode is held?

sql
SELECT l.sid AS session_id, l.type AS lock_type, l.lmode AS lock_mode, l.request AS requested_mode, l.block AS is_blocking, o.object_name AS table_name, o.object_type AS object_type FROM v$lock l JOIN dba_objects o ON o.object_id = l.id1 WHERE l.sid > 50 ORDER BY l.sid;

Look at lmode values:

  • •0: No lock.
  • •2: Row Share (RS).
  • •3: Row Exclusive (RX). DML operation.
  • •4: Share (S).
  • •5: Share Row Exclusive (SRX).
  • •6: Exclusive (X). Strongest lock.

If you see lmode = 6 and block = 1, that session blocks everyone.

Step 3: Which Table and Which Lock Type?

Check which table, which mode the lock is held in.

sql
SELECT o.object_name AS table_name, l.type AS lock_type, l.lmode AS lock_mode, COUNT(*) AS cnt FROM v$lock l JOIN dba_objects o ON o.object_id = l.id1 WHERE l.sid > 50 GROUP BY o.object_name, l.type, l.lmode ORDER BY cnt DESC;

▸Understand Lock Modes

TypeMeaningDanger
TX RowRow lockLow, normal write
TM TableTable lockMedium, DDL blocking
UL UserApplication lockMedium, application design
ITLBlock ITL slotMedium, INITRANS setting
EnqueueQueue lockDanger grows as queue grows

If you see enq: TX - allocate ITL entry, the problem is not lock duration, it is block design. INITRANS value may be low. Increase INITRANS when rebuilding the table.

sql
-- Check INITRANS SELECT table_name, ini_trans, max_trans FROM user_tables WHERE table_name = 'ORDERS';

Step 4: Decide — 3 Options

In a lock crisis you have 3 options. Which one you choose depends on what the blocking query is.

▸Option A: Wait — Safest Option

If the blocking query has been running for less than 10 seconds and is a normal operation, wait. Because the query will finish, the lock will release, the queue will empty. Intervention can make it worse.

Waiting rule: If the blocking query has been running for less than 2 minutes and shows progress, wait. Do not kill in panic.

▸Option B: Warn the Blocking Query Owner — Communicate with the App Team

If the blocking query has been running for more than 10 minutes and belongs to an application session, first notify the application team. Because if you kill that query, there may be a half-finished operation on the application side.

The sentence you say must be clear:

Blocking SID 123, Serial 45678, has been open for 42 minutes. Query: UPDATE orders SET status... 20 sessions wait for it. If it will not finish in 5 minutes, I will kill it.

Warning without numbers does not work. Say SID, Serial, duration, and waiting count.

▸Option C: Kill — Last Resort

If the blocking query has been running for more than 30 minutes, its owner is unreachable, and the system is at a standstill, you must kill it.

sql
-- First verify the session SELECT sid, serial#, username, machine, program, status, logon_time FROM v$session WHERE sid = 123 AND serial# = 45678; -- Then kill it, do not use IMMEDIATE, first try normal kill ALTER SYSTEM KILL SESSION '123,45678';

▸3 Rules When Killing

  1. 1Never kill in bulk. Kill 1 blocking session, not 20 waiting sessions. If you kill waiters, the blocker still stands and new waiters come.
  2. 2First verify SID and Serial. If you kill the wrong session, you kill an innocent report or backup. SID alone is not enough. Use it with Serial.
  3. 3Monitor after kill. After killing, verify locks released. If not, there is a second blocker in the chain. Also the killed transaction is rolled back. Rollback can take as long as the transaction itself.
sql
-- Monitor rollback progress SELECT sid, serial#, username, status, event FROM v$session WHERE sid = 123;

Step 5: Deadlock — Two Transactions Wait for Each Other

Deadlock is a special case of locking. Two transactions wait for each other, neither progresses. Oracle automatically detects deadlock and chooses one as victim.

sql
-- Deadlock error example: -- ORA-00060: deadlock detected while waiting for resource

To diagnose deadlock, there are 2 ways:

▸Way 1: Alert Log

sql
-- Check alert log file SELECT value FROM v$diag_info WHERE name = 'Diag Trace';

In the alert log, a trace file is generated for deadlock. The trace file shows which two transactions waited for each other, which SQLs ran, and which one was chosen as victim.

▸Way 2: Read the Trace File

In the trace file, look at the Deadlock graph section. It shows waiting and blocking sessions, lock types, and SQL IDs.

The root cause of deadlock is usually access order. If two transactions access the same tables in different order, deadlock occurs.

Example:

text
Transaction A: First Orders, then Customers Transaction B: First Customers, then Orders

Both wait for each other. Solution is to use the same order in all transactions. Always first Orders, then Customers. Order standard reduces deadlock by 90%.

Step 6: Prevent Recurrence — Permanent Solutions

You survived the crisis. Now take 5 permanent measures so it does not repeat.

▸1. Keep Transactions Short

Transactions must not contain:

  • •HTTP calls
  • •External API waiting
  • •User confirmation waiting
  • •Sleep, waiting, long loops
  • •File reading, email sending

A transaction should only do database work. Nothing else. Open the transaction, do the work, close it. A transaction longer than 3 seconds is suspicious. A transaction longer than 30 seconds requires an alarm.

▸2. Do Not Do Unindexed UPDATE

An unindexed UPDATE locks the whole table. Because Oracle scans the table to find which row to update and locks every row it scans.

sql
-- Bad: If customer_id is unindexed, the whole table is locked UPDATE orders SET status = 'Shipped' WHERE customer_id = 123; -- Good: First check the plan SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));

If plan output shows TABLE ACCESS FULL, that UPDATE will lock the table. First add the index, then do the UPDATE.

▸3. Use Oracle's Read Advantage

In Oracle, reading does not wait for a write lock. Reading reads the old version. This is different from other engines. So you can run report queries at the same time as write transactions. But a long transaction still holds old versions and bloats Undo. Read advantage is not an excuse for long transactions.

▸4. Lock Timeout and Application-Side Retry

In Oracle, lock wait time can be set at session level. On the application side, if a lock wait times out, put retry logic.

sql
-- DDL lock wait at session level ALTER SESSION SET ddl_lock_timeout = 10;

This setting prevents DDL operations from waiting forever. For DML locks, use timeout and retry logic on the application side.

▸5. Set an Access Order Standard

Rule for the whole team: Tables will always be accessed in the same order in transactions.

Example standard:

  1. 1First Customers
  2. 2Then Orders
  3. 3Then OrderItems
  4. 4Then Payments

This order will be the same in all code. Code accessing in a different order will be rejected in code review.

Verification: Did the Lock Release?

After intervention, run the same queries again:

sql
SELECT event AS wait_event, COUNT(*) AS cnt FROM v$session WHERE status = 'ACTIVE' AND type = 'USER' GROUP BY event ORDER BY cnt DESC;

Success criteria:

  • •Did enq: TX count return to 0 or normal?
  • •Did long transaction count drop?
  • •Did waiting sessions start working?
  • •Did application error rate return to normal?

If you cannot say yes to these questions, there is a second blocker in the chain. Go back to Step 2, find the new blocker.

7 Common Mistakes

First mistake: Killing waiting sessions. Waiters are innocent. Kill the blocker. If you kill waiters, the problem continues.

Second mistake: Judging a lock by its type. Not lock type, but duration is the problem. A 1-second table lock is normal. A 2-hour row lock is a disaster.

Third mistake: Making HTTP calls inside a transaction. A transaction is opened for database work. The outside world is not waited for.

Fourth mistake: Killing with SID and not using Serial#. You kill the wrong session.

Fifth mistake: Thinking deadlock is a database error. Deadlock is an application design error. Without fixing access order, deadlock does not end.

Sixth mistake: Doing unindexed UPDATE. An unindexed UPDATE locks the whole table. First check with the plan.

Seventh mistake: Thinking a lock problem is a memory or CPU problem. If the system stops while CPU is 15%, the first place to look is the lock screen. Look at waiting, not CPU.

Checklist

  • enq: TX count checked
  • Long transaction count and longest duration checked
  • Blocking and blocked sessions identified
  • Root blocker found
  • Lock type and table determined
  • Blocking query duration and owner verified
  • If shorter than 2 minutes, waited, not killed in panic
  • If long, application team notified
  • If needed, KILL SESSION used, SID + Serial verified first
  • After kill, locks released verified
  • Rollback progress monitored
  • If deadlock, access order checked
  • DDL_LOCK_TIMEOUT setting checked
  • If ITL waiting, INITRANS checked
  • Long transaction alarm set up
  • Access order standard shared with team
  • Root cause fixed in code

Conclusion

A lock is not the fault of the database. A lock is the mirror of transaction design. With short transactions, correct access order, no unindexed UPDATE, and timeout settings, lock crises can be almost completely prevented. After reading this article, when the system stops you will look not at CPU, but at waiting. You will find not the waiter, but the blocker. And you will not only solve the crisis, but prevent it from recurring.

Performance Pillar Completed — Oracle Leg and Whole Pillar

With this article, the Oracle leg of the Performance Pillar and the whole Performance Pillar are complete.

Completed Articles:

  • •Pillar Hub: Performance Guide
  • •[Universal] N+1, EXPLAIN ANALYZE, Connection Pool, Partitioning
  • •[PostgreSQL] pg_stat_statements, Vacuum, Index Selection, Memory Tuning, Lock Diagnosis
  • •[MySQL] Performance Schema, Buffer Pool + Redo Log, Purge + Undo, Lock Diagnosis
  • •[SQL Server] Query Store, Memory Tuning, Lock Diagnosis
  • •[Oracle] AWR + ASH, SGA / PGA Tuning, Lock Diagnosis

Total: Pillar + 18 Clusters

Next Phase:

  • •New Pillar: Backup & Recovery
  • •PostgreSQL: pgBackRest, PITR
  • •MySQL: XtraBackup, Binlog PITR
  • •SQL Server: Full / Differential / Log Backup, Point-in-Time Restore
  • •Oracle: RMAN, Flashback, Data Pump

Related Articles

  • •Pillar: Performance Guide — Performance & Query Optimization
  • •Cluster: [Oracle] Finding the 20 Most Expensive Queries with AWR
  • •Cluster: [Oracle] Memory Tuning — SGA and PGA
  • •Cluster: [PostgreSQL] Lock Diagnosis — pg_locks + pg_stat_activity in 5 Minutes
  • •Cluster: [MySQL] Lock Diagnosis — InnoDB Lock Waits
  • •Cluster: [SQL Server] Lock Diagnosis — Blocking and Deadlock
  • •Next Pillar: Backup & Recovery — Introduction
Operational Checklist

Verify each operational safety check before completing the task: