| Lesson 8 |
Monitoring the data cache |
| Objective |
Monitor the SQL Server data cache using sys.dm_os_buffer_descriptors. |
Monitor the SQL Server Data Cache with sys.dm_os_buffer_descriptors
dbcc buffer is not deprecated in the formal sense
sp_lock, covered a few lessons ago, is deprecated: a documented, supported command scheduled for removal.
dbcc buffer was never in Microsoft's official DBCC documentation at all, in any version. It is one of a handful of undocumented internal commands, alongside others like
dbcc pss, that circulated through books and forums rather than official support channels, because it happened to work and people found it useful for inspecting the buffer pool. Its syntax, for recognition only, looked like this:
dbcc buffer [(dbname|db_id [,object_name|objectid [,number of pages [ ,display option]]] )]
It may still execute on a current instance, undocumented commands often do, but Microsoft gives no guarantee it keeps working, documents no supported syntax for it, and has never recommended it for production use. This lesson replaces it entirely with
sys.dm_os_buffer_descriptors, a fully documented DMV that answers the same questions with more precision.
This is the second lesson in a row to make this kind of change. The previous lesson corrected
dbcc memusage and
dbcc proccache along the same lines, and the pattern is not a coincidence: this part of the course was originally written around SQL Server's internal, undocumented command set from an era when DMVs did not yet exist as an alternative. Every one of those commands has since been overtaken by a documented, supported DMV that does the same job better, and this lesson's objective was rewritten specifically to reflect that rather than teach a command Microsoft never stood behind in the first place.
sys.dm_os_buffer_descriptors: Cache Usage by Database
The previous lesson introduced
sys.dm_os_buffer_descriptors briefly, as the modern replacement for the also-undocumented
dbcc memusage. This lesson treats it as the primary tool for data cache monitoring in its own right, starting with the single most common question: how much cache is each database using?
SELECT DB_NAME(database_id) AS database_name,
COUNT(*) * 8 / 1024.0 AS cached_mb
FROM sys.dm_os_buffer_descriptors
WHERE database_id <> 32767
GROUP BY database_id
ORDER BY cached_mb DESC;
Database ID 32767 is the internal Resource database and is usually excluded from this kind of report, since it is not something application workload is actually competing for cache space with.
Running this on a typical multi-database instance tends to produce a result dominated by whichever database handles the most active workload, with smaller or rarely queried databases showing only a few megabytes of cached pages, often cold data left over from a backup verification or an ad hoc report rather than anything currently relevant. A database that should be lightly used showing up near the top of this list is itself worth investigating, the same way an unexpected spike in
sp_monitor's connection count would be.
Which Tables and Indexes Are Using the Cache
Joined against the catalog views, the same DMV identifies specific hot tables and indexes rather than just a database-level total:
SELECT OBJECT_NAME(p.object_id) AS table_name, i.name AS index_name,
COUNT(*) * 8 / 1024.0 AS cached_mb
FROM sys.dm_os_buffer_descriptors AS bd
JOIN sys.allocation_units AS au ON bd.allocation_unit_id = au.allocation_unit_id
JOIN sys.partitions AS p ON au.container_id = p.hobt_id
JOIN sys.indexes AS i ON p.object_id = i.object_id AND p.index_id = i.index_id
WHERE bd.database_id = DB_ID()
GROUP BY p.object_id, i.name
ORDER BY cached_mb DESC;
A table or index sitting unexpectedly high on this list is worth a second look: it may simply be large and frequently queried, which is fine, or it may be evicting other, more important data from a cache that is smaller than the workload actually needs.
This is also a genuinely useful complement to the object-level buffer query the previous lesson introduced for
dbcc memusage's replacement. That earlier query counted buffers per table; this one adds the index dimension on top, which matters because a single table with several indexes can have most of its cached pages belong to an index nobody actually queries against, rather than the table's own data pages or the index that actually serves the workload's reads.
How Cache Memory Is Distributed by Page Type
A different cut of the same DMV shows how cache memory splits across page types rather than across tables, which is useful for a quick sanity check on where memory is actually going:
SELECT page_type, COUNT(*) AS page_count,
COUNT(*) * 8 / 1024.0 AS cache_mb
FROM sys.dm_os_buffer_descriptors
GROUP BY page_type
ORDER BY cache_mb DESC;
On a healthy, well-indexed workload, data and index pages should dominate this list. A surprisingly large share spent on allocation-related page types (IAM, PFS, or GAM pages, for instance) relative to actual data can point toward excessive file growth and fragmentation rather than genuine workload demand, since those page types exist to track space allocation rather than to hold rows, and a database with a great many small allocations spread across many files tends to need proportionally more of them.
Finding Dirty Pages
A dirty page is one modified in memory but not yet written to disk.
is_modified flags exactly that, which is useful when investigating checkpoint behavior or an unexpectedly long recovery:
SELECT DB_NAME(database_id) AS database_name,
COUNT(*) AS dirty_pages
FROM sys.dm_os_buffer_descriptors
WHERE is_modified = 1
GROUP BY database_id
ORDER BY dirty_pages DESC;
A database carrying an unusually large number of dirty pages for an extended period means more work for the next checkpoint and, in the event of an unplanned restart, a longer recovery, since every dirty page represents a change that still has to be written out or replayed before the database comes back online consistent. SQL Server's own automatic checkpoint behavior is generally tuned to keep recovery time within a target window on its own, so a persistently high dirty page count across repeated checks is more often a sign of a sustained, heavy write workload than a misconfiguration, but it is still worth knowing about before an unplanned restart turns it into an unexpectedly long outage rather than a quick one.
Cache Hit Ratio
For the classic buffer cache hit ratio figure,
sys.dm_os_performance_counters, covered two lessons ago, still exposes it directly:
SELECT counter_name, cntr_value
FROM sys.dm_os_performance_counters
WHERE object_name LIKE '%Buffer Manager%'
AND counter_name IN ('Buffer cache hit ratio', 'Buffer cache hit ratio base');
On a modern instance with a reasonably sized buffer pool, this ratio is typically well above 95%, often into the high 90s, simply because memory is large relative to many working sets. That makes a single snapshot reading less informative than the trend: a ratio that holds steady near its usual level is unremarkable, while one that drops noticeably from its own baseline is a more reliable signal of memory pressure than comparing against a fixed, one-size-fits-all threshold. An instance that normally sits at 99.5% dropping to 97% over a week is a more meaningful signal, on most workloads, than another instance that has sat at 92% consistently for months without incident; the second number looks worse in isolation but tells you less, because it has no baseline departure to actually point at.
Buffer cache hit ratio base is worth a specific note: it is not a percentage itself but the denominator the ratio is calculated against, and the two counters are meant to be read together rather than
Buffer cache hit ratio base being mistaken for a second, separate metric.
Inspecting a Specific Page
Once
sys.dm_os_buffer_descriptors identifies which page to look at,
DBCC PAGE, still documented, unlike
dbcc buffer, inspects its actual contents:
DBCC TRACEON (3604);
DBCC PAGE ('database_name', 1, 12345, 3);
DBCC TRACEON (3604) is required first so the output returns to the query window instead of only the error log. The four arguments are the database name, the file ID, the page ID, and a print option: print option 3, used above, returns both the page header and the interpreted row contents, which is usually the most useful level of detail for a monitoring investigation rather than a raw byte-level dump.
The page header section of the output includes fields like
m_pageId,
m_type (confirming the page type matches what
sys.dm_os_buffer_descriptors reported), and
m_slotCnt, the number of rows stored on that page. The two tools divide the work cleanly:
sys.dm_os_buffer_descriptors finds which page belongs to which object and whether it is cached and dirty, while
DBCC PAGE shows what is actually stored on that page once it has been identified. Reaching for
DBCC PAGE directly without first narrowing down a page of interest through the DMV is rarely productive outside of very small test databases, since there is no practical way to guess a meaningful page ID without it.
A Note on MRU and LRU
The legacy version of this lesson described
dbcc buffer[1] as returning the most recently used page first, or least recently used if a negative page count was passed.
sys.dm_os_buffer_descriptors has no equivalent column; it does not expose recency-of-access ordering. The buffer pool's eviction behavior, loosely, older and less-used pages are more likely to be evicted first, is still a real and useful concept, but it is not something this DMV, or any other documented tool, lets you query directly page by page. Where the old command offered a specific, orderable view into recency, the modern approach trades that away in exchange for everything else covered in this lesson: reliable syntax, catalog-view joins, and a guarantee Microsoft will not quietly change the output format in a future release.
This is worth stating plainly rather than papering over: the modern replacement is not a strict superset of what the old command could do. It is better for nearly every practical monitoring purpose covered in this lesson, database-level and object-level cache usage, dirty pages, page type distribution, and it is supported in a way the old command never was, but a narrow use case built specifically around observing recency order is genuinely not reproducible through documented means. Anyone who actually depended on that specific behavior, as opposed to the general idea of cache usage, is the rare exception this lesson's otherwise clean replacement does not fully cover.
Memory Pressure and the Broader Picture
The data cache is only one consumer of SQL Server's overall memory, and sys.dm_os_buffer_descriptors only reports on that one consumer. For the broader question of what else memory is being spent on, plan cache, lock memory, connection overhead, and more, sys.dm_os_memory_clerks, introduced two lessons ago as part of the dbcc memusage replacement, remains the right tool: it breaks memory down by clerk type across the whole instance, not just the buffer pool. Windows Performance Monitor, covered in this module's first lesson, adds Page Life Expectancy as a single, widely used headline number for buffer pool memory pressure specifically: a page's average time in cache before being evicted, with a sharp, sustained drop a classic sign that the buffer pool is under more pressure than the physical memory allocated to it can comfortably absorb.
None of these tools conflicts with the others. sys.dm_os_buffer_descriptors answers where the data cache's pages actually are; sys.dm_os_memory_clerks answers how memory is split across SQL Server's internal consumers generally; Page Life Expectancy answers how much pressure the buffer pool specifically is under as a single trending number. A thorough investigation into a memory-related symptom typically touches all three rather than stopping at the first one that returns a result.
Choosing Between sys.dm_os_buffer_descriptors and the Rest of This Module
sys.dm_os_buffer_descriptors answers questions about memory and cache specifically: what is cached, how much, and whether it is dirty. It does not answer the session-level and lock-level questions earlier lessons in this module covered, and it is a different kind of tool entirely from sp_monitor's instance-wide pulse or DBCC CHECKDB's integrity check. When a symptom looks like memory pressure specifically, a declining cache hit ratio, a database's working set clearly exceeding available cache, this DMV is the right place to look; when the symptom is blocking, a specific slow query, or a suspected corruption, the tools from earlier lessons remain the right ones instead.
A worked scenario pulls several of these together. Suppose sp_monitor's io_busy percentage has crept upward over a week of daily checks, with nothing obviously wrong in Activity Monitor and no blocking in sys.dm_tran_locks. The next reasonable step is exactly what this lesson covers: check the cache hit ratio trend first, then the per-database and per-object breakdown from sys.dm_os_buffer_descriptors to see whether one database or one table's working set has grown past what the cache can comfortably hold. A falling hit ratio alongside rising I/O busy time, with one database's cached megabytes climbing steadily across checks, points toward a cache sized for yesterday's data volume rather than today's, a very different conclusion than blocking or a missing index would lead to, and one none of the earlier lessons' tools would have surfaced on their own.
Building This Into a Routine
Cache monitoring fits naturally alongside the instance-wide checks this module has already built into a routine: a periodic look at the cache hit ratio trend and the per-database cache breakdown is a reasonable companion to sp_monitor's own periodic check, both answering a version of "is this instance under resource pressure." Unlike DBCC CHECKDB, there is no need to schedule these queries during a maintenance window; sys.dm_os_buffer_descriptors is a lightweight, read-only view and can be queried at any time without meaningfully affecting the workload it is reporting on.
The same logging pattern covered in the previous lesson, an Agent job inserting results into a table on a schedule, applies just as well here. Logging the per-database cache totals and the hit ratio counters every few minutes turns a series of one-off snapshots into a trend line, which is exactly what the worked scenario above actually needed: not a single reading, but confirmation that a number had been moving in one direction over days, something no single sys.dm_os_buffer_descriptors query, by itself, can show.
Put together, this lesson's tools cover the data cache from three angles: where the memory is going right now (the database and object breakdowns), whether that is actually a problem (the hit ratio trend and Page Life Expectancy), and what to do once a specific page needs closer inspection (DBCC PAGE). None of that was available through dbcc buffer in any documented, reliable form; it only looked that way because the undocumented command happened to answer a narrower version of the same questions, for those who knew it existed and were willing to accept the lack of any support behind it.
[1]Most recently used (MRU): the in-memory data page that was the last page to be accessed.
Least recently used (LRU): the in-memory data page that has gone the longest time without being accessed.
