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

📚 Interview question

Fifteen minutes after a release, your Azure SQL Database CPU hits 100% and the API starts timing out. Walk me through how you find the query responsible using Query Store and DMVs, how you mitigate it in minutes, how you fix it properly, and what you put in place so it doesn't happen again.

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.

Senior RealWorldScenario Advanced azure-sql dmv incident-response performance-regression query-store sql-server

🎯 Key points

  • Confirm the bottleneck: sys.dm_db_resource_stats (15-second rows for about an hour; sys.resource_stats in master for ~14 days) and Azure Monitor metrics
  • CPU saturation makes requests queue for schedulers and workers; when max_worker_percent nears 100% new requests wait or fail, which is what the API sees as timeouts
  • Live view: sys.dm_exec_requests grouped by query_hash, ordered by cpu_time; Query Store Top Resource Consuming for the last hour vs yesterday
  • Classify: new query from the release, changed query text, same query with a new plan, more executions (N+1), or capacity
  • Mitigate by cause: new/changed code -> feature flag off or roll back; plan regression -> force last good plan (or confirm FORCE_LAST_GOOD_PLAN did); unclear -> temporary scale-up
  • Root cause fix: SARGable LINQ/SQL, missing index, N+1 loop, parameter types; prove it with reads per call and CPU before/after
  • Prevention: Query Store comparison in release checks, Application Insights dependency alerts, automatic plan correction on, production-sized load tests
  • Communicate: incident channel, timeline, blameless post-incident review

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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_stats shows 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_requests joined 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 >= from into a comparison on o.CreatedAt.Date, which EF Core translated to a CONVERT(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."


Triage decision

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

Communication and timeline

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can run a database performance incident calmly: find, mitigate, fix, prevent.

Green flags

  • Confirms the bottleneck with resource stats before acting.
  • Uses both live DMVs and Query Store history.
  • Distinguishes new query, changed query and plan regression, with the right mitigation for each.
  • Talks about prevention and communication.

Red flags

  • Restarts or fails over first.
  • Only knows 'scale up'.
  • No idea how to map a query back to code.

📚 Learn in depth

1. Confirm the bottleneck

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.

2. What's running now

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.

3. What changed

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.

4. Mitigation options and their trade-offs

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

5. Common root causes after a release

  • Non-SARGable LINQ (.Date, ToString(), string functions) translated to functions on columns.
  • N+1 queries from lazy loading or a loop calling the database.
  • Parameter type mismatch (nvarchar vs varchar) from a mapping change.
  • A new filter on an unindexed column.
  • A migration that dropped or changed an index.

6. Prevention as a system

  • Release check: run the integration test suite against a production-sized copy and compare Query Store top queries before and after.
  • Alerts: Azure Monitor CPU > 80% for 5 minutes; Application Insights dependency p95 and failure rate per operation.
  • Automatic plan correction left on.
  • Feature flags for risky data-access changes.

Try it yourself

  1. On a test Azure SQL database, generate load with a non-SARGable query and watch sys.dm_db_resource_stats.
  2. Group sys.dm_exec_requests by query_hash during the load.
  3. Use Query Store to compare two one-hour windows.
  4. Write an EF Core query with .Date in a filter, log the SQL, and rewrite it as a range.
  5. Create an Azure Monitor alert on CPU percent and trigger it.

💻 Code

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

⚠ Common mistakes

  • Mistake: Restarting, failing over or scaling the database first. Why it is wrong: It clears the plan cache and DMV evidence and the query returns. Instead: Capture DMV and Query Store data first; scale only as an explicit time-buying step.
  • Mistake: Forcing a plan for a query that's new. Why it is wrong: There's no previous good plan; the code is the problem. Instead: Roll back or turn off the feature flag.
  • Mistake: Killing the top sessions. Why it is wrong: The app immediately reissues the same queries. Instead: Mitigate the cause.
  • Mistake: Looking only at the slowest single execution. Why it is wrong: A 50 ms query run 50,000 times uses more CPU. Instead: Rank by total CPU (avg × executions).
  • Mistake: Leaving a temporary scale-up in place. Why it is wrong: Cost rises and the regression is hidden. Instead: Track it as an action with a date to scale back.
  • Mistake: Not tagging EF Core queries. Why it is wrong: Mapping a query_id to code takes much longer. Instead: Use TagWith/TagWithCallSite on important queries.
  • Mistake: Testing releases on tiny databases. Why it is wrong: A function on a column (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.
  • Mistake: Ignoring what Azure SQL already did. Why it is wrong: Automatic plan correction may have forced or unforced a plan during the incident, which changes what you see. Instead: Check sys.dm_db_tuning_recommendations and the automatic tuning settings as part of triage, and keep FORCE_LAST_GOOD_PLAN on.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses Query Store to compare time windows Why: Checks Query Store depth: settings, forcing, hints
    How to 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.

  2. When: Candidate considers a plan regression Why: Checks parameter sniffing diagnosis
    How to 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.

  3. When: Candidate mentions EF Core or Application Insights Why: Checks the EF Core-specific regression workflow
    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.

🛠 Real-world problems: how you handle them

Azure SQL CPU pinned at 100% after an orders API release
Situation
An [orders API] on [Azure SQL Database, General Purpose 8 vCores, Australia East] handled [about 300] requests per second at peak. A release went out at [10:00] with a new 'today's orders' filter.
Signals
Azure Monitor CPU alert at [10:14]; `max_worker_percent` climbing; Application Insights showed SQL dependency p95 from [40 ms] to [9 s], HTTP 500 rate [12%], and connection timeout exceptions.
Investigation
`sys.dm_db_resource_stats` confirmed CPU at 100% from [10:05]. `sys.dm_exec_requests` grouped by query_hash showed [60+] copies of one statement. Query Store comparison showed that query_id had no data yesterday and was using [70%] of CPU. Its plan was a clustered index scan with `CONVERT(date, [CreatedAt])` in the predicate; the EF Core tag pointed at the new filter using `.Date`.
Resolution
Immediate: turned off the feature flag at [10:21]; CPU fell to [40%] within [3] minutes and errors cleared. Fix next day: half-open date range in LINQ, verified seek on a production-sized copy, reads per call from [96,000] to [420].
Prevention
Integration test asserting the generated SQL contains no functions on indexed columns for critical queries; release step comparing Query Store top-10 CPU queries in staging; feature flags required for new data-access paths; post-incident review shared with the team.

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.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me