Covers a production incident on Azure SQL: confirming CPU saturation with sys.dm_db_resource_stats, finding the culprit with sys.dm_exec_requests and Query Store, telling a plan regression from a new or changed query, mitigating with plan forcing, rollback or scaling, fixing the root cause, and preventing it with release gates and alerts.
First I confirm the database is the bottleneck: sys.dm_db_resource_stats or Azure Monitor shows CPU at 100% while workers and waits climb. Then I find the culprit two ways: live, with sys.dm_exec_requests ordered by CPU, and historically, with Query Store's Top Resource Consuming for the last hour against yesterday.
The key question is whether it's a new or changed query from the release, or the same query with a new plan. A plan regression I mitigate by forcing the last good plan; a code regression by rolling back or turning off the feature flag. Scaling up buys time but isn't a fix.
Then I fix the root cause (non-SARGable LINQ, missing index, N+1), and add release checks and alerts so we catch it before customers do.
"My first job is to stop the bleeding, and to do that I need the culprit fast. I confirm it's really the database: Azure Monitor or
sys.dm_db_resource_statsshows CPU pinned at 100% from the release time, and the API's Application Insights dependency calls show SQL duration and timeouts rising. Then I run two queries side by side.sys.dm_exec_requestsjoined to the SQL text and plan, ordered by CPU, shows what's running now; usually the same statement appears dozens of times. And Query Store's Top Resource Consuming report by total CPU for the last hour, compared with the same hour yesterday, shows what changed.For example, at [company] after a release of our [orders API], CPU went to 100% within [15] minutes. Query Store showed a query_id that didn't exist the day before using [70%] of CPU, so it was new code, not a plan regression. The plan was a clustered index scan of [9 million] rows, executed [hundreds] of times a minute, because a LINQ change had turned
o.CreatedAt >= frominto a comparison ono.CreatedAt.Date, which EF Core translated to aCONVERT(date, ...)on the column. Forcing a plan wouldn't help a new query, so we turned off the feature flag; CPU fell to [40%] in [about 3] minutes. The fix was a SARGable range, plus an integration test asserting the generated SQL, and we released it the next day.If it had been the same query with a new plan, I'd have forced the previous plan in Query Store, or checked whether automatic plan correction had already done it. Scaling up the service objective is a valid way to buy time, but I'd say so explicitly and scale back after. The mistake I see is people restarting or failing over the database: it flushes the evidence, and the same query comes straight back. Find it, mitigate the specific thing, then fix and prevent."
| What Query Store shows | Likely cause | Mitigation |
|---|---|---|
| New query_id dominating CPU | New code path from release | Feature flag off / roll back |
| Same query, new text (different hash) | Changed LINQ or SQL | Roll back; compare old vs new SQL |
| Same query_id, new plan_id | Plan regression (stats, sniffing) | Force last good plan |
| Same query and plan, many more executions | N+1 or retry storm | Roll back; check App Insights call counts |
| Nothing new, everything slower | Resource limit, noisy job, blocking | Check waits, jobs, scale up temporarily |
| Minute | Action |
|---|---|
| 0–5 | Confirm DB CPU, open incident channel, notify stakeholders |
| 5–10 | Identify query (DMVs + Query Store) |
| 10–20 | Mitigate (flag off, roll back, force plan, or scale) |
| Next day | Root cause fix with test; post-incident review |
Turning the flag off restored CPU from 100% to [40%] in [3] minutes and API error rate from [12%] to under [0.1%]. The fixed query read [420] pages instead of [96,000] per call, and a release gate now compares Query Store top CPU queries in staging before and after each deployment.
Checks whether the candidate can run a database performance incident calmly: find, mitigate, fix, prevent.
Green flags
Red flags
Azure SQL Database exposes resource usage in the database itself:
SELECT end_time, avg_cpu_percent, avg_data_io_percent, avg_log_write_percent,
max_worker_percent, max_session_percent
FROM sys.dm_db_resource_stats -- 15-second granularity, about 1 hour
ORDER BY end_time DESC;
sys.resource_stats in master keeps 5-minute data for about 14 days. If workers are near 100% too, requests are queuing, which is what causes connection timeouts in the app.
sys.dm_exec_requests (session, status, cpu_time, wait_type, sql_handle, plan_handle, query_hash)
|-- sys.dm_exec_sql_text(sql_handle) -> statement text
|-- sys.dm_exec_query_plan(plan_handle) -> cached plan
`-- GROUP BY query_hash -> 'same query, 60 copies'
High CPU with SOS_SCHEDULER_YIELD or no wait means CPU-bound execution; CXPACKET/CXCONSUMER suggests parallel scans.
Query Store aggregates per interval, so 'last hour vs same hour yesterday' answers 'new query, changed query, or new plan'. EF Core query tags (TagWith) or TagWithCallSite put the source in the SQL text, making the jump from query_id to code immediate.
| Option | Speed | Risk |
|---|---|---|
| Feature flag off | Seconds | Needs flags around risky changes |
| Roll back deployment | Minutes | Schema migrations may not roll back cleanly |
| Force plan | Seconds | Only for plan regressions |
| Query Store hint (e.g. MAXDOP 1) | Seconds | Treats symptom |
| Scale up service objective | Minutes, brief reconnect | Cost; hides the problem |
| Kill sessions | Seconds | They come straight back |
.Date, ToString(), string functions) translated to functions on columns.sys.dm_db_resource_stats.sys.dm_exec_requests by query_hash during the load..Date in a filter, log the SQL, and rewrite it as a range.The incident queries, in the order I'd run them.
-- 1. Is it CPU? (Azure SQL Database, last ~hour, 15-second rows)
SELECT TOP (40) end_time, avg_cpu_percent, max_worker_percent, avg_data_io_percent
FROM sys.dm_db_resource_stats ORDER BY end_time DESC;
-- 2. What's burning CPU right now, grouped by query shape
SELECT r.query_hash,
COUNT(*) AS running_copies,
SUM(r.cpu_time) AS total_cpu_ms,
MAX(r.wait_type) AS sample_wait,
MIN(SUBSTRING(t.text, r.statement_start_offset / 2 + 1, 400)) AS statement
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.session_id <> @@SPID
GROUP BY r.query_hash
ORDER BY total_cpu_ms DESC;
-- 3. Last hour vs same hour yesterday, by query, from Query Store
WITH w AS (
SELECT p.query_id,
CASE WHEN i.start_time >= DATEADD(hour, -1, SYSUTCDATETIME()) THEN 'now' ELSE 'yesterday' END AS win,
SUM(rs.avg_cpu_time * rs.count_executions) / 1e6 AS cpu_s,
SUM(rs.count_executions) AS execs,
MAX(p.plan_id) AS latest_plan
FROM sys.query_store_runtime_stats rs
JOIN sys.query_store_runtime_stats_interval i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id
JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id
WHERE i.start_time >= DATEADD(hour, -1, SYSUTCDATETIME())
OR i.start_time BETWEEN DATEADD(hour, -25, SYSUTCDATETIME()) AND DATEADD(hour, -24, SYSUTCDATETIME())
GROUP BY p.query_id,
CASE WHEN i.start_time >= DATEADD(hour, -1, SYSUTCDATETIME()) THEN 'now' ELSE 'yesterday' END
)
SELECT n.query_id, n.cpu_s AS cpu_now, y.cpu_s AS cpu_yesterday, n.execs, y.execs AS execs_yesterday
FROM w n LEFT JOIN w y ON y.query_id = n.query_id AND y.win = 'yesterday'
WHERE n.win = 'now'
ORDER BY n.cpu_s DESC; -- cpu_yesterday NULL = new query from the release
-- 4a. Plan regression: force the previous plan
EXEC sys.sp_query_store_force_plan @query_id = 8812, @plan_id = 301;
The root cause in this story, and the fix, in EF Core:
namespace Orders.Api.Queries;
using Microsoft.EntityFrameworkCore;
public sealed class RecentOrdersQuery(OrdersDbContext db)
{
public Task<List<OrderSummary>> RunAsync(DateOnly day, CancellationToken ct)
{
var from = day.ToDateTime(TimeOnly.MinValue);
var to = from.AddDays(1);
// Before (released): o.CreatedAt.Date == from -> CONVERT(date, CreatedAt) = @p -> scan
// After: half-open range on the raw column -> index seek
return db.Orders
.TagWithCallSite()
.Where(o => o.CreatedAt >= from && o.CreatedAt < to)
.Select(o => new OrderSummary(o.Id, o.CreatedAt, o.Total))
.ToListAsync(ct);
}
}
public sealed record OrderSummary(long Id, DateTime CreatedAt, decimal Total);
TagWith/TagWithCallSite on important queries.CONVERT(date, CreatedAt)) forces SQL Server to evaluate it for every row, so there's no seek; on 1,000 rows that's invisible, on 9 million rows run hundreds of times a minute it saturates CPU. Instead: Test data-access changes against production-sized data and look at the plan.sys.dm_db_tuning_recommendations and the automatic tuning settings as part of triage, and keep FORCE_LAST_GOOD_PLAN on.The senior skill here is triage: quickly classifying the incident as new code, changed code, plan regression, or capacity, because each has a different minute-one mitigation. Feature flags and Query Store are what make a 3-minute mitigation possible; without them the only lever is a full rollback.
Prevention is a system, not a person being careful: production-sized test data, SQL assertions on critical queries, Query Store comparisons as a release step, alerts on database CPU and dependency latency, automatic plan correction on, and a blameless review that turns each incident into a check.
| Mitigation | When it fits | Cost | When not to |
|---|---|---|---|
| Feature flag off | New code path | Requires flag discipline | Change not behind a flag |
| Roll back | Changed code, no irreversible migration | Loses other release fixes | Destructive migration already ran |
| Force last good plan | Plan regression | Plan ages | New or changed query text |
| Scale up | Need time, cause unclear | Cost, brief reconnects | As the permanent answer |
Query Store is a flight recorder inside each database. It saves query text, every plan a query has used, and runtime statistics (duration, CPU, logical reads, memory, waits) aggregated per time interval, and it survives restarts and failovers.
I use the Regressed Queries and Top Resource Consuming reports to see which query got slower and whether its plan changed. If it did, I can force the previous plan, or attach a Query Store hint without touching code.
It's on by default in Azure SQL Database and for new databases in SQL Server 2022, and Azure SQL's automatic plan correction can force the last good plan for you. The trade-off is a little overhead and storage; the settings to watch are size, capture mode and the flip to read-only when full.
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.
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.
How to tell it (STAR)
**S:** Fifteen minutes after we released our [orders API], Azure SQL CPU hit 100% and [12%] of requests were failing. **T:** As [the on-call engineer], I had to restore service and find the cause. **A:** I confirmed CPU saturation in sys.dm_db_resource_stats, saw sixty copies of one statement in sys.dm_exec_requests, and Query Store showed it was a brand-new query using 70% of CPU, so forcing a plan wouldn't help. The query tag pointed to a new LINQ filter using `.Date`, which EF Core turned into a function on the column. I turned off the feature flag, and the next day shipped a range-based filter plus a test on the generated SQL. **R:** CPU dropped to [40%] within [3] minutes, errors cleared, the fixed query used [99%] fewer reads, and Query Store comparisons are now part of every release.
Last updated 23 Nov 2026.