The cross-layer method for tuning EF Core and SQL Server data access: splitting request time into app, round trips and database, finding the generated SQL, reading the plan, fixing at the right layer and verifying with numbers.
I start by breaking down where the time goes, not by guessing at indexes. In Application Insights I open a slow request in the end-to-end transaction view and look at its SQL dependency calls: lots of small calls mean N+1 or chattiness, one long call means a query or plan problem, and a short SQL time inside a long request means the cost is in the app (materialisation, tracking, serialisation). Next I get the exact SQL with EF Core logging or TagWithCallSite(). Then I read the actual execution plan and Query Store for logical reads, estimated vs actual rows, scans and key lookups. I fix it at the cheapest correct layer: projection and query shape first, then indexes, then plan stability, and only then caching. Each change is proved with before/after p95 and logical reads. The trade-off is that chasing SQL alone misses the round trips and the in-app cost, which are often the bigger share.
"My first job is to find out where the time actually goes, because 'the database is slow' is wrong surprisingly often. I open a slow sample in Application Insights' end-to-end transaction view and read the request as a timeline. If it has 180 SQL dependency calls of 3 ms each, it's an N+1 or a chatty loop, and no index will fix it. If it has one call taking 2.4 seconds, it's a query or plan problem. If SQL adds up to 200 ms of a 1.5-second request, the cost is in my process: materialising and tracking thousands of entities, or serialising a huge graph.
Once I know it's a query, I get the exact SQL. I tag queries with
TagWithCallSite()so the SQL carries the file and line, and I can find it in Query Store or Extended Events. Then I read the actual plan: logical reads, estimated vs actual rows, scans where I expected seeks, key lookups running thousands of times, sort spills. Query Store tells me whether this is a steady cost or a plan that regressed. For example, at [company] a [customer search] endpoint was [2.1 s] at p95. The timeline showed one query doing [1.8 million] logical reads because of a non-SARGable date filter. Rewriting the predicate and adding a covering index brought it to [140 ms] and [3,000] reads.I fix at the cheapest correct layer: shape the query (projection, no cartesian Includes) first, then indexes, then plan stability, and caching last. The mistake I see is tuning the SQL in SSMS and never checking whether the request got faster in production. The query is only the means; the request p95 is the number I'm accountable for."
| Layer | Symptom in the trace | Typical cause | First fix |
|---|---|---|---|
| Round trips | Dozens or hundreds of short SQL calls | N+1, lazy loading, per-item queries in a loop | Projection with joins, batching, Include or split query |
| Query execution | One long SQL call | Scan, bad estimate, missing index, parameter sniffing | Rewrite predicate, index, fix statistics, Query Store hint |
| Waiting | SQL time high but low CPU in Query Store | Blocking, RESOURCE_SEMAPHORE, I/O waits |
Shorter transactions, RCSI, smaller memory grants |
| Transfer | Long SQL call with huge row count | Over-fetching columns or rows, cartesian explosion | Project to DTOs, page, split queries |
| In-app | Short SQL, long request | Tracking thousands of entities, mapping, serialisation | AsNoTracking, project to DTO, stream |
| Question | Tool |
|---|---|
| How many calls, and how long each? | Application Insights transaction search, dependency duration, OpenTelemetry traces |
| Which LINQ produced this SQL? | TagWith, TagWithCallSite, ToQueryString(), EF Core command logging |
| What does the query cost? | Actual execution plan, SET STATISTICS IO, TIME ON, Query Store runtime stats |
| Did it regress? | Query Store regressed queries, plan history per query |
| Is it waiting rather than working? | Query Store wait stats, sys.dm_exec_requests, blocking reports |
An [orders list] endpoint was [1.6 s] at p95 with [62] SQL calls per request. Replacing lazy-loaded navigation access with one projected query cut that to [1] call and [210 ms]. A covering index on (CustomerId, CreatedAt DESC) INCLUDE (Status, Total) then brought it to [90 ms], and Query Store showed logical reads drop from [48,000] to [600].
Checks whether the candidate has a repeatable, measurement-driven method across app and database, rather than jumping straight to indexes.
Green flags
TagWith, ToQueryString, actual plans, Query StoreRed flags
For a data-heavy endpoint, latency is roughly:
request time = app CPU + Σ (network RTT + SQL wait + SQL CPU + row transfer) + materialisation + serialisation
The Σ is per round trip. With an Azure App Service in Australia East talking to Azure SQL in the same region, RTT is often around 1 ms. So 200 round trips cost at least 200 ms before SQL does any work. That is why counting calls comes before reading plans.
GET /api/orders?customer=42 1,640 ms
├─ SQL SELECT ... FROM Customers 4 ms
├─ SQL SELECT ... FROM Orders 12 ms
├─ SQL SELECT ... FROM OrderLines (x60) ~3 ms each ← N+1
└─ JSON serialisation 90 ms
Application Insights (or any OpenTelemetry backend) records SqlClient calls as dependencies. With EnableSqlCommandTextInstrumentation (or the OpenTelemetry SqlClient option to record statement text) you can see the command text, but treat it as sensitive: parameter values can contain personal information covered by the Privacy Act 1988.
query.ToQueryString() shows the SQL for one query in tests or the debugger.optionsBuilder.LogTo(..., LogLevel.Information) or the Microsoft.EntityFrameworkCore.Database.Command log category logs every command with its duration.TagWith("OrdersList") or TagWithCallSite() adds a SQL comment, so you can find the query in Query Store (query_sql_text) and Extended Events.SET STATISTICS IO ON gives logical reads per table. Reads are more stable than duration on a shared server, which makes them the better before/after measure.EF Core has to materialise rows into objects, run identity resolution and, when tracking, snapshot original values for change detection. For large read-only result sets, AsNoTracking() or projecting to a DTO record removes most of that. Projection also shrinks the SQL column list, which can make a covering index possible.
One change at a time, measured in three places:
TagWithCallSite() to a query and find it in sys.query_store_query_text.SET STATISTICS IO, TIME ON, record the logical reads, add a covering index and compare.ToListAsync() with and without AsNoTracking() for 10,000 rows in BenchmarkDotNet, using [MemoryDiagnoser].Tag queries so each SQL statement can be traced back to its LINQ, log commands in development, and project to a DTO without tracking.
// Program.cs
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ShopDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("Shop"));
if (builder.Environment.IsDevelopment())
{
// Logs every command with its duration; never log parameter values in production.
options.LogTo(Console.WriteLine, [DbLoggerCategory.Database.Command.Name], LogLevel.Information);
}
});
var app = builder.Build();
app.MapGet("/api/customers/{id:int}/orders", async (int id, ShopDbContext db, CancellationToken ct) =>
await db.Orders
.TagWithCallSite() // SQL comment with file and line: findable in Query Store
.Where(o => o.CustomerId == id)
.OrderByDescending(o => o.CreatedAt)
.Select(o => new OrderSummary(o.Id, o.CreatedAt, o.Status, o.Lines.Sum(l => l.Quantity * l.UnitPrice)))
.Take(50)
.ToListAsync(ct)); // projection: no tracking, only needed columns, one round trip
app.Run();
public sealed record OrderSummary(int Id, DateTime CreatedAt, string Status, decimal Total);
In SQL Server, measure reads before and after, and find the tagged query in Query Store:
SET STATISTICS IO, TIME ON;
-- paste the logged SQL here and run it with the same parameter values
SELECT TOP (20) qt.query_sql_text, rs.avg_duration / 1000.0 AS avg_ms, rs.avg_logical_io_reads, rs.count_executions
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 qt.query_sql_text LIKE N'%OrdersEndpoint%' -- part of the call-site tag
ORDER BY rs.avg_duration DESC;
sp_executesql, or read the plan from Query Store.EnableSensitiveDataLogging off outside development and tag queries instead.The senior move is to treat the request, not the query, as the unit of performance, and to pick the layer that gives the biggest gain for the least risk. In my experience the most common causes of slow EF Core endpoints are round trips and query shape, which no index fixes. But plan problems are a close second and need checking every time: parameter sniffing, stale statistics after a big data load, and a regressed plan in Query Store. A query that is fast for one customer and slow for another is usually a plan problem, not a shape problem. Waits matter too. Long transactions holding locks, including a TransactionScope that escalates to a distributed transaction, show up as SQL time with low CPU. Genuine 'SQL Server is too slow' problems are rare.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| Projection / query shape | Over-fetching, N+1, cartesian Includes | Code change, low risk | Query is already minimal |
| Index | Hot predicate scans, key lookups | Write cost and storage, needs DBA review | Write-heavy tables with many existing indexes |
| Statistics update / plan forcing / Query Store hints | Estimate gaps, plan regression, parameter sniffing | Forced plans can go stale as data changes | Root cause is a bad predicate |
| Caching | Read-heavy, tolerates staleness | Invalidation and consistency | Data must be fresh, or the query is simply bad |
I measure with logical reads for the SQL and p95 plus calls per request for the endpoint, and I keep the Query Store baseline so a later regression is easy to see. The method is the same in Datadog or New Relic as in Application Insights: per-request spans with SQL dependencies.
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.
An estimated plan is what the optimiser would do; an actual plan is the same plan plus runtime numbers: actual rows, number of executions, memory grant used and runtime warnings. Data flows right to left; thick arrows mean many rows.
The first thing I check is estimated vs actual rows on each operator: a big gap means a bad estimate, and almost every bad plan follows from one. Then I look for scans where I expected seeks, key lookups executed thousands of times, the join type (nested loops with a huge outer input is a red flag), and warnings such as CONVERT_IMPLICIT, spills and residual predicates.
Cost percentages are estimates too, so I confirm with logical reads from SET STATISTICS IO.
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.
How to tell it (STAR)
**S:** At [company], our order-history endpoint had drifted from [250 ms] to almost [2 seconds] at p95 as the catalogue grew. **T:** I was asked to fix it without a big rewrite. **A:** Instead of guessing, I broke one slow request down in Application Insights. It had [60] SQL calls from lazy loading plus one query scanning [1.2 million] pages because of a function on the date column. I replaced the lazy loading with one projected query, rewrote the date predicate as a range, and added a covering index after checking the write cost with our DBA. I verified each step with logical reads and production p95. **R:** p95 dropped to [120 ms], Azure SQL CPU fell by [about 40%], and we added a test that fails if an endpoint's SQL call count grows.
Last updated 23 Nov 2026.