Covers query memory grants: which operators need memory, how grants are sized from estimates and row width, spills to tempdb and their warnings, oversized grants and RESOURCE_SEMAPHORE waits, memory grant feedback (batch, row mode, percentile and persistence), and diagnosis with DMVs, Query Store and hints.
Operators like sort and hash match need workspace memory, and SQL Server reserves it as a memory grant before the query starts, sized from the estimated rows × estimated row width.
Memory grant feedback (row mode since 2019, percentile and persistence in 2022) adjusts grants on repeated executions. I diagnose with the actual plan's MemoryGrantInfo, sys.dm_exec_query_memory_grants and Query Store, then fix the cause: bad estimates, SELECT * with wide nvarchar(max) columns, or sorts an index could avoid. Hints are the last resort.
"Some operators can't stream: a sort has to see all its input, a hash join has to build a hash table. They need workspace memory, and SQL Server reserves it up front as a memory grant, at compile time based on estimates and at run time from what's available. The size comes from estimated rows times estimated row width, so it inherits every estimation error. Row width has a nasty twist: for variable-length columns the optimiser assumes they're half full, so
nvarchar(4000)counts as 4,000 bytes per row whatever is actually in it.When the grant is too small, the sort or hash writes to tempdb, a spill, and you see the warning in the actual plan with a spill level. That's often an order of magnitude slower. When it's too big, memory is reserved but unused, and under concurrency other queries wait on
RESOURCE_SEMAPHOREbefore they can even start, so the server looks idle on CPU but requests are slow. For example, at [company] a [search endpoint] usedSELECT *on a table with threenvarchar(max)columns and sorted the result. Each execution asked for about [1.5 GB]; at [20] concurrent requests the instance ran out of grant memory and requests queued for seconds. Selecting only the needed columns and adding an index that supplied the order dropped the grant to [a few MB] and the waits disappeared.Recent versions help. Memory grant feedback adjusts the grant for repeated executions of the same plan: batch mode since 2017, row mode since 2019, and in SQL Server 2022 it uses a percentile of recent usage and persists in Query Store so it survives eviction. The mistake I see is reaching for
MAX_GRANT_PERCENTor more memory first. Grants are a symptom: fix the estimate, the row width, or remove the sort, and the grant fixes itself."
| Under-granted | Over-granted | |
|---|---|---|
| Cause | Row estimate too low | Row estimate too high, wide declared columns |
| Symptom | Spill warnings, tempdb I/O, slow single query | RESOURCE_SEMAPHORE waits, queued queries, 'Excessive Grant' warning |
| Seen in | Actual plan, sort_warning / hash_spill_details XE, Query Store tempdb usage |
sys.dm_exec_query_memory_grants (grant_time NULL = waiting), wait stats |
| Fix | Fix estimate, update statistics, remove sort with index | Fix estimate, narrow columns, select fewer columns |
| Feature | Version / compat | Notes |
|---|---|---|
| Batch mode MGF | 2017 / 140 | Columnstore or batch mode queries |
| Row mode MGF | 2019 / 150 | All row mode queries |
| Percentile-based MGF | 2022 / 140+ | Uses recent history, avoids oscillation |
| Persistence in Query Store | 2022 | Feedback survives plan eviction |
Feedback can disable itself for a plan if usage keeps oscillating, and it only helps from the second execution onwards.
The search fix cut the grant from [1.5 GB] to [6 MB] per execution, RESOURCE_SEMAPHORE waits went from [thousands of seconds per hour] to zero, and p95 dropped from [4.2 s] to [180 ms] at the same concurrency.
Checks whether the candidate understands how estimates turn into memory and concurrency problems, and can diagnose both spills and grant waits.
Green flags
Red flags
streaming (no grant) blocking / memory-consuming (grant)
------------------- -----------------------------------
Index Seek / Scan Sort, Top N Sort (large N)
Nested Loops Hash Match (join, aggregate)
Stream Aggregate Exchange (parallelism buffers)
Compute Scalar Batch mode operators, columnstore inserts
For each memory-consuming operator: estimated input rows × estimated row size, plus overhead. The query's grant has a required amount (minimum to start) and an ideal/desired amount. SQL Server grants up to the desired amount, capped by the workload group's REQUEST_MAX_MEMORY_GRANT_PERCENT (25% default).
Row size uses declared types; for varchar(n)/nvarchar(n) it assumes half the declared length. So:
| Column | Declared | Assumed per row |
|---|---|---|
nvarchar(50) |
100 bytes | 50 bytes |
nvarchar(4000) |
8,000 bytes | 4,000 bytes |
nvarchar(max) |
LOB | estimated as 4,000 bytes (in-row portion) |
That's why oversizing columns 'just in case' inflates grants for every sort over them.
query ready -> request grant -> RESOURCE_SEMAPHORE
| available? yes -> execute
| no -> wait in queue (smallest-first heuristics, timeout)
v
error 8645 on timeout
sys.dm_exec_query_memory_grants shows requested_memory_kb, granted_memory_kb, used_memory_kb, max_used_memory_kb and grant_time (NULL while waiting).
A spill writes part of the sort runs or hash partitions to tempdb and reads them back. Spill level 1 is one extra pass; higher levels mean recursive partitioning. Actual plans show 'Operator used tempdb to spill data during execution with spill level N'. Query Store records avg_tempdb_space_used and max_tempdb_space_used (2017+) so you can find spilling queries historically.
After execution, if used memory was far below the grant (excessive) or the query spilled (insufficient), the cached plan's grant is adjusted for the next run. 2022's percentile mode looks at a history of executions rather than just the last one, reducing oscillation for parameter-sensitive queries, and persistence stores the adjustment in Query Store. Plans that keep flipping disable feedback (IsMemoryGrantFeedbackAdjusted = NoFeedbackDisabled in plan XML).
OPTION (MIN_GRANT_PERCENT = x, MAX_GRANT_PERCENT = y) per query (percent of the max grant).REQUEST_MAX_MEMORY_GRANT_PERCENT for reporting logins.nvarchar(4000) column that only holds 20 characters, then on the same data typed nvarchar(50), and compare MemoryGrantInfo in the actual plans.sys.dm_exec_query_memory_grants and RESOURCE_SEMAPHORE waits.IsMemoryGrantFeedbackAdjusted in the second plan.max_tempdb_space_used.Find queries waiting for grants, those with oversized grants, and those that spill.
-- Queries holding or waiting for workspace memory right now
SELECT mg.session_id, mg.requested_memory_kb, mg.granted_memory_kb,
mg.used_memory_kb, mg.max_used_memory_kb, mg.grant_time, mg.wait_time_ms,
t.text
FROM sys.dm_exec_query_memory_grants mg
CROSS APPLY sys.dm_exec_sql_text(mg.sql_handle) t
ORDER BY mg.requested_memory_kb DESC; -- grant_time NULL = queued on RESOURCE_SEMAPHORE
-- Historically: biggest grants and tempdb users from Query Store (values in 8 KB pages)
SELECT TOP (20) p.query_id,
MAX(rs.max_query_max_used_memory) * 8 / 1024 AS max_used_mb,
MAX(rs.max_tempdb_space_used) * 8 / 1024 AS max_tempdb_mb,
SUM(rs.count_executions) AS execs
FROM sys.query_store_runtime_stats rs
JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id
GROUP BY p.query_id
ORDER BY max_tempdb_mb DESC, max_used_mb DESC;
-- Before: SELECT * with wide columns and a sort -> huge grant
SELECT * FROM dbo.Tickets WHERE Status = 'Open' ORDER BY CreatedAt DESC;
-- After: only needed columns, and an index that supplies the order (no Sort, no grant)
CREATE INDEX IX_Tickets_Status_Created
ON dbo.Tickets (Status, CreatedAt DESC) INCLUDE (Subject, CustomerId);
SELECT TicketId, Subject, CustomerId, CreatedAt
FROM dbo.Tickets WHERE Status = 'Open' ORDER BY CreatedAt DESC;
-- Last resort for a reporting query you can't fix yet
SELECT CustomerId, SUM(Total) FROM dbo.Orders GROUP BY CustomerId
OPTION (MAX_GRANT_PERCENT = 5);
In EF Core, project to a DTO so wide columns never enter the sort:
namespace Support.Data;
using Microsoft.EntityFrameworkCore;
public sealed record OpenTicket(int TicketId, string Subject, int CustomerId, DateTime CreatedAt);
public sealed class OpenTicketsQuery(SupportDbContext db)
{
// Projecting avoids selecting Body/Notes (nvarchar(max)), which would inflate the grant
public Task<List<OpenTicket>> RunAsync(CancellationToken ct) =>
db.Tickets
.Where(t => t.Status == "Open")
.OrderByDescending(t => t.CreatedAt)
.Select(t => new OpenTicket(t.TicketId, t.Subject, t.CustomerId, t.CreatedAt))
.ToListAsync(ct);
}
nvarchar(4000) or nvarchar(max) 'to be safe'. Why it is wrong: Grants assume half the declared size, so sorts over them reserve huge memory. Instead: Size columns to the data.SELECT * (or EF Core entity queries) on tables with LOB columns, followed by ORDER BY. Why it is wrong: Wide rows go into the sort and inflate the grant. Instead: Project only needed columns.sys.dm_exec_query_memory_grants.MAX_GRANT_PERCENT everywhere. Why it is wrong: It can cause spills for queries that genuinely need memory. Instead: Use it narrowly after fixing estimates.Memory grants are where estimation errors become concurrency problems. A single over-granted report query can starve an OLTP workload without touching much CPU, which is why 'the server looks idle but everything is slow' should make you check RESOURCE_SEMAPHORE. The fixes are mostly design choices made long before the incident: column sizes, projections instead of entity queries, and indexes that supply order.
Modern feedback features reduce the damage for repeated queries, and Query Store's tempdb and memory columns make problems visible historically. I still treat hints and Resource Governor as containment, not cures.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| Fix estimate (stats, SARGable, types) | Spills or excessive grants from bad estimates | Low | Estimates already accurate |
| Narrow columns / project fewer | Wide declared or LOB columns in sorts | Schema or code change | — |
| Index supplying order | Frequent ORDER BY on large sets | Write cost | Rare queries |
MIN/MAX_GRANT_PERCENT |
Specific query, urgent | Can cause spills | Broad use |
| Resource Governor | Mixed reporting + OLTP on SQL Server | Admin complexity; not in Azure SQL DB | Single-workload databases |
Statistics describe the distribution of values in one or more columns: a density vector (how many distinct values) and a histogram of up to 200 steps on the leading column. The cardinality estimator combines them with its model assumptions to predict how many rows each operator returns, and every plan choice depends on that number.
Statistics are auto-created on indexes and filtered columns and auto-updated after enough modifications (since compat level 130, roughly SQRT(1000 × rows) for big tables). The CE version follows the database compatibility level.
Stale or sampled statistics show up as big estimated vs actual row gaps, nested loops over huge inputs and spills. The trade-off: fuller, more frequent updates give better plans but cost I/O and trigger recompiles.
An estimated plan is what the optimiser would do; an actual plan is the same plan plus runtime numbers: actual rows, number of executions, memory grant used and runtime warnings. Data flows right to left; thick arrows mean many rows.
The first thing I check is estimated vs actual rows on each operator: a big gap means a bad estimate, and almost every bad plan follows from one. Then I look for scans where I expected seeks, key lookups executed thousands of times, the join type (nested loops with a huge outer input is a red flag), and warnings such as CONVERT_IMPLICIT, spills and residual predicates.
Cost percentages are estimates too, so I confirm with logical reads from SET STATISTICS IO.
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.
How to tell it (STAR)
**S:** Our [support ticket search] slowed the whole application at around [20] concurrent users, yet CPU was only [30%]. **T:** I was asked to find out why the server looked idle but was slow. **A:** Wait stats showed RESOURCE_SEMAPHORE, and the memory grants DMV showed each search reserving about 1.5 GB but using under 20 MB. The plan sorted entire rows including three nvarchar(max) columns, so the optimiser sized the grant for very wide rows. I changed the query to project only the columns the list needed and added an index that supplied the sort order. **R:** Grants dropped to [a few MB], the memory waits disappeared, and search p95 went from [4.2 s] to [180 ms] at the same load.
Last updated 23 Nov 2026.