SQL Server 2012: Monitoring Latches and Spinlocks
Latches and spinlocks are lightweight synchronization objects SQL Server uses to protect in-memory structures. You can't control them directly, but heavy contention on them limits throughput on busy servers. SQL Server 2012 exposes several ways to measure it.
Latches vs locks vs spinlocks
- Locks protect logical data (rows, pages) for the duration of transactions.
- Latches protect physical structures, such as a page in the buffer pool, for very short periods.
- Spinlocks protect internal data structures for even shorter periods; a waiting thread spins on the CPU instead of yielding.
Wait statistics: the starting point
SELECT wait_type, waiting_tasks_count, wait_time_ms
FROM sys.dm_os_wait_stats
WHERE wait_type LIKE 'PAGELATCH%' OR wait_type LIKE 'PAGEIOLATCH%' OR wait_type LIKE 'LATCH%'
ORDER BY wait_time_ms DESC;
- PAGEIOLATCH_* waits mean sessions wait for pages to be read from disk: an I/O or memory problem.
- PAGELATCH_* waits mean contention on pages already in memory, for example the last page of an index with an ever-increasing key, or allocation pages in tempdb.
- LATCH_* waits are non-buffer latches.
Which latch classes
SELECT latch_class, waiting_requests_count, wait_time_ms
FROM sys.dm_os_latch_stats
ORDER BY wait_time_ms DESC;
Classes such as ACCESS_METHODS_HOBT_VIRTUAL_ROOT or FGCB_ADD_REMOVE point to specific components.
Which pages: current waits
SELECT session_id, wait_type, resource_description
FROM sys.dm_os_waiting_tasks
WHERE wait_type LIKE 'PAGELATCH%';
resource_description shows db_id:file_id:page_id. Pages 1, 2 or 3 in tempdb files (PFS, GAM, SGAM) indicate tempdb allocation contention; adding equally sized tempdb data files is the usual fix.
Spinlocks
SELECT name, collisions, spins, spins_per_collision, backoffs
FROM sys.dm_os_spinlock_stats
ORDER BY spins DESC;
Compare two snapshots taken a few minutes apart under load; absolute values since startup are less useful. High backoffs on a particular spinlock indicate contention worth investigating, typically on systems with many cores.
Extended Events
For deeper analysis, capture sqlserver.latch_suspend_end or sqlos.spinlock_backoff events with an Extended Events session, ideally with call stacks, during a short reproducible test.
Typical fixes
- last-page insert contention: different key design, hash partitioning or (in SQL Server 2019+)
OPTIMIZE_FOR_SEQUENTIAL_KEY, - tempdb allocation contention: more tempdb files and trace flag 1118 in SQL Server 2012,
- I/O latches: faster storage or more memory.
Today's equivalent
The same DMVs exist in current versions. SQL Server 2016 and later apply many tempdb fixes by default, and SQL Server 2019 added memory-optimized tempdb metadata.