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

📚 Interview question

An API endpoint that reads from SQL Server through EF Core is slow, and you don't yet know where the time goes. Walk me through how you tune it end to end: from Application Insights dependency timings, to the SQL EF Core generates, to the execution plan, and how you prove each change helped.

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.

Mid-Level Theory Intermediate application-insights ef-core execution-plans performance query-store sql-server

🎯 Key points

  • Break request time down first: app code vs number of DB round trips vs time per query (Application Insights or any OpenTelemetry APM end-to-end view)
  • Count the dependency calls per request: many fast calls = N+1/chattiness, one slow call = query or plan problem
  • Get the exact SQL: EF Core logging (LogTo / Microsoft.EntityFrameworkCore.Database.Command), TagWith/TagWithCallSite, ToQueryString()
  • Read the actual plan and Query Store: logical reads, rows estimated vs actual (stale statistics, parameter sniffing), scans, key lookups, spills, waits
  • Fix at the cheapest correct layer: projection and query shape in LINQ, then indexes, then plan stability, then caching
  • Watch materialisation and tracking cost in the app (AsNoTracking, DTO projection, AsAsyncEnumerable streaming for large results)
  • Change one thing at a time and verify with before/after p95, logical reads and Query Store duration in production

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Where the time can go

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

The toolchain per layer

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

Order of fixes

  1. Query shape: project only needed columns, remove N+1, avoid cartesian Includes, push filters and paging to the server.
  2. Indexes: a seek-friendly predicate plus a covering index for the hot query; check the write cost.
  3. Plan stability: statistics, parameter sniffing, Query Store plan forcing or hints.
  4. App-side cost: no-tracking, compiled queries for very hot simple queries, DbContext pooling.
  5. Caching or precomputation: only once the query is as good as it reasonably gets.

Production example

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].

🔍 What the interviewer is checking

Checks whether the candidate has a repeatable, measurement-driven method across app and database, rather than jumping straight to indexes.

Green flags

  • Splits request time into round trips, SQL time and in-app cost before fixing anything
  • Names concrete tools: Application Insights dependencies, TagWith, ToQueryString, actual plans, Query Store
  • Uses logical reads and p95 as before/after evidence
  • Fixes query shape before indexes, and indexes before caching

Red flags

  • "Add an index" or "add Redis" as the first answer
  • Only talks about SQL, ignoring N+1 and materialisation
  • No way to prove the change helped in production

📚 Learn in depth

1. A request is a sum of parts

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.

2. Seeing the request as a timeline

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.

3. From LINQ to the SQL text

  • 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.

4. Reading the cost in SQL Server

  • 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.
  • In the actual plan, compare estimated vs actual rows. A 100x gap means statistics or parameter sniffing. Look for key lookups with high execution counts, scans on large tables, and sort or hash spill warnings.
  • Query Store keeps per-plan duration, CPU, reads and waits over time, so you can tell "always slow" from "slow since Tuesday's plan change".

5. Costs in the app process

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.

6. Verifying

One change at a time, measured in three places:

  1. SQL: logical reads and CPU per execution (Query Store).
  2. Request: p50/p95 and SQL calls per request (Application Insights).
  3. System: Azure SQL DTU/vCore CPU and blocking.

Try it yourself

  1. Turn on EF Core command logging in a sample API and count the commands for one request that touches a navigation property in a loop.
  2. Add TagWithCallSite() to a query and find it in sys.query_store_query_text.
  3. Run the query in SSMS with SET STATISTICS IO, TIME ON, record the logical reads, add a covering index and compare.
  4. Compare ToListAsync() with and without AsNoTracking() for 10,000 rows in BenchmarkDotNet, using [MemoryDiagnoser].
  5. Open the Application Insights end-to-end transaction view for a slow request and write down the time per layer.

💻 Code

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;

⚠ Common mistakes

  • Mistake: Optimising without measuring, for example adding indexes because the endpoint "feels slow". Why it is wrong: You may tune a query that is 5% of the request while 150 round trips cost the rest. Instead: Break down the request timeline first and record a baseline p95.
  • Mistake: Looking only at SQL duration. Why it is wrong: Round trips, materialisation, tracking and serialisation never appear in the plan. Instead: Compare total SQL time with request time and count calls per request.
  • Mistake: Tuning the query in SSMS with literal values. Why it is wrong: SSMS uses different SET options and literals, so you get a different plan from the parameterised one the app uses. Instead: Use the logged parameterised SQL with sp_executesql, or read the plan from Query Store.
  • Mistake: Using duration as the only before/after measure on a shared database. Why it is wrong: Duration is noisy because of concurrency and cache state. Instead: Use logical reads and CPU per execution, plus production p95.
  • Mistake: Reaching for caching first. Why it is wrong: It hides a bad query, adds staleness and invalidation bugs, and the cold path stays slow. Instead: Fix query shape and indexes first; cache what is still expensive.
  • Mistake: Micro-optimising cold paths, such as compiling a query that runs twice a day. Why it is wrong: It adds complexity for no measurable gain. Instead: Rank queries by total cost (executions × cost) in Query Store.
  • Mistake: Logging SQL parameter values in production. Why it is wrong: It can put personal information in logs, which is a Privacy Act and APP 11 risk. Instead: Leave EnableSensitiveDataLogging off outside development and tag queries instead.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions many short SQL calls in one request Why: Checks they can detect and fix N+1 queries in EF Core in detail.
    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.

  2. When: Candidate mentions reading the actual execution plan Why: Checks they can actually read operators, estimates and warnings in a plan.
    How to answer

    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.

  3. When: Candidate mentions Query Store or plan regressions Why: Checks depth on Query Store: regressed queries, plan forcing and 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.

🛠 Real-world problems: how you handle them

Customer search slow after the product catalogue tripled
Situation
[B2C retail API] on Azure App Service and Azure SQL in Australia East, [~300 requests/s] at peak. The customer order-history endpoint's p95 rose from [250 ms] to [1.9 s] over a month as data grew.
Signals
Application Insights p95 alert on the endpoint; dependency view showing [40-70] SQL calls per request; Azure SQL CPU at [70%]; no errors.
Investigation
Opened slow samples in the end-to-end transaction view: one 900 ms query plus dozens of 5 ms calls. Enabled EF Core command logging in staging and found lazy loading triggering per-order line queries. Pulled the slow query from Query Store via its TagWithCallSite comment; the actual plan showed a clustered index scan from `CONVERT(date, CreatedAt) = @d` and [1.2 million] logical reads.
Resolution
Immediate: replaced the lazy-loaded navigation access with a single projected query, which cut calls to 2 per request. Real fix: rewrote the date filter as a range (`CreatedAt >= @start AND CreatedAt < @end`) and added a covering index on `(CustomerId, CreatedAt DESC) INCLUDE (Status, Total)`. p95 fell to [120 ms] and reads to [900].
Prevention
Disabled lazy loading proxies; added an integration test that asserts the number of SQL commands per request with an interceptor; Application Insights alert on dependency calls per request; Query Store regressed-query review in the weekly ops meeting.

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.

More in EF and SQL Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me