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

📚 Interview question

After a release, p95 latency on your orders API doubles and Azure SQL CPU climbs, but there are no errors. You suspect an EF Core query regression. Walk me through how you go from Application Insights to the SQL Server execution plan to the LINQ change that caused it, how you mitigate, and what you change so it doesn't happen again.

Covers diagnosing an EF Core query performance regression end to end: Application Insights release comparison and dependencies, Query Store regressed queries and plans, TagWith to map SQL to code, finding the LINQ change in the diff, mitigation (rollback, forced plan) and prevention.

Senior RealWorldScenario Advanced application-insights ef-core execution-plans performance-regression production-debugging query-store

🎯 Key points

  • Confirm it is the release: compare before/after by deployment annotation and application_Version
  • Rule out other causes: gradual data growth, stale statistics after a big load, tier or config changes
  • Application Insights: which operation, and is time in SQL dependencies (count or duration)?
  • Query Store: Regressed Queries and Top Resource Consuming; compare plans before and after
  • Map SQL back to code with TagWith / TagWithCallSite, then read the LINQ diff
  • Typical causes: non-sargable predicate, new Include (explosion), lost projection, lazy-loading N+1, parameter type change
  • Mitigate fast: roll back or flag off; Query Store plan forcing only for same-text plan regressions
  • Fix, verify with ToQueryString and the actual plan, then prevent: tags, perf tests, Query Store alerts, a written post-incident review

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd work from the outside in, and mitigate as soon as I'm confident it's the release. In Application Insights I'd look at the performance view with the deployment annotation and compare p95 by operation for an hour before and after. That usually narrows it to one or two endpoints. In the end-to-end transaction view for a slow request, the question is whether the SQL dependencies got longer or more numerous. Many short identical calls is N+1; one long call is a worse query or a worse plan.

For example, at [company] after [a release], p95 on [the orders list] went from [about 180 ms] to [about 400 ms]. Application Insights showed one SQL dependency that had gone from [20 ms] to [250 ms]. In Query Store, Regressed Queries showed that statement with a new plan: a clustered index scan where we'd had a seek. Our queries carried TagWith comments, so the SQL text said which handler it came from, and the diff showed a refactor that changed a date filter to o.CreatedAt.Date == day. EF Core translated that to CONVERT(date, [o].[CreatedAt]) = @day, which can't use the index range the old >= start AND < end predicate did. I [rolled back that release / turned off the feature flag] to stop the impact, then changed the LINQ back to a half-open range, checked ToQueryString() and the actual plan, and redeployed. p95 went back to [about 170 ms].

The mistake I see is jumping to plan forcing or scaling up the database. Plan forcing is right only when the same SQL got a worse plan, for example parameter sniffing after a statistics update. When the SQL text itself changed, forcing can't help, because Query Store sees it as a new query. And scaling up hides the regression while costing money. The senior part is the prevention: tags on queries, a performance test on production-sized data, and an alert on Query Store regressions."


The path from symptom to LINQ

Step Tool Question answered
1. Scope Application Insights performance view, deployment annotations, application_Version Which operations regressed, and did it start with the release?
2. Shape End-to-end transaction view, dependency count and duration per operation Longer SQL (worse query or plan) or more SQL calls (N+1)?
3. Statement Query Store: Regressed Queries, Top Resource Consuming, plan history Which statement, new SQL text or new plan for the same text?
4. Code TagWith / TagWithCallSite in the SQL text, git diff of the release Which LINQ changed?
5. Proof ToQueryString(), actual plan, SET STATISTICS IO Does the fix restore the seek and the reads?

Common EF Core regressions

LINQ change SQL effect
.Date, .Year, ToLower() on a column Non-sargable predicate: scan
New collection Include Cartesian explosion: rows multiply
Select projection replaced by returning entities Wide rows, key lookups, tracking cost
Lazy loading or a query in a loop N+1
Property mapped as Unicode where the column is varchar Implicit conversion
Contains on a growing list Plan per list size (older EF) or a different plan shape

Production example

The date-filter regression above added about 220 ms at p95 across [about 2 million] requests a day and pushed Azure SQL CPU from about 35% to 80%. The rollback took effect in minutes; the corrected query and a new performance test shipped the next day.

🔍 What the interviewer is checking

Checks that the candidate can run a structured production investigation from telemetry to plan to code, distinguishes plan regressions from query regressions, mitigates sensibly and prevents recurrence.

Green flags

  • Correlates with the deployment and compares p95 by operation and version
  • Distinguishes many short SQL calls (N+1) from one long call
  • Uses Query Store for regressed queries and plan history
  • Maps SQL to code with query tags
  • Mitigates first (rollback or flag), then proves the fix with the plan and reads

Red flags

  • Scales the database as the solution
  • Forces a plan without checking whether the SQL text changed
  • No evidence chain: guesses the cause from the diff alone

📚 Learn in depth

1. Confirming the release is the cause

Application Insights
  requests | where timestamp > ago(6h)
  | summarize p95 = percentile(duration, 95) by bin(timestamp, 10m), application_Version, name

If p95 jumps exactly where application_Version changes, and only for some operations, it's the release. If it rises gradually or for every operation, look at data growth, statistics, or the database tier instead.

2. Reading the dependency shape

slow request (450 ms)
  ├─ SQL  250 ms   <- one long call: worse query or plan
  └─ HTTP  30 ms

slow request (450 ms)
  ├─ SQL 2 ms x 180  <- many short calls: N+1

3. Query Store

Query Store records, per query, the plans used and runtime statistics per interval. Two cases:

Case What Query Store shows Fix
Same SQL, new plan One query id, two plan ids; the new plan is slower Force the good plan (sp_query_store_force_plan) as mitigation, then fix the cause (statistics, parameter sniffing, missing index)
New SQL text A new query id that appeared at release time Fix the LINQ; forcing doesn't apply

Azure SQL automatic tuning can force the last good plan automatically (FORCE_LAST_GOOD_PLAN), which helps the first case but not the second.

4. Mapping SQL to code

TagWith("Orders.List") adds a -- Orders.List comment to the SQL, visible in Query Store, Application Insights and Extended Events. TagWithCallSite() (EF Core 7+) adds the file and line. Without tags you're left grepping for table and column names.

5. Why the date filter regressed

-- before: sargable range, index seek on (TenantId, CreatedAt)
WHERE [o].[TenantId] = @t AND [o].[CreatedAt] >= @start AND [o].[CreatedAt] < @end
-- after: function on the column
WHERE [o].[TenantId] = @t AND CONVERT(date, [o].[CreatedAt]) = @day

SQL Server can sometimes still seek on CONVERT(date, datetime2) using a dynamic range, but with estimate errors and extra work; in this case the optimiser chose a scan, and the plan diff in Query Store showed it.

6. Making the fix stick

  • A performance test that runs the hot queries against a production-sized, anonymised database (synthetic data where privacy requires it under the Privacy Act) and fails on a logical-reads budget.
  • A Query Store regression alert, or Azure SQL Intelligent Insights, wired to the on-call channel.
  • Deployment annotations and application_Version on telemetry so comparisons are one query away.

Try it yourself

  1. Write the KQL above against your own Application Insights and chart p95 by version.
  2. Add TagWith to a query, run it, and find the comment in Query Store's query text.
  3. Change a range filter to .Date == and compare plans and logical reads.
  4. Force a plan with sp_query_store_force_plan in a test database, then change the LINQ and see that the forced plan no longer applies.
  5. Build a test that fails if a query exceeds a logical-reads budget using SET STATISTICS IO.

💻 Code

The regression, the fix, and the tags that made it traceable.

namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;

public sealed record OrderListItem(int Id, DateTime CreatedAt, decimal Total, string CustomerName);

public sealed class ListOrdersHandler(ShopDbContext db)
{
    // REGRESSION (shipped in the release): .Date on the column -> CONVERT(date, ...) -> index scan.
    public Task<List<OrderListItem>> HandleRegressedAsync(int tenantId, DateOnly day, CancellationToken ct) =>
        db.Orders
            .TagWith("Orders.List")
            .Where(o => o.TenantId == tenantId && o.CreatedAt.Date == day.ToDateTime(TimeOnly.MinValue))
            .Select(o => new OrderListItem(o.Id, o.CreatedAt, o.Total, o.Customer.Name))
            .ToListAsync(ct);

    // FIX: a half-open range on the stored value keeps the predicate sargable.
    public Task<List<OrderListItem>> HandleAsync(int tenantId, DateOnly day, CancellationToken ct)
    {
        var start = day.ToDateTime(TimeOnly.MinValue);
        var end = start.AddDays(1);
        return db.Orders
            .TagWithCallSite()                     // adds file and line to the SQL comment
            .Where(o => o.TenantId == tenantId && o.CreatedAt >= start && o.CreatedAt < end)
            .OrderByDescending(o => o.CreatedAt)
            .Select(o => new OrderListItem(o.Id, o.CreatedAt, o.Total, o.Customer.Name))
            .ToListAsync(ct);
    }
}
-- Query Store: find regressed queries in the last day and the comment that maps them to code.
SELECT TOP (10) q.query_id, qt.query_sql_text, p.plan_id,
       rs.avg_duration / 1000.0 AS avg_ms, rs.avg_logical_io_reads, rs.last_execution_time
FROM sys.query_store_query_text AS qt
JOIN sys.query_store_query AS q ON q.query_text_id = qt.query_text_id
JOIN sys.query_store_plan AS p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id
WHERE rs.last_execution_time > DATEADD(day, -1, SYSUTCDATETIME())
  AND qt.query_sql_text LIKE N'%Orders.List%'
ORDER BY rs.avg_duration DESC;
// Application Insights: p95 by operation and release version.
requests
| where timestamp > ago(12h) and name startswith "GET /api/orders"
| summarize p95 = percentile(duration, 95), calls = count() by bin(timestamp, 15m), application_Version
| order by timestamp asc

⚠ Common mistakes

  • Mistake: Scaling up the database to make the alert go away. Why it is wrong: it hides the regression, costs money and the problem grows with data. Instead: find the statement and fix it; scale only as a short, deliberate mitigation.
  • Mistake: Forcing the old plan when the SQL text changed. Why it is wrong: Query Store treats new text as a new query, so the forced plan doesn't apply. Instead: force plans only for same-text plan regressions; fix the LINQ otherwise.
  • Mistake: Looking only at average duration. Why it is wrong: averages hide tail regressions and per-tenant effects. Instead: compare p95 and p99 by operation and version.
  • Mistake: Debugging without a way to map SQL to code. Why it is wrong: finding the LINQ from SQL text in a large codebase is slow. Instead: tag queries with TagWith or TagWithCallSite.
  • Mistake: Testing performance on a small developer database. Why it is wrong: scans are fast on 1,000 rows; the regression only appears at production volume. Instead: run hot queries against production-sized synthetic or anonymised data with a reads budget.
  • Mistake: Rolling forward with a guess while users suffer. Why it is wrong: a second bad deploy prolongs the incident. Instead: roll back or flag off first, then fix calmly.

🏛 Senior insight: trade-offs

The senior skill here is running the incident and the investigation in parallel: mitigate quickly once the release is clearly the cause, then find the exact statement, the exact plan change and the exact LINQ change, with evidence at each step. I also rule out the non-release causes explicitly: a gradual rise points to data growth, and a sudden plan change on unchanged SQL after a large import often means stale or freshly updated statistics (check sys.dm_db_stats_properties for last update and modification counter). I'm wary of database-side band-aids (plan forcing, scaling) when the root cause is application code, because they hide the next regression. The lasting fix is observability built in before the incident: tagged queries, version-aware telemetry, Query Store alerts and a performance gate on hot queries.

Finally, I write it up: a blameless post-incident review with the timeline, the evidence chain (telemetry, Query Store plan ids, the LINQ diff), the fix and the prevention items with owners, shared with the other teams that use the same query helpers. In my experience the write-up, plus the review checklist item that comes out of it, prevents more regressions than the fix itself.

Mitigation When it fits Cost When not to
Roll back the release Clear correlation with the deploy Loses the release's other changes Schema migrations that are not backward compatible
Feature flag off The change is behind a flag Needs flags in place Untargeted refactors
Query Store plan forcing Same SQL, new worse plan Plan can become wrong as data changes SQL text changed
Update statistics Plan changed after a large data change Brief extra I/O; may recompile many plans Root cause is new SQL text
Scale up temporarily Buying time during peak Cost, hides the cause As the fix

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TagWith or mapping SQL to code Why: Checks depth on ToQueryString, LogTo, TagWith and how EF Core queries appear in telemetry
    How to answer

    For one query, ToQueryString() shows the SQL without running it. For a running app, LogTo(Console.WriteLine, LogLevel.Information) or, in ASP.NET Core, setting the Microsoft.EntityFrameworkCore.Database.Command log category to Information logs each command with its duration. TagWith("Orders list") puts a SQL comment in the statement (and TagWithCallSite() adds file and line), so a slow query found in Query Store or a trace leads straight back to the code. EnableSensitiveDataLogging adds parameter values to logs: useful locally, but it leaks personal data and secrets, so never in production. In production, Application Insights / OpenTelemetry record each SQL command as a dependency with timing, and capturing SQL text is opt-in. The trade-off is visibility versus log volume, cost and privacy.

  2. When: Candidate identifies a non-sargable predicate as the cause Why: Checks they know the LINQ patterns that defeat indexes and how to fix them
    How to answer

    In EF Core, indexes are part of the model: HasIndex(...) or the [Index] attribute generate CREATE INDEX in a migration, so the schema stays in source control. EF Core adds indexes for foreign keys by convention; every other index is your decision. On SQL Server you can make them unique, filtered (HasFilter), descending (IsDescending) and covering (IncludeProperties). The other half is writing LINQ that can use them: Name.ToLower() == x, Contains (becomes LIKE '%x%'), o.CreatedAt.Year == 2026 and arithmetic on columns are non-sargable, so SQL Server scans; an nvarchar parameter against a varchar column causes an implicit conversion. I verify with the actual execution plan and Query Store. The trade-off: every index speeds some reads and slows every write.

  3. When: Candidate mentions many short SQL dependencies per request Why: Checks they can diagnose and fix the N+1 variant of the regression
    How to answer

    N+1 means one query loads a list of N rows and then the code runs one more query per row to fetch related data: 1 + N round trips instead of 1 or 2. In EF Core it comes from lazy loading, a query inside a foreach (FirstOrDefaultAsync, CountAsync, Entry(x).Collection().Load()), or a mapper touching navigations. I detect it by counting SQL commands per request: EF Core logging (LogTo or the Microsoft.EntityFrameworkCore.Database.Command category), Application Insights dependency calls under one operation id, or MiniProfiler's duplicate-query warning. The fix is a set-based query: project with Select into a DTO, Include the navigation, or fetch the children in one query with Contains(ids) and join in memory. The trade-off: one round trip per request is the goal, but one huge joined query can cause cartesian explosion, so sometimes two queries beat one.

🛠 Real-world problems: how you handle them

Date filter refactor turns an index seek into a scan
Situation
An orders API on ASP.NET Core and EF Core 10 against Azure SQL [Business Critical, Australia East] serving [about 2 million] requests a day. A release refactored the order list handler into a shared query helper.
Signals
Within 30 minutes of the release, p95 for `GET /api/orders` rose from [about 180 ms] to [about 400 ms]; Azure SQL CPU rose from [35%] to [80%]; no errors or exceptions; Application Insights smart detection raised a response-time degradation alert.
Investigation
Application Insights showed the regression only on the order list operation and only on the new `application_Version`. The transaction view showed one SQL dependency growing from [20 ms] to [250 ms]. Query Store's Regressed Queries listed a new query id with a clustered index scan and [about 60x] the logical reads. The `-- Orders.List` tag pointed to the handler; the diff showed `CreatedAt.Date == day` replacing a range.
Resolution
Rolled back the release within [15 minutes], which restored p95. Changed the LINQ back to a half-open range, confirmed the seek with `ToQueryString()` and the actual plan on a production-sized copy, and redeployed the next day.
Prevention
Added `TagWithCallSite()` to the shared query helper; a performance test with a logical-reads budget for the top 20 queries on a production-sized synthetic dataset; a Query Store regression alert; non-sargable patterns added to the review checklist.

How to tell it (STAR)

**S:** After a release of [our orders API], p95 on the order list doubled to about [400 ms] and database CPU hit [80%], with no errors. **T:** I was [on call / the engineer who owned the release] and needed to restore performance and find the cause. **A:** Application Insights showed the regression only on one operation and only on the new version, with one SQL call going from [20] to [250 ms]. Query Store showed a new query using a scan, and our query tag pointed straight to the handler. The diff showed a refactor had changed a date range to a .Date comparison, which EF Core translated into CONVERT on the column. I rolled back within [15 minutes], restored the range filter, proved the seek on a production-sized copy, and added a logical-reads performance test and a Query Store alert. **R:** p95 returned to about [170 ms], CPU to [35%], and the performance test has since blocked [two] similar changes before release.

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me