Wait Event Analysis

A session is always either using CPU or waiting for something. Splitting response time into these two shows where to fix. If I/O waits are large, reduce the amount read. If lock waits are large, look at transactions. If log write waits are large, look at commit frequency or the disk.

System-wide cumulative values are totals since the instance started, so to see a problem happening now, take two snapshots and look at the difference. Also exclude "idle" waits (waiting for the client, timers of background processes).

Oracle

Required privileges: SELECT on V$SYSTEM_EVENT, V$SESSION_EVENT, V$SYS_TIME_MODEL (SELECT_CATALOG_ROLE). ASH (V$ACTIVE_SESSION_HISTORY, DBA_HIST_ACTIVE_SESS_HISTORY) requires a Diagnostics Pack license.

CPU share of DB time

SELECT stat_name, ROUND(value / 1e6) AS seconds
FROM v$sys_time_model
WHERE stat_name IN ('DB time', 'DB CPU', 'sql execute elapsed time', 'parse time elapsed');

DB time is the sum of the time user sessions spent using CPU or waiting without being idle. Subtracting DB CPU gives the wait time.

Top system-wide waits

SELECT event, wait_class, total_waits,
       ROUND(time_waited_micro / 1e6) AS waited_sec,
       ROUND(time_waited_micro / NULLIF(total_waits, 0) / 1000, 2) AS avg_ms
FROM v$system_event
WHERE wait_class <> 'Idle'
ORDER BY time_waited_micro DESC
FETCH FIRST 15 ROWS ONLY;

Commonly seen events:

  • db file sequential read: reading one block at a time, as in index access. db file scattered read, direct path read: full scans.
  • log file sync: waiting for the redo write at commit. Commits are too frequent or the log disk is slow.
  • enq: TX - row lock contention: row lock wait (Checking locks and blocking).
  • latch: cache buffers chains, buffer busy waits: accesses concentrated on the same block (hot block).

Waits per session

-- What each session is doing right now
SELECT sid, username, sql_id, state, event, wait_class,
       wait_time_micro / 1000 AS wait_ms
FROM v$session
WHERE type = 'USER' AND status = 'ACTIVE';

-- Cumulative waits of one session
SELECT event, total_waits, ROUND(time_waited_micro / 1e6, 1) AS waited_sec
FROM v$session_event
WHERE sid = 123 AND wait_class <> 'Idle'
ORDER BY time_waited_micro DESC;

event is what the session is waiting for right now only when state is WAITING. With WAITED SHORT TIME or WAITED KNOWN TIME, the session is using CPU now, and event is what it last waited for.

Waits in a recent interval (ASH)

ASH samples active sessions every second. The sample count is roughly the number of seconds.

SELECT NVL(event, 'ON CPU') AS event, COUNT(*) AS samples,
       ROUND(100 * RATIO_TO_REPORT(COUNT(*)) OVER (), 1) AS pct
FROM v$active_session_history
WHERE sample_time > SYSTIMESTAMP - INTERVAL '15' MINUTE
GROUP BY NVL(event, 'ON CPU')
ORDER BY samples DESC
FETCH FIRST 15 ROWS ONLY;
  • Adding sql_id to the GROUP BY shows which SQL experienced that wait.
  • DBA_HIST_ACTIVE_SESS_HISTORY keeps only one sample per 10 seconds, so count each sample as about 10 seconds.
  • Generate a report with @?/rdbms/admin/ashrpt.sql. The "Top 10 Foreground Events by Total Wait Time" section of the AWR report answers the same question.

PostgreSQL

Required privileges: pg_read_all_stats to see the query text of other users' sessions. To reset statistics, superuser (or EXECUTE on the relevant function).

Current waits

PostgreSQL has no cumulative wait-time statistics. pg_stat_activity shows only what sessions are waiting for at this very moment.

SELECT COALESCE(wait_event_type, 'CPU') AS wait_event_type,
       COALESCE(wait_event, 'CPU') AS wait_event,
       COUNT(*) AS sessions
FROM pg_stat_activity
WHERE state = 'active'
  AND backend_type = 'client backend'
  AND pid <> pg_backend_pid()
GROUP BY 1, 2
ORDER BY sessions DESC;
  • An active session whose wait_event is NULL is treated as using CPU (it could also be an uninstrumented wait).
  • Main wait_event_type values: IO (file reads such as DataFileRead), Lock (row and table locks), LWLock (internal shared-memory locks, e.g. BufferMapping, WALWrite), Client (ClientRead; the client is not sending the next command).

Collecting samples to see proportions

A single instantaneous value is hard to judge from, so collect several snapshots. In psql, repeat with \watch.

CREATE TEMP TABLE wait_samples AS
SELECT now() AS ts, pid, wait_event_type, wait_event, query_id
FROM pg_stat_activity WHERE false;

INSERT INTO wait_samples
SELECT now(), pid, wait_event_type, wait_event, query_id   -- query_id: PostgreSQL 14+
FROM pg_stat_activity
WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid();
\watch 1

-- After stopping with Ctrl+C
SELECT COALESCE(wait_event, 'CPU') AS wait_event, COUNT(*) AS samples,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM wait_samples
GROUP BY 1
ORDER BY samples DESC;

Grouping by query_id and joining with pg_stat_statements shows which queries waited. To collect samples continuously, use an extension such as pg_wait_sampling (not a core feature).

I/O statistics (pg_stat_io, PostgreSQL 16+)

SELECT backend_type, object, context,
       reads, read_time, writes, write_time, extends, hits, evictions, fsyncs
FROM pg_stat_io
WHERE reads > 0 OR writes > 0
ORDER BY reads + writes DESC;
  • Read and write counts are given per backend type (client, autovacuum, checkpointer, background writer, and so on). The unit is blocks (the op_bytes column, usually 8KB).
  • read_time and write_time accumulate only when track_io_timing = on (in milliseconds).
  • If writes of client backend is high, shared buffers are too small and clients are writing dirty pages out themselves. It is normal for the checkpointer and background writer to do the writing.
  • In 15 and earlier, use blks_read, blks_hit, blk_read_time in pg_stat_database and pg_statio_user_tables instead.
SELECT pg_stat_reset_shared('io');   -- PostgreSQL 16+

WARNING This resets the instance-wide I/O statistics to zero. If a monitoring tool collects these values, its graphs will be interrupted.

SQL Server

Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+). To reset statistics, ALTER SERVER STATE.

Top system-wide waits

SELECT TOP (15) wait_type, waiting_tasks_count,
       wait_time_ms / 1000 AS wait_sec,
       signal_wait_time_ms / 1000 AS signal_sec,
       CAST(100.0 * wait_time_ms / SUM(wait_time_ms) OVER () AS decimal(5, 1)) AS pct,
       CAST(1.0 * wait_time_ms / NULLIF(waiting_tasks_count, 0) AS decimal(12, 2)) AS avg_ms
FROM sys.dm_os_wait_stats
WHERE wait_time_ms > 0
  AND wait_type NOT IN (
      'SLEEP_TASK', 'LAZYWRITER_SLEEP', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', 'WAITFOR',
      'XE_TIMER_EVENT', 'XE_DISPATCHER_WAIT', 'REQUEST_FOR_DEADLOCK_SEARCH',
      'CHECKPOINT_QUEUE', 'LOGMGR_QUEUE', 'DIRTY_PAGE_POLL', 'BROKER_TO_FLUSH',
      'BROKER_TASK_STOP', 'BROKER_EVENTHANDLER', 'BROKER_RECEIVE_WAITFOR',
      'SP_SERVER_DIAGNOSTICS_SLEEP', 'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
      'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP', 'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP',
      'FT_IFTS_SCHEDULER_IDLE_WAIT', 'SOS_WORK_DISPATCHER', 'ONDEMAND_TASK_QUEUE')
  AND wait_type NOT LIKE 'SLEEP_%'
ORDER BY wait_time_ms DESC;
  • The exclusion list covers the typical idle waits. Each version adds new waits, so if an unfamiliar name appears near the top, first check whether it is an idle wait.
  • signal_wait_time_ms is the time spent waiting for a CPU turn after getting what the task was waiting for. If it exceeds 20 to 25% of the total, CPU is short.

Commonly seen waits:

  • PAGEIOLATCH_SH, PAGEIOLATCH_EX: reading pages from data files. The amount read is large or the disk is slow.
  • WRITELOG: log write at commit.
  • LCK_M_*: lock waits (Checking locks and blocking).
  • CXPACKET, CXCONSUMER: waits between threads in parallel execution. CXCONSUMER (2016 SP2+, 2017 CU3+) can usually be ignored.
  • SOS_SCHEDULER_YIELD: sharing CPU. Some queries are using a lot of CPU.
  • ASYNC_NETWORK_IO: the client is fetching results slowly. The problem is on the application side rather than the DB.

Cumulative waits per session (2016+)

SELECT session_id, wait_type, waiting_tasks_count, wait_time_ms, signal_wait_time_ms
FROM sys.dm_exec_session_wait_stats
WHERE session_id = 57
ORDER BY wait_time_ms DESC;

These are values since the session connected. If a connection pool reuses the connection (sp_reset_connection), they return to 0. For what is being waited on now, use sys.dm_os_waiting_tasks or sys.dm_exec_requests.wait_type.

Waits per query (Query Store, 2017+)

SELECT TOP (20) p.query_id, ws.wait_category_desc,
       SUM(ws.total_query_wait_time_ms) AS wait_ms
FROM sys.query_store_wait_stats ws
JOIN sys.query_store_plan p ON p.plan_id = ws.plan_id
GROUP BY p.query_id, ws.wait_category_desc
ORDER BY wait_ms DESC;

Waits are grouped into categories (CPU, Buffer IO, Lock, Parallelism, and so on) rather than individual wait names. Query Store must be on, with WAIT_STATS_CAPTURE_MODE = ON (the default in 2017+).

Reset for interval comparison

DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

WARNING This clears the instance-wide cumulative wait statistics. If a monitoring tool draws graphs from the differences in these values, the values will be interrupted. Rather than clearing, it is better to save the values at two points in a table and subtract.