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

📚 Interview question

A stored procedure (or an EF Core query) is fast when you run it in SSMS but takes 30 seconds from your .NET API, and Query Store shows its duration jumped yesterday with no code change. How do you diagnose it, and what are your options to fix it?

Covers diagnosing parameter sniffing: why SSMS and the app get different plans (ARITHABORT and other SET options, local variables), finding the regressed plan in Query Store, comparing compiled and runtime parameter values, and fixes from OPTION (RECOMPILE) and OPTIMIZE FOR to plan forcing, Query Store hints, PSP optimisation and code changes.

Senior Debugging Advanced debugging ef-core execution-plans parameter-sniffing query-store sql-server

🎯 Key points

  • Parameter sniffing: plan compiled for the first parameter values is reused for all later values; a recompile (statistics update, failover, eviction) re-rolls the dice
  • SSMS defaults SET ARITHABORT ON, SqlClient uses OFF, so SSMS gets its own cache entry and a fresh plan; local variables use density, not sniffing
  • Query Store 'Regressed queries' shows the plan change; plan XML has ParameterCompiledValue vs ParameterRuntimeValue
  • Immediate mitigation: force the previous good plan in Query Store (or let FORCE_LAST_GOOD_PLAN do it), or evict that single plan by plan_handle
  • OPTION (RECOMPILE) costs compile CPU every call (often 1–50 ms) and hides the query from plan-cache DMVs; only for low-frequency, high-skew queries
  • Other fixes: OPTIMIZE FOR, Query Store hints for ORM SQL, splitting code paths, an index that makes one plan cheap for all values
  • PSP optimisation (SQL Server 2022, compat 160) and OPPO (SQL Server 2025, compat 170) handle some skew automatically
  • Forced parameterisation is not a fix for sniffing (it creates more sniffing); never DBCC FREEPROCCACHE the whole server

⏱ 30-second answer

This is almost always parameter sniffing. SQL Server compiled the plan for the first parameter values it saw, maybe a tiny customer, and now reuses it for a customer with 2 million rows. SSMS looks fast because it runs with SET ARITHABORT ON (the app's SqlClient uses OFF), so it gets a separate cache entry and compiles a fresh plan for my values.

I confirm it in Query Store: the regressed query, two plan ids, and in the plan XML ParameterCompiledValue vs ParameterRuntimeValue. Mitigate by forcing the good plan. Then fix properly: OPTION (RECOMPILE) for infrequent queries, OPTIMIZE FOR, a Query Store hint, splitting code paths, or an index that makes one plan good for everyone. SQL Server 2022's PSP optimisation helps some cases.

🗣 Full answer (senior)

How I would answer this in an interview

> "'Fast in SSMS, slow in the app' and 'slow since yesterday with no code change' together point straight at parameter sniffing. When a parameterised statement compiles, the optimiser sniffs the parameter values and builds a plan for them: seek plus key lookups for a customer with 20 orders, say. That plan is cached and reused. If it was evicted and recompiled yesterday, perhaps after a statistics update or a failover, and the first caller was unusual, everyone else now runs a plan built for the wrong data. SSMS hides it because SSMS sets ARITHABORT ON and SqlClient doesn't; SET options are part of the cache key, so my SSMS run compiles its own plan for my values. And if I paste the query with DECLARE @CustomerId int = 42, that's a local variable, which uses the density vector, so I'm not testing the same thing at all. > > For example, at [company] our [order history] endpoint went from [300 ms] to [28 s] one morning. I opened Query Store's Regressed Queries, found the procedure with two plans, and the new plan's XML showed ParameterCompiledValue was a customer with [11] orders, while the runtime value was one of our biggest accounts with [1.8 million]. The old plan used a hash join and scan; the new one did 1.8 million key lookups. I forced the previous plan in Query Store, which brought p95 back within [minutes], then fixed it properly by [adding a covering index so both plan shapes became cheap] and kept the forced plan off. > > The mistake I see is running DBCC FREEPROCCACHE on the server. It 'fixes' it until the next unlucky compile and causes a CPU storm while every plan recompiles. Parameter sniffing is a feature that usually helps; the fix is to make the plan right for the data distribution, not to keep rolling the dice."


Diagnosis steps

Step Tool What I'm looking for
1 Application Insights dependency telemetry Which SQL call regressed, when it started
2 Query Store: Regressed Queries / Queries With High Variation Same query_id, new plan_id, duration jump
3 Plan XML ParameterList Compiled vs runtime values
4 Histogram / row counts per value How skewed the parameter is
5 Reproduce with sp_executesql and the app's SET options Same plan as the app

Why SSMS differs

Cause Effect
ARITHABORT ON in SSMS, OFF in SqlClient Different plan cache entry, fresh compile
Local variables in a pasted query Density-based estimate, not sniffing
Literal values instead of parameters Different statement text, its own plan
Different database context or schema-unqualified names Different cache entry

Fix options

Fix When it fits Cost
Force last good plan (Query Store) Immediate mitigation Plan may age badly; review later
OPTION (RECOMPILE) Runs < a few times per second, very skewed Compile CPU every execution
OPTIMIZE FOR (@p = value) / UNKNOWN One plan is acceptable for all Some values get a mediocre plan
Query Store hint (sp_query_store_set_hints) Can't change the code (EF Core, vendor app) Managed outside source control
Split procedures / branch by value Known 'big' vs 'small' tenants More code
Covering index Both plan shapes can become cheap Write cost
PSP optimisation (2022, compat 160) Equality predicates on skewed columns Automatic; up to 3 plan variants

Production example

Forcing the old plan restored p95 from 28 s to 350 ms within ten minutes. The covering index then made the 'small customer' plan cheap even for large customers (logical reads 1.9 million to 22,000), and we unforced the plan a week later after Query Store showed stable duration.

🔍 What the interviewer is checking

Checks whether the candidate can diagnose the most common production SQL performance incident methodically and pick a proportionate fix.

Green flags

  • Names parameter sniffing and explains the ARITHABORT/SET options cache key difference.
  • Uses Query Store and compiled vs runtime parameter values.
  • Mitigates with plan forcing, then fixes properly.
  • Knows the cost of RECOMPILE and mentions PSP optimisation.

Red flags

  • Flushes the whole plan cache.
  • Tests with local variables and concludes 'it's fine'.
  • Says 'add WITH (NOLOCK)' or 'restart the server'.

📚 Learn in depth

1. What sniffing actually is

At compile time the optimiser can see parameter values (stored procedure parameters, sp_executesql parameters, which is what EF Core, Dapper and SqlClient send). It uses them to look up the histogram and estimate rows. The plan is then cached and reused for every value.

first call: @CustomerId = 17 (11 rows)
   -> estimate 11 rows -> Index Seek + Key Lookup + Nested Loops -> cached

later call: @CustomerId = 3 (1.8M rows)
   -> cache hit -> same plan -> 1.8M key lookups, tiny memory grant, spills

The opposite also happens: a plan compiled for a big value (scan, hash, big grant) makes every small lookup slow and memory-hungry.

2. Why it changed 'with no code change'

Plans are recompiled when statistics update past the threshold, an index is rebuilt, the plan is evicted under memory pressure, the instance restarts or fails over (Azure SQL reconfigurations included), or someone runs sp_recompile. Whoever calls first decides the plan.

3. The SET options trap

Plan cache entries are keyed by text and plan-affecting SET options. Check them:

SELECT pa.attribute, pa.value
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_plan_attributes(cp.plan_handle) pa
WHERE pa.attribute = 'set_options';

SSMS and SqlClient differ in ARITHABORT, so you see two entries. To reproduce the app, run SET ARITHABORT OFF; in SSMS first, then call it with sp_executesql and the same parameter values.

4. Reading compiled vs runtime values

In the plan XML (root SELECT properties in SSMS, 'Parameter List'):

<ColumnReference Column="@CustomerId"
    ParameterCompiledValue="(17)" ParameterRuntimeValue="(3)" />

Runtime values appear only in actual plans. Query Store stores the compiled values with each plan.

5. Built-in help in recent versions

  • Parameter Sensitive Plan optimisation (SQL Server 2022, compat level 160): for equality predicates on skewed columns, the optimiser builds a dispatcher plan that picks one of up to three query variants by the parameter's cardinality range. Shown in Query Store as variants of one parent query.
  • Optional parameter plan optimisation (OPPO) (SQL Server 2025, compat level 170, on by default there): handles WHERE (@p IS NULL OR col = @p) patterns with separate variants.
  • Automatic plan correction (FORCE_LAST_GOOD_PLAN, on by default for new Azure SQL servers): detects plan-choice regressions and forces the last good plan, verifying the result.

None of them cover every case (ranges, multiple skewed predicates, catch-all procedures).

6. EF Core and Dapper specifics

EF Core and Dapper send sp_executesql, so sniffing applies. You can't put OPTION (RECOMPILE) in LINQ directly; use a DbCommandInterceptor scoped by a query tag (TagWith) or a Query Store hint on the query_id. Tags also make the query easy to find in Query Store.

Try it yourself

  1. Create a skewed orders table (one customer with 1 million rows, others with 10), call a procedure for a small customer then the big one, and compare actual plans.
  2. Run the same procedure in SSMS with default settings and with SET ARITHABORT OFF, and list the cache entries with sys.dm_exec_plan_attributes.
  3. Find the query in Query Store, force the good plan with sp_query_store_force_plan, and confirm with is_forced_plan.
  4. Apply sp_query_store_set_hints @query_id, N'OPTION (RECOMPILE)' and observe compile counts.
  5. Switch to compat level 160 and look for PSP dispatcher plans and query variants.

💻 Code

Find the regression, mitigate it, and fix it.

-- 1. Queries whose recent duration is much worse than before, with plan counts
SELECT TOP (10)
    q.query_id,
    qt.query_sql_text,
    COUNT(DISTINCT p.plan_id)                       AS plan_count,
    MAX(rs.avg_duration) / 1000.0                   AS worst_avg_ms,
    MIN(rs.avg_duration) / 1000.0                   AS best_avg_ms
FROM sys.query_store_query q
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
JOIN sys.query_store_plan p        ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats rs ON rs.plan_id = p.plan_id
WHERE rs.last_execution_time > DATEADD(day, -2, SYSUTCDATETIME())
GROUP BY q.query_id, qt.query_sql_text
HAVING COUNT(DISTINCT p.plan_id) > 1
ORDER BY MAX(rs.avg_duration) / NULLIF(MIN(rs.avg_duration), 0) DESC;

-- 2. Mitigate: force the previously good plan (reversible)
EXEC sys.sp_query_store_force_plan @query_id = 4711, @plan_id = 902;

-- Or, for a query you can't edit (EF Core), attach a hint to it
EXEC sys.sp_query_store_set_hints @query_id = 4711, @query_hints = N'OPTION (RECOMPILE)';

-- 3. Code-level fixes in a procedure
CREATE OR ALTER PROCEDURE dbo.GetOrderHistory @CustomerId int
AS
SELECT OrderId, OrderDate, Total
FROM dbo.Orders
WHERE CustomerId = @CustomerId
ORDER BY OrderDate DESC
OPTION (RECOMPILE);   -- fine at tens of calls per second; not at thousands

For EF Core, tag the query so you can find it and target it with an interceptor:

namespace Shop.Data;

using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

public sealed class RecompileInterceptor : DbCommandInterceptor
{
    public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
        DbCommand command, CommandEventData eventData,
        InterceptionResult<DbDataReader> result, CancellationToken ct = default)
    {
        // Only queries explicitly tagged by the developer get the hint
        if (command.CommandText.Contains("-- order-history", StringComparison.Ordinal))
            command.CommandText += " OPTION (RECOMPILE)";
        return base.ReaderExecutingAsync(command, eventData, result, ct);
    }
}

public sealed class OrderHistoryQuery(ShopDbContext db)
{
    public Task<List<OrderRow>> RunAsync(int customerId, CancellationToken ct) =>
        db.Orders
          .TagWith("order-history")
          .Where(o => o.CustomerId == customerId)
          .OrderByDescending(o => o.OrderDate)
          .Select(o => new OrderRow(o.OrderId, o.OrderDate, o.Total))
          .ToListAsync(ct);
}

public sealed record OrderRow(long OrderId, DateTime OrderDate, decimal Total);

⚠ Common mistakes

  • Mistake: Running DBCC FREEPROCCACHE on the server to fix it. Why it is wrong: It flushes every plan, spikes CPU and the bad plan may come back on the next unlucky compile. Instead: Force the good plan or evict the single plan with DBCC FREEPROCCACHE (plan_handle).
  • Mistake: Reproducing in SSMS with default settings. Why it is wrong: ARITHABORT ON gives a separate cache entry and a fresh plan. Instead: SET ARITHABORT OFF and call sp_executesql with the app's values.
  • Mistake: Copying the query and declaring local variables. Why it is wrong: Local variables use density estimates, not sniffing. Instead: Parameterise exactly as the app does.
  • Mistake: Putting OPTION (RECOMPILE) on a query that runs thousands of times a second. Why it is wrong: Every call pays compile CPU (milliseconds each, far more for complex queries) and the plan isn't kept in the cache for DMV analysis. Instead: Use plan forcing, OPTIMIZE FOR, or a better index; keep RECOMPILE for infrequent, highly skewed queries.
  • Mistake: Leaving forced plans in place forever. Why it is wrong: Data and schema change; a forced plan can become the bad plan or fail to force. Instead: Track forced plans and review them after the real fix.
  • Mistake: Setting ARITHABORT ON in the app 'to match SSMS'. Why it is wrong: It changes nothing about sniffing; it just moves which session gets which plan. Instead: Fix the plan's sensitivity.
  • Mistake: Blaming the deployment. Why it is wrong: Recompiles happen from statistics updates, failovers and memory pressure. Instead: Correlate the plan change time in Query Store with those events.
  • Mistake: Writing EF Core catch-all filters such as .Where(o => customerId == null || o.CustomerId == customerId) for search screens. Why it is wrong: One cached plan has to serve 'all rows' and 'one customer', so it is wrong for one of them. Instead: Compose the IQueryable conditionally so each filter combination is its own statement, or rely on OPPO only after testing on compat 170.
  • Mistake: Not tagging EF Core queries. Why it is wrong: Generated SQL is hard to match to code in Query Store during an incident. Instead: Use TagWith (or TagWithCallSite) on important queries so the comment appears in the SQL text.
  • Mistake: Treating OPTIMIZE FOR UNKNOWN as a universal fix. Why it is wrong: It plans for the average from the density vector, which is wrong for both tails of skewed data. Instead: Use it only when an average plan is measurably acceptable for all values.

🏛 Senior insight: trade-offs

Parameter sniffing is the default behaviour and usually a win; the problem is skew combined with plan shapes that are very sensitive to row counts. The most durable fix is often to make the cheap plan safe for every value (a covering index removes the key lookups that made the small plan dangerous) rather than adding a hint.

Every fix is a trade-off between compile CPU, plan quality and visibility. RECOMPILE buys a perfect plan per call at the price of CPU and lost plan-cache history; forcing buys stability at the price of a plan that ages; hints in Query Store buy speed of mitigation at the price of living outside source control. I want mitigation fast, visible and reversible, recorded in the incident notes, with a follow-up ticket for the real fix. On Azure SQL, automatic plan correction may already have acted; check sys.dm_db_tuning_recommendations, Query Store and Azure SQL Intelligent Insights before acting, and keep an Application Insights alert on dependency p95 per query tag.

Option When it fits Cost When not to
Force plan in Query Store Incident mitigation Needs review; can fail after schema change Permanent fix without monitoring
OPTION (RECOMPILE) Low frequency, high skew Compile CPU per call; no cached plan stats Hot paths
OPTIMIZE FOR UNKNOWN Average plan is acceptable to all Mediocre for extremes Highly skewed data
Query Store hints ORM or vendor SQL Lives outside source control When you can fix the code
Index change Plan shapes can converge Write cost Write-heavy tables with many indexes
Separate statements per filter combination Search screens, catch-all queries More plans in cache Hundreds of combinations

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions differences between how the app and SSMS send parameters Why: Checks the related nvarchar vs varchar implicit conversion problem
    How to answer

    In .NET a string becomes an nvarchar parameter by default (ADO.NET AddWithValue, Dapper sends nvarchar(4000), EF Core when the property is Unicode). nvarchar has higher data type precedence than varchar, so SQL Server converts the column, not the parameter: CONVERT_IMPLICIT(nvarchar, AccountNo). With a SQL collation that means a scan of every row; with a Windows collation you may get a dynamic seek, but with worse estimates. SSMS was fast because the literal there was varchar.

    Diagnose with the plan warning ('Type conversion may affect seek plan'), Query Store and a plan cache search. Fix at the mapping layer: EF Core IsUnicode(false)/HasColumnType("varchar(20)"), Dapper DbString { IsAnsi = true }, ADO.NET SqlDbType.VarChar with a size. Trade-off: changing the column to nvarchar also works but doubles storage.

  2. When: Candidate mentions EF Core or Application Insights Why: Checks the end-to-end path from app telemetry to the LINQ change
    How to answer

    First I confirm it's the release: Application Insights with the deployment annotation, comparing p95 by operation before and after. Then I check where the time goes: in the slow operation, are SQL dependencies longer (a worse query) or more numerous (N+1)? Next, Query Store on Azure SQL: Regressed Queries and Top Resource Consuming Queries show which statement got worse and whether its plan changed. I map that SQL back to code with TagWith comments (or the text), then read the LINQ diff: typical culprits are a non-sargable predicate, a new collection Include, a lost projection, or a parameter type change. I mitigate first: roll back or flag the change off; force the old plan only if it's purely a plan regression. Then fix the LINQ, verify the plan, and add query tags, a perf test and Query Store alerts. The trade-off: rollback is fastest, but only the root cause stops it recurring.

  3. When: Candidate mentions newer SQL Server versions handling sniffing Why: Checks currency with modern SQL Server and its limits
    How to answer

    At compatibility level 160 (SQL Server 2022, Azure SQL), when a parameterised query has an equality predicate on a column whose histogram shows heavy skew, the optimiser compiles a dispatcher plan instead of one plan. At run time the dispatcher looks up the parameter value's cardinality in the statistics, puts it in a low, medium or high bucket, and runs the matching query variant, each with its own cached plan. It considers up to three such predicates. It does not handle range predicates, catch-all @p IS NULL OR col = @p queries (SQL Server 2025's Optional Parameter Plan Optimisation, OPPO, targets those), skew the statistics can't see, or estimation problems that aren't about the parameter.

🛠 Real-world problems: how you handle them

Order history endpoint regresses from 300 ms to 28 s overnight
Situation
A [customer portal] API on [Azure SQL Business Critical] served order history for [about 60,000] customers. Order counts were highly skewed: most customers had under 50 orders, [a handful of corporate accounts] had over a million.
Signals
Application Insights alerts on p95 dependency duration for `dbo.GetOrderHistory` (from [300 ms] to [28 s]); timeouts in the API logs for some customers only; Azure SQL CPU at [85%]; no deployment in the previous 24 hours.
Investigation
Query Store Regressed Queries showed the procedure with a new plan id created at [02:14], right after an automatic statistics update. The new plan's compiled value was a customer with [11] orders; it used an index seek plus key lookups with nested loops. Running it in SSMS was fast because SSMS's ARITHABORT ON compiled a separate plan. With `SET ARITHABORT OFF` and `sp_executesql` the slow plan reproduced, showing [1.8 million] key lookups and a sort spill.
Resolution
Immediate: forced the previous plan with `sp_query_store_force_plan`, restoring p95 within [10 minutes]. Long term: added a covering index `(CustomerId, OrderDate DESC) INCLUDE (Total, Status)` so the seek plan needed no lookups and was cheap for every customer, then unforced the plan after a week of stable Query Store data.
Prevention
Load tests now include the largest and smallest tenants; a runbook covers 'fast in SSMS, slow in app' with the ARITHABORT check; forced plans are listed on a weekly dashboard from `sys.query_store_plan WHERE is_forced_plan = 1`; automatic plan correction left enabled.

How to tell it (STAR)

**S:** Our order history API went from [300 ms] to [28 seconds] overnight with no deployment, and only some customers were timing out. **T:** I was on call and needed to restore service, then stop it recurring. **A:** Query Store showed a new plan right after a statistics update, compiled for a customer with 11 orders. SSMS looked fine because of the ARITHABORT difference, so I reproduced with the app's settings and saw 1.8 million key lookups. I forced the old plan to stop the bleeding, then added a covering index so one plan was cheap for every customer, and unforced the plan a week later. **R:** p95 was back under [350 ms] within ten minutes, logical reads for the big accounts fell from [1.9 million] to [22,000], and we added skewed tenants to our load tests.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me