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.
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.
"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
TagWithcomments, so the SQL text said which handler it came from, and the diff showed a refactor that changed a date filter too.CreatedAt.Date == day. EF Core translated that toCONVERT(date, [o].[CreatedAt]) = @day, which can't use the index range the old>= start AND < endpredicate 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, checkedToQueryString()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."
| 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? |
| 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 |
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.
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
Red flags
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.
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
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.
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.
-- 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.
application_Version on telemetry so comparisons are one query away.TagWith to a query, run it, and find the comment in Query Store's query text..Date == and compare plans and logical reads.sp_query_store_force_plan in a test database, then change the LINQ and see that the forced plan no longer applies.SET STATISTICS IO.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
TagWith or TagWithCallSite.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.