SQL Server Wait Statistics Report: dm_os_wait_stats

This T-SQL script reads sys.dm_os_wait_stats, removes the wait types that only record idle background threads, and ranks what is left by its share of the remaining wait time. The top rows show which resource the instance has spent the most time waiting for since the engine started or the counters were last reset.

Purpose and Overview

A slow instance rarely announces which resource is the problem, but its wait statistics usually name it. Every time a worker thread cannot continue because it needs a lock, a page from disk, a memory grant, a CPU slot or an acknowledgment from the client, SQL Server adds the elapsed time to a counter for that wait type. Sorting those counters answers the first diagnostic question, where the time goes, before any query-level tracing starts.

The raw view is noisy. Checkpoint, log writer, lazy writer, Extended Events, Service Broker and full-text threads spend most of their lives waiting for work, and on a quiet instance their totals dwarf everything else. A report that does not remove them ranks idle threads above the waits that cost users time. This script keeps an explicit list of those idle wait types in a CTE, drops them, and expresses each remaining wait type as a percentage of the filtered total.

Three details of how the view behaves shape how the report is read:

  • It counts completed waits. The view shows the time for waits that have finished. A task that is stuck on a lock right now adds no time to the totals until its wait ends; sys.dm_os_waiting_tasks lists the waits in progress.
  • It is cumulative. The counters are not persisted. They start at zero when the database engine starts and grow until the next restart or manual reset, so a percentage is a share of everything since then, not of the last hour.
  • Time includes the wait for a CPU. wait_time_ms includes signal_wait_time_ms, the gap between the thread being signaled and the thread running again.

Code Breakdown

The script has three CTEs and a final SELECT. It needs the VIEW SERVER STATE permission, or VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later.

 1WITH idle_waits AS (
 2    SELECT wait_type
 3    FROM (VALUES
 4        ('BROKER_EVENTHANDLER'), ('BROKER_RECEIVE_WAITFOR'), ('BROKER_TASK_STOP'),
 5        ('BROKER_TO_FLUSH'), ('BROKER_TRANSMITTER'),
 6        ('CHECKPOINT_QUEUE'), ('CLR_AUTO_EVENT'), ('CLR_MANUAL_EVENT'),
 7        ('CXCONSUMER'), ('DBMIRROR_EVENTS_QUEUE'), ('DIRTY_PAGE_POLL'),
 8        ('DISPATCHER_QUEUE_SEMAPHORE'), ('FT_IFTS_SCHEDULER_IDLE_WAIT'),
 9        ('HADR_WORK_QUEUE'), ('KSOURCE_WAKEUP'), ('LAZYWRITER_SLEEP'),
10        ('LOGMGR_QUEUE'), ('ONDEMAND_TASK_QUEUE'),
11        ('QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP'),
12        ('QDS_PERSIST_TASK_MAIN_LOOP_SLEEP'), ('REDO_THREAD_PENDING_WORK'),
13        ('REQUEST_FOR_DEADLOCK_SEARCH'), ('SERVER_IDLE_CHECK'),
14        ('SLEEP_DBSTARTUP'), ('SLEEP_DCOMSTARTUP'), ('SLEEP_MASTERDBREADY'),
15        ('SLEEP_MASTERMDREADY'), ('SLEEP_MASTERUPGRADED'), ('SLEEP_MSDBSTARTUP'),
16        ('SLEEP_SYSTEMTASK'), ('SLEEP_TASK'), ('SLEEP_TEMPDBSTARTUP'),
17        ('SNI_HTTP_ACCEPT'), ('SOS_WORK_DISPATCHER'), ('SP_SERVER_DIAGNOSTICS_SLEEP'),
18        ('SQLTRACE_BUFFER_FLUSH'), ('SQLTRACE_INCREMENTAL_FLUSH_SLEEP'),
19        ('SQLTRACE_WAIT_ENTRIES'), ('WAITFOR'), ('WAIT_XTP_OFFLINE_CKPT_NEW_LOG'),
20        ('XE_DISPATCHER_JOIN'), ('XE_DISPATCHER_WAIT'), ('XE_TIMER_EVENT')
21    ) AS v(wait_type)
22),
23filtered_waits AS (
24    SELECT ws.wait_type,
25           ws.waiting_tasks_count,
26           ws.wait_time_ms,
27           ws.max_wait_time_ms,
28           ws.signal_wait_time_ms
29    FROM sys.dm_os_wait_stats AS ws
30    WHERE ws.waiting_tasks_count > 0
31      AND ws.wait_time_ms > 0
32      AND ws.wait_type NOT IN (SELECT wait_type FROM idle_waits)
33),
34totals AS (
35    SELECT SUM(wait_time_ms) AS total_wait_ms
36    FROM filtered_waits
37)
38SELECT TOP (20)
39    fw.wait_type,
40    fw.waiting_tasks_count,
41    fw.wait_time_ms,
42    fw.signal_wait_time_ms,
43    fw.wait_time_ms - fw.signal_wait_time_ms                      AS resource_wait_time_ms,
44    fw.max_wait_time_ms,
45    CAST(fw.wait_time_ms * 1.0 / fw.waiting_tasks_count AS DECIMAL(18, 2)) AS avg_wait_ms,
46    CAST(100.0 * fw.wait_time_ms / t.total_wait_ms AS DECIMAL(5, 2))       AS pct_of_total_waits
47FROM filtered_waits AS fw
48CROSS JOIN totals AS t
49ORDER BY fw.wait_time_ms DESC;

Idle Wait List

The idle_waits CTE holds wait types that mark a background thread sleeping or waiting for work: the checkpoint, log writer and lazy writer queues, the deadlock monitor's interval between searches, Extended Events dispatchers, SQL Trace queues, Service Broker and full-text schedulers, database startup sleeps and the availability group worker queue. WAITFOR is there because it records the WAITFOR statement that a session issued on purpose. CXCONSUMER is there because it is a normal part of parallel query execution.

The list is explicit rather than a set of LIKE 'HADR_%' or LIKE 'SLEEP_%' patterns. A prefix pattern would also hide waits that matter: HADR_SYNC_COMMIT, for example, is the time a synchronous-commit availability group spends sending the log, writing it and getting the acknowledgment from the secondary, which is a real cost of the configuration. The price of an explicit list is that an idle wait type missing from it will show up in the output. Look up any unfamiliar name in the wait types reference before acting on it; many entries there are marked internal use only and do not point to a tunable resource.

Filtering and Totals

filtered_waits removes the idle list and skips wait types that have never occurred (waiting_tasks_count = 0) or that have accumulated no time. totals sums wait_time_ms over what remains, so the percentage in the final result is relative to the filtered total, not to all waits on the instance. Adding a name to the idle list changes every percentage in the report.

Signal Time and Resource Time

signal_wait_time_ms is the time between the thread being signaled that its resource is available and the thread running. wait_time_ms - signal_wait_time_ms is the time spent waiting for the resource itself, shown as resource_wait_time_ms. A signaled thread does not run at once: it goes on the queue of runnable workers and waits for a quantum on the scheduler. Signal time is therefore time spent waiting for CPU after the resource was already available.

Average and Maximum Wait

avg_wait_ms divides total wait time by the number of waits, and waiting_tasks_count is incremented when each wait starts. A wait type with a modest share of total time but a very high average points to a few long stalls, while a large share with a tiny average points to a very frequent short wait. max_wait_time_ms gives the longest single completed wait for the type.

Key Benefits and Use Cases

  • Where-to-look-first answer. The top few rows name the resource class, such as disk reads, log flushes, locks, memory grants, parallelism, CPU or client speed, before any query is opened.
  • Idle noise removed. The explicit idle list keeps background sleeps from filling the top of the report.
  • Share of time, not raw counts. pct_of_total_waits makes the ranking comparable between instances and between snapshots.
  • CPU queuing visible. The signal and resource split separates waiting for a CPU from waiting for the thing the task asked for.
  • Cheap to run. The query reads a single dynamic management view and touches no user tables.
  • Baseline material. Saving the output before and after a change, such as a new index, a configuration change or a hardware move, gives a measurable comparison.

Performance Considerations

  • Cumulative since startup. The counters are cleared only by a restart or an explicit reset. On an instance that has run for months, last week's change disappears into the totals. SELECT sqlserver_start_time FROM sys.dm_os_sys_info; returns the last startup time so the window is known.
  • Completed waits only. A task blocked for an hour adds nothing to wait_time_ms until the wait ends, although waiting_tasks_count already counted it when the wait started, so avg_wait_ms is skewed low while the stall lasts. During an incident, check sys.dm_os_waiting_tasks for what is waiting now.
  • Instance-wide. The view aggregates every database and every session. sys.dm_exec_session_wait_stats gives similar numbers per session when the question is about one connection.
  • Reset needs more rights. DBCC SQLPERF ('sys.dm_os_wait_stats', CLEAR); zeroes the counters and requires the ALTER SERVER STATE permission. Everyone and every monitoring tool reading the view sees the reset, so clear it deliberately and rarely.
  • Wait names change with versions. Since SQL Server 2016 SP2 and 2017 CU3, CXPACKET covers only synchronizing the exchange iterator and producing rows, and threads consuming rows are tracked as CXCONSUMER. In SQL Server 2022 and later, exchange synchronization also moves to CXSYNC_PORT and CXSYNC_CONSUMER. Percentages from different versions are not directly comparable.
  • Rank is not diagnosis. The top wait type is where the time went, not proof of a defect. A busy server legitimately waits for the log, the disk and the client.

Practical Tips

  • Measure a window instead of a lifetime. Copy the counters into a temp table, wait, and subtract. Run it while the problem workload is active, and extend the exclusion list with the idle waits from the main script. Unlike a counter reset, it leaves the counters intact for everyone else.
 1SELECT wait_type, waiting_tasks_count, wait_time_ms, signal_wait_time_ms
 2INTO   #waits_start
 3FROM   sys.dm_os_wait_stats;
 4
 5WAITFOR DELAY '00:05:00';
 6
 7SELECT TOP (10)
 8       e.wait_type,
 9       e.waiting_tasks_count - s.waiting_tasks_count AS waits_in_window,
10       e.wait_time_ms        - s.wait_time_ms        AS wait_ms_in_window
11FROM   sys.dm_os_wait_stats AS e
12INNER JOIN #waits_start AS s ON s.wait_type = e.wait_type
13WHERE  e.wait_time_ms - s.wait_time_ms > 0
14  AND  e.wait_type NOT IN ('WAITFOR', 'SLEEP_TASK', 'LAZYWRITER_SLEEP', 'XE_TIMER_EVENT')
15ORDER BY wait_ms_in_window DESC;
16
17DROP TABLE #waits_start;
  • Save the report on a schedule. Insert the top rows into a history table from a SQL Agent job, with the capture time and sqlserver_start_time, so a restart is visible as a break in the series.
  • See what is waiting now. SELECT TOP (20) session_id, wait_type, wait_duration_ms, blocking_session_id, resource_description FROM sys.dm_os_waiting_tasks ORDER BY wait_duration_ms DESC; shows the live waits and who is blocking.
  • Read the common ones in context. PAGEIOLATCH_SH and PAGEIOLATCH_EX mean a task waits for a buffer that is being read from or written to disk, and long waits can mean a disk subsystem problem. WRITELOG is the wait for a log flush to complete, commonly at commit or checkpoint, and long waits come from log disk latency, I/O that cannot keep up, or a large number of commits and rollbacks. LCK_M_* waits mean data contention between queries. ASYNC_NETWORK_IO means the server is waiting for the client to take the data it sent, and the client application is the first suspect. RESOURCE_SEMAPHORE means a query could not get its memory grant, and can end in error 8645. SOS_SCHEDULER_YIELD with acceptable query times can be ignored; with slow queries it points at scans and plan quality. THREADPOOL means tasks are waiting for a worker thread, often because batches are running long.
  • Parallelism waits. For CXPACKET, tune the query first; if the waiting is excessive and cannot be reduced that way, the cost threshold for parallelism and the maximum degree of parallelism are the settings to examine. Some parallelism waiting is a normal part of parallel execution, so a high CXPACKET count on its own is not a reason to change MAXDOP.
  • Keep the exclusion list short and reviewed. Every name added to idle_waits changes the percentages, so add a name only after reading what it means.

Conclusion

This report turns the cumulative wait counters into a ranked list with idle background threads removed, a signal and resource split, and each wait type's share of the remaining time. Start every performance investigation with it, take a windowed measurement when the totals are old, and then move to sys.dm_os_waiting_tasks or query-level tools for the resource it points to.

References

Posts in this series