dataiotech Labs
Back to Performance Guide
[SQL Server]RUNBOOKSQL Server 2022 / 201924 minSenior DBA / SRE

[SQL Server] RUNBOOK: Memory Tuning — Buffer Pool and Memory Grant

What shared_buffers is in PostgreSQL, what InnoDB Buffer Pool is in MySQL, Buffer Pool is in SQL Server. But SQL Server has one difference: It does not leave memory to the OS, it manages it itself. Default setting is to use all memory. This looks good at first, but no room remains for the OS, the server swaps, the system slows down. In this guide you will learn how much memory to allocate to SQL Server, how the Buffer Pool works, how to diagnose Memory Grant pressure, how to choose MAXDOP and Cost Threshold correctly, and how to apply changes safely in production.

Production Incident Scenario

There is a server. 64 GB RAM, 16 CPUs. SQL Server installed with default settings. The application team says the system is slow. The DBA looks: SQL Server uses 62 GB memory. 2 GB remains for the OS. The OS constantly struggles for memory. Queries sometimes take 200 ms, sometimes 5000 ms. Inconsistent. Why? Because queries waiting for memory grants queue up. A query asks for memory for sorting and hash operations, but there is no memory. It waits. Other queries wait too. The problem is not the server, it is the memory limit. First we need to determine how much memory to allocate to SQL Server.

Summary

What shared_buffers is in PostgreSQL, what InnoDB Buffer Pool is in MySQL, Buffer Pool is in SQL Server. But SQL Server has one difference: It does not leave memory to the OS, it manages it itself. Default setting is to use all memory. This looks good at first, but no room remains for the OS, the server swaps, the system slows down. In this guide you will learn how much memory to allocate to SQL Server, how the Buffer Pool works, how to diagnose Memory Grant pressure, how to choose MAXDOP and Cost Threshold correctly, and how to apply changes safely in production.

Scenario

There is a server. 64 GB RAM, 16 CPUs. SQL Server installed with default settings. The application team says the system is slow. The DBA looks: SQL Server uses 62 GB memory. 2 GB remains for the OS. The OS constantly struggles for memory. Queries sometimes take 200 ms, sometimes 5000 ms. Inconsistent. Why? Because queries waiting for memory grants queue up. A query asks for memory for sorting and hash operations, but there is no memory. It waits. Other queries wait too. The problem is not the server, it is the memory limit. First we need to determine how much memory to allocate to SQL Server.

Concept: How Does SQL Server Manage Memory?

SQL Server uses memory in 3 main parts:

  • •Buffer Pool: Data and index cache. When you first read a table, it reads from disk and puts it into the Buffer Pool. When you read the same table a second time, it reads from memory instead of disk. The logic is the same as in PostgreSQL and MySQL.
  • •Memory Grant: Memory a query temporarily requests while running. Operations like sorting, Hash Join, Hash Aggregate ask for memory while running. When done, they return the memory.
  • •Other: Plan cache, per-connection memory, lock table, CLR, Columnstore, and other areas.

The difference from PostgreSQL and MySQL is this: SQL Server manages memory dynamically. If you set an upper limit with max server memory, SQL Server stays below that limit. If you do not set a limit, it tries to take all memory in the OS. So setting a limit is mandatory.

Step 0: Learn Current Settings and the Server

Before changing anything, note the current state.

sql
SELECT name, value, value_in_use, description FROM sys.configurations WHERE name IN ( 'max server memory (MB)', 'min server memory (MB)', 'max degree of parallelism', 'cost threshold for parallelism', 'optimize for ad hoc workloads' );

Also learn server info:

sql
SELECT physical_memory_kb / 1024 / 1024 AS total_ram_gb, virtual_memory_kb / 1024 / 1024 AS virtual_memory_gb, cpu_count AS cpu_count FROM sys.dm_os_sys_info;

Write these two side by side. For example:

  • •Total RAM: 64 GB
  • •CPU: 16 cores
  • •max server memory: 2147483647 MB (default, unlimited)
  • •max degree of parallelism: 0 (default, unlimited)
  • •cost threshold for parallelism: 5 (default, very low)

If you change settings without this table, you will not know what you fixed.

Step 1: Max Server Memory — The Most Important Setting

▸Starting Formula

text
max server memory = Total RAM - Memory Reserved for OS

Memory reserved for OS:

Total RAMReserve for OSRemaining for SQL Server
8 GB2 GB6 GB
16 GB4 GB12 GB
32 GB6 GB26 GB
64 GB8 GB56 GB
128 GB12 GB116 GB
256 GB16 GB240 GB

▸Why Must We Leave Room for the OS?

Because the OS also does work besides SQL Server. File system cache, backup, monitoring agents, antivirus, remote desktop, all need memory. If SQL Server takes all memory, the OS swaps. On a server that swaps, SQL Server runs slower than memory. Leaving room is mandatory.

Special case: If another application also runs on the server, subtract its memory too. For example, if IIS runs on the same server, reserve 8 GB for IIS, then calculate for SQL Server.

▸Change Step

sql
-- First set the upper limit EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'max server memory (MB)', 57344; -- 56 GB RECONFIGURE; EXEC sp_configure 'min server memory (MB)', 8192; -- 8 GB RECONFIGURE;

min server memory determines the minimum memory SQL Server will hold. 8 GB prevents cold starts. But do not make it too high. Because SQL Server will not release that memory.

RECONFIGURE is enough to make it permanent. No restart needed. But monitor for 24 hours after the change.

Step 2: Is the Buffer Pool Enough? Diagnosis

You understand whether the Buffer Pool is healthy with 3 metrics.

▸1. Page Life Expectancy (PLE)

PLE shows how long a page stays in the Buffer Pool. The longer a page stays, the better. Because there is no need to read from disk again.

sql
SELECT object_name, counter_name, cntr_value AS value FROM sys.dm_os_performance_counters WHERE object_name LIKE '%Buffer Manager%' AND counter_name IN ('Page life expectancy', 'Buffer cache hit ratio', 'Page reads/sec', 'Page writes/sec');

Interpretation:

  • •PLE over 300: Usually healthy.
  • •PLE 100 - 300: Warning, pressure may be starting.
  • •PLE under 100: Problem. Buffer Pool is small or queries read unnecessary data.

But do not decide by PLE alone. Because on a large server PLE is naturally high, on a small server it is low. Monitor PLE as a trend. If PLE was 1000 yesterday and is 50 today, there is a problem.

▸2. Buffer Cache Hit Ratio

sql
SELECT cntr_value AS hit_ratio FROM sys.dm_os_performance_counters WHERE object_name LIKE '%Buffer Manager%' AND counter_name = 'Buffer cache hit ratio';

Interpretation:

  • •Over 99%: Excellent.
  • •97% - 99%: Good.
  • •95% - 97%: Warning.
  • •Below 95%: Problem.

But hit ratio can be high while queries still read unnecessary data. Evaluate together with Query Store.

▸3. Page Reads / Sec

If Page Reads is constantly high, data not found in the Buffer Pool is read from disk. Either Buffer Pool is small, or queries read unnecessary data.

Step 3: Memory Grant — Why Do Queries Wait?

Memory Grant is the most important memory concept specific to SQL Server. It can be thought of like work_mem in PostgreSQL and sort buffer in MySQL, but it is managed more centrally.

If a query will do sorting or Hash Join, it first asks for memory permission. SQL Server estimates how much memory to give the query and grants it. The query uses that memory while running, returns it when done.

▸Diagnosis: Is There Memory Grant Waiting?

sql
SELECT session_id, wait_type, wait_time / 1000.0 AS wait_sec, granted_memory_kb / 1024 AS granted_memory_mb, requested_memory_kb / 1024 AS requested_memory_mb, LEFT(text, 150) AS query_text FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) WHERE r.wait_type = 'RESOURCE_SEMAPHORE' ORDER BY r.wait_time DESC;

If you see RESOURCE_SEMAPHORE waiting, queries queued for memory grants. Reasons:

  • •A query asks for very large memory. For example it sorts 10 million rows with ORDER BY.
  • •Many queries ask for memory at the same time.
  • •max server memory is too low.

▸See Memory Grant Info

sql
SELECT TOP 20 LEFT(st.text, 150) AS query_text, qs.max_grant_kb / 1024 AS max_grant_mb, qs.max_used_grant_kb / 1024 AS max_used_mb, qs.max_ideal_grant_kb / 1024 AS ideal_grant_mb FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st WHERE qs.max_grant_kb > 0 ORDER BY qs.max_grant_kb DESC;

If max_grant_mb is much larger than max_used_mb, the query asks for more memory than needed. Statistics may be old or query design may be bad.

▸Solution: Fix the Query, Do Not Increase Memory

If there is Memory Grant waiting, the first solution is not to increase memory. The first solution is to fix the query.

  • •Select needed columns instead of SELECT *. Fewer columns, less memory.
  • •Use an index for sorting. Indexed sorting does not ask for memory grants.
  • •Reduce DISTINCT and GROUP BY usage. Both ask for memory.
  • •Split large sorts. Do not sort 10 million rows at once, use pagination.

If waiting still exists after the query is fixed, then review max server memory.

Step 4: MAXDOP and Cost Threshold — Parallelism Settings

▸What Is MAXDOP?

MAXDOP determines how many CPU cores a query can use at most. Default 0 means unlimited. On a 16-core server, one query can use all 16 cores. This is fast for a single query but slows other queries. Because one query occupies all CPU.

▸Starting Formula

Microsoft's recommendation:

  • •Under 8 cores: MAXDOP = core count
  • •Over 8 cores: MAXDOP = 8
  • •If there is a NUMA node: MAXDOP = core count per NUMA node

Example for a 16-core server:

sql
EXEC sp_configure 'max degree of parallelism', 8; RECONFIGURE;

▸What Is Cost Threshold for Parallelism?

It is the threshold that determines whether a query is worth running in parallel. Default 5 is very low. Even small queries try to run in parallel. Running in parallel brings coordination cost. For a small query, parallel is slower than serial.

Recommended starting point:

sql
EXEC sp_configure 'cost threshold for parallelism', 50; RECONFIGURE;

Value 50 means only really large queries run in parallel. Small queries run serially, finish faster, do not occupy CPU.

▸Diagnosis: Is There a Parallelism Problem?

sql
SELECT TOP 20 wait_type, waiting_tasks_count AS waiting_tasks, wait_time_ms / 1000.0 AS total_wait_sec FROM sys.dm_os_wait_stats WHERE wait_type IN ('CXPACKET', 'CXCONSUMER', 'SOS_SCHEDULER_YIELD') ORDER BY wait_time_ms DESC;

If CXPACKET waiting is very high, parallel queries wait for each other. Lower MAXDOP or increase Cost Threshold.

Step 5: Full Example — For a 64 GB Server

sql
-- Memory EXEC sp_configure 'max server memory (MB)', 57344; -- 56 GB EXEC sp_configure 'min server memory (MB)', 8192; -- 8 GB -- Parallelism EXEC sp_configure 'max degree of parallelism', 8; EXEC sp_configure 'cost threshold for parallelism', 50; -- Other EXEC sp_configure 'optimize for ad hoc workloads', 1; RECONFIGURE;

▸For a 16 GB Server

sql
EXEC sp_configure 'max server memory (MB)', 12288; -- 12 GB EXEC sp_configure 'min server memory (MB)', 2048; EXEC sp_configure 'max degree of parallelism', 4; EXEC sp_configure 'cost threshold for parallelism', 50; EXEC sp_configure 'optimize for ad hoc workloads', 1; RECONFIGURE;

▸For a 128 GB Server

sql
EXEC sp_configure 'max server memory (MB)', 118784; -- 116 GB EXEC sp_configure 'min server memory (MB)', 16384; EXEC sp_configure 'max degree of parallelism', 8; EXEC sp_configure 'cost threshold for parallelism', 50; EXEC sp_configure 'optimize for ad hoc workloads', 1; RECONFIGURE;

▸What Is optimize for ad hoc workloads?

sql
EXEC sp_configure 'optimize for ad hoc workloads', 1;

This setting makes single-use queries store a small placeholder in cache instead of the full plan. So Plan Cache does not bloat. Useful in systems with many ad hoc queries. Recommended to be on in production.

Verification: Did the Change Work?

Compare these 4 metrics before and after the change:

▸1. Page Life Expectancy

sql
SELECT cntr_value AS ple FROM sys.dm_os_performance_counters WHERE counter_name = 'Page life expectancy';

Target: Stable and over 300.

▸2. Buffer Cache Hit Ratio

Target: Over 97%, ideal over 99%.

▸3. Memory Grant Waiting

sql
SELECT COUNT(*) AS waiting_queries FROM sys.dm_exec_requests WHERE wait_type = 'RESOURCE_SEMAPHORE';

Target: 0 or not increasing.

▸4. Most Expensive Queries

sql
SELECT TOP 10 LEFT(qst.query_sql_text, 120), qrs.avg_duration / 1000.0 AS avg_time_ms FROM sys.query_store_runtime_stats qrs JOIN sys.query_store_plan qsp ON qsp.plan_id = qrs.plan_id JOIN sys.query_store_query qsq ON qsq.query_id = qsp.query_id JOIN sys.query_store_query_text qst ON qst.query_text_id = qsq.query_text_id ORDER BY qrs.avg_duration DESC;

Target: Average and total time should drop.

▸Verification Schedule

  • •1 hour after change: PLE and Memory Grant waiting check
  • •24 hours after change: Most expensive queries and Buffer Cache Hit Ratio check
  • •7 days after change: Weekly trend comparison

A change is not accepted as permanent without 7 days of monitoring.

7 Common Mistakes

First mistake: Not setting max server memory. Default unlimited leaves no room for the OS.

Second mistake: Making the Buffer Pool 100%. No room remains for the OS, the system swaps.

Third mistake: Deciding by looking at PLE alone. PLE is monitored as a trend, not interpreted with a single value.

Fourth mistake: Trying to solve Memory Grant waiting by increasing memory. First fix the query.

Fifth mistake: Leaving MAXDOP at 0. One query occupies all CPU.

Sixth mistake: Leaving Cost Threshold at 5. Even small queries try to run in parallel.

Seventh mistake: Changing all settings at once. One change, one measurement.

Checklist

  • Total RAM, CPU, and other application memory noted
  • Current max server memory, MAXDOP, and Cost Threshold recorded
  • PLE and Buffer Cache Hit Ratio measured
  • Memory Grant waiting measured
  • max server memory set to RAM - OS share
  • min server memory set
  • MAXDOP set to 8
  • Cost Threshold set to 50
  • optimize for ad hoc workloads = 1 verified
  • PLE measured again after 1 hour
  • Most expensive queries measured again after 24 hours
  • Memory Grant waiting checked to be zero
  • Useless change reverted

Conclusion

In SQL Server, memory tuning is cheaper and more effective than scaling up the server. A correctly allocated 64 GB runs faster than a wrongly configured 128 GB. First measure, then change one setting, then measure again. If you do not break this loop, your memory settings will always fit your system's real load.

Next cluster: SQL Server Lock Diagnosis. Because after solving the memory problem, next is to diagnose lock waits that queue queries.

Related Articles

  • •Pillar: Performance Guide — Performance & Query Optimization
  • •Cluster: [SQL Server] Finding the 20 Most Expensive Queries with Query Store
  • •Cluster: [PostgreSQL] Memory Tuning — shared_buffers, work_mem, effective_cache_size
  • •Cluster: [MySQL] InnoDB Buffer Pool and Redo Log Tuning
  • •Next: [SQL Server] Lock Diagnosis — Blocking and Deadlock
Operational Checklist

Verify each operational safety check before completing the task: