📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your SQL Server shows low CPU but many requests waiting on RESOURCE_SEMAPHORE. What is happening and what do you do?

Diagnosing memory grant starvation (RESOURCE_SEMAPHORE waits) when CPU is low, and fixing it at the query, server and Resource Governor level.

Senior Theory Advanced memory-grants performance query-store sql-server wait-stats

🎯 Key points

  • Waiting for workspace memory, not CPU
  • sys.dm_exec_query_memory_grants: grant_time NULL means waiting
  • Compare granted vs max_used memory to spot over-grants
  • Typical cause: inflated estimates and wide columns in sorts and hashes
  • Check max server memory and other memory clerks squeezing the buffer pool
  • Fix queries first; MAX_GRANT_PERCENT or Resource Governor as containment
  • Track it over time: wait stats, Query Store memory columns, memory grant feedback

⏱ 30-second answer

Queries are queued for workspace memory (for sorts and hashes), not CPU: other queries hold large grants and the semaphore has nothing left. I list sys.dm_exec_query_memory_grants to see who holds big grants and who is waiting (grant_time NULL), compare granted_memory_kb with max_used_memory_kb, and find the offenders in Query Store. Usually a few queries over-estimate rows or sort wide columns, so I fix those first. I also check that max server memory is sensible, and use MAX_GRANT_PERCENT or Resource Governor (SQL Server, Azure SQL Managed Instance) as containment, not the cure.

🗣 Full answer (senior)

What it means. Sort, hash join, hash aggregate and some other operators need workspace memory. Before a query starts it asks for a grant sized from the optimiser's row and row-size estimates. Grants come from a resource semaphore (by default up to roughly 75% of target memory for all grants together, and 25% per query per Resource Governor workload group). When outstanding grants use it up, new queries wait on RESOURCE_SEMAPHORE before they run a single row. CPU looks idle because nothing is executing — it is all queued.

How I diagnose it.

  1. Confirm the wait: sys.dm_os_wait_stats (delta over a few minutes) or sys.dm_exec_requests showing RESOURCE_SEMAPHORE.
  2. sys.dm_exec_query_memory_grants: rows with grant_time IS NULL are waiting; sort the granted ones by granted_memory_kb. A query granted 6 GB that uses 200 MB (max_used_memory_kb) is the problem.
  3. sys.dm_exec_query_resource_semaphores shows the total, available and waiter counts.
  4. Query Store (max_query_max_used_memory, and the plan's MemoryGrantInfo) shows which queries have been asking for big grants historically.
  5. Check the server side: is max server memory set (and not too low), and is something else (a large plan cache, columnstore, another instance) shrinking the memory available for grants?

How I fix it.

  • Queries first: fix bad cardinality estimates (stale statistics, table variables, multi-statement TVFs, non-SARGable predicates), stop sorting nvarchar(max) or wide rows (sort only keys, then join back), and add indexes that supply order so the sort disappears.
  • Memory grant feedback (batch mode since SQL Server 2017, row mode since 2019 at compat 150; SQL Server 2022 adds percentile-based adjustment and persists feedback in Query Store) shrinks repeated over-grants automatically — check it isn't disabled or oscillating.
  • Containment: OPTION (MAX_GRANT_PERCENT = 10) on a known offender, or a Resource Governor workload group with a lower REQUEST_MAX_MEMORY_GRANT_PERCENT for reporting logins. On Azure SQL Database you can't configure Resource Governor, so query fixes and hints are the tools.
  • Capacity: only after the above — more memory or a larger tier.

Production example. A reporting endpoint in an ASP.NET Core API ran a query that sorted on a wide JSON column. Under month-end load, eight concurrent calls each grabbed ~3 GB and every OLTP query that needed a small hash join waited. Projecting only keys in the sort and adding an index that provided the order cut the grant to ~40 MB and the waits disappeared.

🔍 What the interviewer is checking

Checks that the candidate can diagnose memory grant starvation under concurrency rather than guess at CPU or blocking.

Green flags: names workspace memory and the semaphore; uses sys.dm_exec_query_memory_grants and granted vs used; links grants to cardinality and row-size estimates; fixes queries before hardware; mentions max server memory, Resource Governor and memory grant feedback.

Red flags: thinks it is a lock wait; recommends more CPU or more memory first; can't say where the grant size comes from; puts hints everywhere.

📚 Learn in depth

How a grant is sized. The optimiser computes required memory (the minimum to start, e.g. enough for sort buffers) and ideal memory (enough to do all sorts and hashes in memory) from estimated rows × estimated row size. Variable-length columns are estimated at half their declared size, so nvarchar(4000) costs 4,000 bytes per row whether the data is 10 characters or not. The request is capped by the workload group's REQUEST_MAX_MEMORY_GRANT_PERCENT (default 25%).

The semaphore. There are two resource semaphores per resource pool: a small one for cheap queries (under ~5 MB grant, low cost) and a regular one. Waiters are queued by cost; small queries can be stuck behind a big queued query. request_time_out_sec in Resource Governor (or the default derived from query cost, up to 24 times the estimated cost in seconds) eventually fails a waiter with error 8645.

Granted vs used. A grant is reserved up front and held until the operators that need it finish. Over-grants waste memory others need; under-grants spill to tempdb (Sort Warnings / Hash Warnings, spilled_pages in actual plans). Both are estimation problems.

Memory grant feedback. After execution, SQL Server compares the grant with actual use; if the query wasted more than 50% of a large grant, or spilled, the cached plan's grant is adjusted next time. SQL Server 2022 adds percentile-based adjustment (to stop oscillation for parameter-sensitive queries) and persists feedback in Query Store so it survives plan eviction and restarts.

💻 Code

-- Who holds grants and who is waiting
SELECT  mg.session_id,
        mg.requested_memory_kb,
        mg.granted_memory_kb,
        mg.max_used_memory_kb,
        mg.grant_time,          -- NULL = still waiting
        mg.wait_time_ms,
        mg.dop,
        t.text
FROM sys.dm_exec_query_memory_grants AS mg
CROSS APPLY sys.dm_exec_sql_text(mg.sql_handle) AS t
ORDER BY mg.granted_memory_kb DESC;

-- Semaphore capacity and waiters
SELECT resource_semaphore_id, pool_id, target_memory_kb,
       available_memory_kb, granted_memory_kb, grantee_count, waiter_count
FROM sys.dm_exec_query_resource_semaphores;

-- Historical offenders from Query Store (memory columns are 8 KB pages)
SELECT TOP (20) q.query_id,
       MAX(rs.max_query_max_used_memory) * 8 AS max_used_kb,
       SUM(rs.count_executions) AS executions
FROM sys.query_store_runtime_stats AS rs
JOIN sys.query_store_plan  AS p ON p.plan_id  = rs.plan_id
JOIN sys.query_store_query AS q ON q.query_id = p.query_id
GROUP BY q.query_id
ORDER BY max_used_kb DESC;

-- Containment on a known offender
SELECT OrderId, CustomerId, Total
FROM dbo.Orders
ORDER BY CreatedAt
OPTION (MAX_GRANT_PERCENT = 10);

⚠ Common mistakes

  • Reading low CPU as "the server is fine" and scaling the app tier instead.
  • Adding memory before finding the two or three queries with inflated grants.
  • Leaving max server memory at the default on a shared box, so the OS and SQL Server fight and grants shrink.
  • Declaring columns as nvarchar(max) or nvarchar(4000) "to be safe" — row-size estimates, and so grants, balloon.
  • Putting MAX_GRANT_PERCENT on everything, which turns over-grants into tempdb spills.
  • Using MIN_GRANT_PERCENT or MAXDOP changes without measuring granted vs used.

🏛 Senior insight: trade-offs

The senior framing is: this is a queueing problem caused by estimation. The grant is reserved up front, so the cost of a bad estimate is paid by everyone else, not just the bad query. I'd fix the estimate or the shape (sort fewer, narrower rows) first, use memory grant feedback and hints as containment, and only then talk capacity. I'd also separate workloads — reporting on a readable secondary or a Resource Governor pool — because mixing reporting and OLTP on one semaphore is how a month-end report takes down checkout. And I'd add an alert on RESOURCE_SEMAPHORE wait time so we see it before customers do.

🛠 Real-world problems: how you handle them

Month-end report starves OLTP of workspace memory
Situation
An Azure SQL Managed Instance in Australia East backs an ordering API. At month-end, finance runs a revenue report endpoint several times in parallel.
Signals
API p95 latency jumps from 80 ms to 9 s; database CPU is around 20%; Application Insights shows SQL dependency calls slow but not failing; wait stats are dominated by RESOURCE_SEMAPHORE.
Investigation
sys.dm_exec_query_memory_grants shows eight sessions from the reporting login each granted ~3 GB with max_used around 150 MB, and dozens of OLTP sessions with grant_time NULL. The plan shows a Sort on a wide nvarchar(max) column with an estimated row size of several KB and estimates 50 times the actual rows because of a table variable.
Resolution
Immediately: kill the duplicate report sessions and add OPTION (MAX_GRANT_PERCENT = 5) to the report query. Long term: replace the table variable with a temp table, sort only the key columns and join back for the wide column, add an index that supplies the order, and put the reporting login in a Resource Governor workload group with REQUEST_MAX_MEMORY_GRANT_PERCENT = 10.
Prevention
Alert on RESOURCE_SEMAPHORE wait time per minute, review Query Store top memory consumers weekly, and route reporting to a readable secondary.

How to tell it (STAR)

**Situation:** At [company], our ordering API slowed to [p95 figure] every month-end while database CPU sat at [percentage]. **Task:** I was asked to find out why. **Action:** I checked wait stats, saw RESOURCE_SEMAPHORE, and used sys.dm_exec_query_memory_grants to find the reporting query holding [size] grants it barely used. I contained it with MAX_GRANT_PERCENT, then fixed the estimate and the wide sort, and moved reporting into its own workload group. **Result:** Grants dropped to [size], API latency at month-end stayed at [figure], and we added an alert so we would see it early.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me