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

📚 Interview question

What is a memory grant in SQL Server? Explain how the grant is sized, what happens when it is too small (sort and hash spills to tempdb) or too large (RESOURCE_SEMAPHORE waits), how memory grant feedback works in recent versions, and how you diagnose and fix grant problems.

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.

Senior Theory Advanced intelligent-query-processing memory-grants query-performance spills sql-server tempdb

🎯 Key points

  • Sort, hash match and some exchange operators need workspace memory reserved before execution starts
  • Grant size comes from estimated rows × estimated row width, so stale or misleading statistics translate directly into wrong grants
  • Variable-length columns are assumed half full of their declared size, so oversized nvarchar columns inflate grants
  • Under-estimate -> spill to tempdb (Sort/Hash warnings, spill level), often an order of magnitude slower
  • Over-estimate -> memory wasted, fewer concurrent queries, RESOURCE_SEMAPHORE waits and 'Excessive Grant' warnings; max per query defaults to 25% of the workload group
  • Memory grant feedback: batch mode (2017), row mode (2019, compat 150), percentile-based and persisted in Query Store (2022)
  • Diagnose: actual plan MemoryGrantInfo, sys.dm_exec_query_memory_grants, Query Store max_query_max_used_memory and tempdb usage
  • Fix the estimate or row width first; MIN_GRANT_PERCENT / MAX_GRANT_PERCENT hints and Resource Governor are last resorts

⏱ 30-second answer

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.

  • Too small and the operator spills to tempdb: a warning triangle in the actual plan and often 10× slower.
  • Too large and memory sits idle while other queries queue on RESOURCE_SEMAPHORE.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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_SEMAPHORE before they can even start, so the server looks idle on CPU but requests are slow. For example, at [company] a [search endpoint] used SELECT * on a table with three nvarchar(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_PERCENT or more memory first. Grants are a symptom: fix the estimate, the row width, or remove the sort, and the grant fixes itself."


Too small vs too big

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

Memory grant feedback by version

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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands how estimates turn into memory and concurrency problems, and can diagnose both spills and grant waits.

Green flags

  • Names the memory-consuming operators and how grants are sized, including the half-declared-width rule.
  • Explains spills and RESOURCE_SEMAPHORE waits as the two failure modes.
  • Knows memory grant feedback and its versions.
  • Fixes estimates and row width before hints.

Red flags

  • 'Make tempdb faster' or 'add RAM' as the answer.
  • Has never heard of RESOURCE_SEMAPHORE.
  • Thinks grants are allocated as the query runs.

📚 Learn in depth

1. Which operators need memory

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

2. How the grant is sized

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.

3. The grant queue

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).

4. Spills

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.

5. Memory grant feedback internals

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).

6. Hints and governance

  • OPTION (MIN_GRANT_PERCENT = x, MAX_GRANT_PERCENT = y) per query (percent of the max grant).
  • Resource Governor workload groups on SQL Server (not in Azure SQL Database) can lower REQUEST_MAX_MEMORY_GRANT_PERCENT for reporting logins.
  • Both are blunt; fixing estimates is better.

Try it yourself

  1. Sort 1 million rows on an nvarchar(4000) column that only holds 20 characters, then on the same data typed nvarchar(50), and compare MemoryGrantInfo in the actual plans.
  2. Force a spill by updating statistics with a tiny sample on a skewed column, sort on it, and find the spill warning.
  3. Run 20 concurrent copies of a big-grant query (e.g. with SQLQueryStress) and watch sys.dm_exec_query_memory_grants and RESOURCE_SEMAPHORE waits.
  4. On compat 150+, run a spilling query twice and look for IsMemoryGrantFeedbackAdjusted in the second plan.
  5. Query Store: list queries by max_tempdb_space_used.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Treating spills as a tempdb problem. Why it is wrong: Faster tempdb only makes the spill less painful; the grant was wrong. Instead: Fix the row estimate or remove the sort or hash.
  • Mistake: Ignoring statistics when grants look wrong. Why it is wrong: The grant is calculated from estimated rows; after a bulk load or on an ascending key the estimate can be tiny, so the sort or hash spills on every execution. Instead: Compare estimated vs actual rows on the spilling operator and update statistics (in the load job for nightly imports).
  • Mistake: Declaring columns as 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.
  • Mistake: 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.
  • Mistake: Seeing low CPU and assuming the server is fine. Why it is wrong: Queries can be queued on RESOURCE_SEMAPHORE before running. Instead: Check wait stats and sys.dm_exec_query_memory_grants.
  • Mistake: Applying 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.
  • Mistake: Expecting memory grant feedback to fix the first run. Why it is wrong: It adjusts subsequent executions and may disable itself for oscillating queries. Instead: Fix estimates for infrequent queries.
  • Mistake: Adding RAM as the fix. Why it is wrong: Bigger memory raises the cap, so oversized grants grow too. Instead: Fix the queries first; add memory if the workload genuinely needs it.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says grants come from row estimates Why: Checks where estimates come from and how statistics go stale
    How to answer

    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.

  2. When: Candidate mentions spill warnings in the plan Why: Checks broader plan-reading skills
    How to answer

    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.

  3. When: Candidate mentions oversized grants Why: Checks diagnosis of grant starvation under concurrency
    How to 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.

🛠 Real-world problems: how you handle them

Search endpoint starves the server of grant memory
Situation
A [support ticket search] API on [SQL Server 2019, 64 GB] allowed sorting by date. The Tickets table had [Body, Notes and History] as nvarchar(max). At [20] concurrent searches the whole application slowed.
Signals
CPU at only [30%] while API p95 rose to [4.2 s]; wait stats dominated by RESOURCE_SEMAPHORE; occasional error 8645 (timeout waiting for memory resources); other OLTP queries also slow.
Investigation
`sys.dm_exec_query_memory_grants` showed each search requesting about [1.5 GB], granted [1.5 GB] but using [under 20 MB], with others queued (grant_time NULL). The plan showed `SELECT *` feeding a Sort on CreatedAt with an estimated row size of over [12 KB] from the LOB columns. Query Store confirmed the search query held the largest max_used memory and grant.
Resolution
Changed the EF Core query to project only the list columns, and added an index on (Status, CreatedAt DESC) INCLUDE (Subject, CustomerId) so no Sort was needed. Grant fell to [6 MB] (or none where the sort disappeared).
Prevention
Code review rule: list endpoints project to DTOs; an analyser flags entity queries with OrderBy on tables with LOB columns; alert on RESOURCE_SEMAPHORE wait time; load test with realistic concurrency.

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.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me