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

📚 Interview question

Your API endpoint is slow and the logs show the same SELECT running 200 times for one request. What is the N+1 query problem in EF Core, how do you detect it (EF Core logging, Application Insights, MiniProfiler), and how do you fix it?

Covers what N+1 queries are in EF Core, the code shapes that cause them, how to detect them with logging, Application Insights and MiniProfiler, and the fixes: projection, Include, batching by key and split queries.

Mid-Level Debugging Intermediate application-insights debugging ef-core miniprofiler n-plus-one query-performance

🎯 Key points

  • 1 query for the parent list + N queries, one per row, for related data
  • Causes: lazy loading, a query or FirstOrDefaultAsync inside a loop, explicit Load per item
  • Detect: count commands per request in LogTo / Application Insights dependencies / MiniProfiler
  • Fix with one set-based query: Select projection, Include, or Contains on a key list
  • Watch the cost per round trip: 1-2 ms on Azure SQL in the same region, x N
  • Guard with a test or middleware that asserts a maximum command count per request
  • Do not over-correct into one giant Include query (cartesian explosion)

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

🗣 Full answer (senior)

How I would answer this in an interview

"N+1 is the most common EF Core performance bug I see. You run one query to get, say, 50 orders, and then for each order the code goes back to the database for its customer or its lines. That's 51 round trips. Each one is cheap on its own, maybe 1 to 2 milliseconds to Azure SQL in the same region, but they are sequential, so a page that should take 15 ms takes 300 ms, and it gets worse as the data grows. It also never shows up in a unit test with three rows.

In EF Core it comes from a few shapes: lazy loading proxies, where touching order.Customer silently fires a query; an await db.Something.FirstOrDefaultAsync() inside a foreach; calling Entry(x).Collection(...).LoadAsync() per item; or AutoMapper walking navigations. To find it I count commands per request. Locally I turn on LogTo and see the same parameterised SELECT repeated. In production, Application Insights shows the end-to-end transaction with dozens of identical SQL dependency calls under one operation id, and MiniProfiler flags duplicate queries in development.

The fix is to make it set-based. For read endpoints I project with Select into a DTO, which EF Core translates into one query with joins or a correlated subquery. If I need entities, I Include the navigation. If the related data comes from a different query path, I collect the keys, run one Where(x => ids.Contains(x.Id)) query, and stitch the results together with a dictionary. The mistake I see is fixing N+1 by Including everything, which turns 51 small queries into one query returning a cartesian product. The goal is a small, fixed number of queries per request, not necessarily one."


Where N+1 comes from in EF Core

Shape Why it fires N queries Fix
Lazy loading proxies Every navigation access is a query Turn lazy loading off; project or Include
Query inside a loop await db.X.FirstOrDefaultAsync(...) per item One Contains(ids) query, then a dictionary
Explicit loading per item Entry(e).Collection(c).LoadAsync() in a loop Include, or load all children in one query
Mapper or serialiser touching navigations Triggers lazy loads during mapping ProjectTo / manual Select before materialising
Count per row db.Lines.CountAsync(l => l.OrderId == o.Id) in a loop Select(o => new { o.Id, LineCount = o.Lines.Count() })

How to detect it

Tool What you look for
LogTo(Console.WriteLine, LogLevel.Information) or the Microsoft.EntityFrameworkCore.Database.Command log category The same SQL text repeated with different parameter values
Application Insights end-to-end transaction view Dozens of identical SQL dependencies under one request; dependency count per request in a KQL query
MiniProfiler (MiniProfiler.EntityFrameworkCore) Duplicate-query highlighting and total SQL time per request
An integration test with a command-counting interceptor Fails the build when an endpoint exceeds its query budget

Production example

An order history endpoint [in a system I worked on] loaded 100 orders and then lazily loaded each order's customer and shipping address: 201 queries and a p95 of about 900 ms. Replacing it with one Select projection cut it to a single query and a p95 of about 60 ms, and Azure SQL DTU use for that endpoint dropped by roughly two thirds.

🔍 What the interviewer is checking

Checks that the candidate can recognise N+1 from symptoms, knows the EF Core shapes that cause it, and fixes it with set-based queries without over-correcting.

Green flags

  • Explains the round-trip cost and why it grows with data volume
  • Names concrete detection tools: LogTo, Application Insights dependencies, MiniProfiler
  • Prefers projection for reads and mentions Contains for key lists
  • Mentions guarding against regressions with a query-count test
  • Warns about cartesian explosion as the over-correction

Red flags

  • Suggests caching or more database capacity as the fix
  • Fixes it by parallelising queries on one DbContext
  • Unaware that lazy loading triggers queries
  • Includes every navigation by default

📚 Learn in depth

1. Why N+1 hurts more than the SQL suggests

Each query pays a fixed cost before any rows are read: a network round trip, SQL Server parsing or plan cache lookup, execution, and result materialisation in EF Core.

Request
  ├─ SELECT * FROM Orders WHERE CustomerId = @p   (1 query, 100 rows)
  ├─ SELECT * FROM Customers WHERE Id = @p0        ┐
  ├─ SELECT * FROM Customers WHERE Id = @p0        │ 100 sequential
  ├─ ...                                           │ round trips
  └─ SELECT * FROM Customers WHERE Id = @p0        ┘

If one round trip costs 1.5 ms, 100 of them cost 150 ms of pure waiting, and they cannot run in parallel on one DbContext because a context does not support concurrent operations. Across regions (an app in Australia Southeast talking to a database in Australia East) the per-trip cost is higher still.

2. What the set-based version looks like

A projection lets EF Core translate the whole graph into one statement:

SELECT [o].[Id], [o].[PlacedAt], [c].[Name], (
    SELECT COUNT(*) FROM [OrderLines] AS [l] WHERE [o].[Id] = [l].[OrderId]) AS [LineCount]
FROM [Orders] AS [o]
INNER JOIN [Customers] AS [c] ON [o].[CustomerId] = [c].[Id]
WHERE [o].[CustomerId] = @customerId

For a key-list fetch, EF Core 8+ sends Contains over a parameter list as OPENJSON(@ids) on SQL Server (EF Core 10 adds more options for how the list is parameterised), so one query handles any number of keys with a stable plan.

3. Why lazy loading is the usual culprit

Lazy loading proxies (UseLazyLoadingProxies()) override virtual navigation properties. The first access calls the context's lazy loader, which runs a query. The code looks like plain property access, so the cost is invisible in review. Serialising an entity graph to JSON touches every navigation, which turns one response into hundreds of queries. Most teams building APIs keep lazy loading off and make data access explicit.

4. Detecting it systematically

  • Logging: EF Core logs every command at Information level under Microsoft.EntityFrameworkCore.Database.Command. Group by SQL text to spot repeats.
  • Application Insights: SQL dependencies carry the operation id, so a KQL query such as dependencies | where type == "SQL" | summarize count() by operation_Id finds requests with abnormal counts.
  • Interceptor in tests: a DbCommandInterceptor that increments a counter lets an integration test assert Assert.True(counter.Count <= 3).

5. Over-correcting

The opposite failure is one query with several collection Includes. Each collection multiplies the row count, so 100 orders with 10 lines and 5 notes return 5,000 rows. The target is a small, bounded number of queries per request, whatever the data size.

Try it yourself

  1. Seed 1,000 orders with customers, write a loop that reads order.Customer.Name with lazy loading on, and count the commands with LogTo.
  2. Rewrite it as a Select projection, print ToQueryString(), and compare timings with BenchmarkDotNet.
  3. Write a DbCommandInterceptor that counts commands and fail an integration test when the count exceeds 2.
  4. Add MiniProfiler to a sample API and look at its duplicate-query warning on the N+1 version.
  5. In Application Insights, write a KQL query that lists the 10 operations with the most SQL dependencies in the last day.

💻 Code

Before and after: an N+1 loop replaced with one projection, plus a command-counting interceptor for tests.

namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;

public sealed record OrderSummary(int Id, DateTime PlacedAt, string CustomerName, int LineCount);

public sealed class OrderQueries(ShopDbContext db)
{
    // BEFORE: 1 query for orders + 2 queries per order = 2N + 1 round trips.
    public async Task<List<OrderSummary>> GetSlowAsync(int customerId, CancellationToken ct)
    {
        var orders = await db.Orders.Where(o => o.CustomerId == customerId).ToListAsync(ct);
        var result = new List<OrderSummary>();
        foreach (var o in orders)
        {
            var customer = await db.Customers.FirstAsync(c => c.Id == o.CustomerId, ct); // query per row
            var lines = await db.OrderLines.CountAsync(l => l.OrderId == o.Id, ct);      // and another
            result.Add(new OrderSummary(o.Id, o.PlacedAt, customer.Name, lines));
        }
        return result;
    }

    // AFTER: one SQL statement with a join and a correlated COUNT subquery.
    public Task<List<OrderSummary>> GetAsync(int customerId, CancellationToken ct) =>
        db.Orders
            .Where(o => o.CustomerId == customerId)
            .Select(o => new OrderSummary(o.Id, o.PlacedAt, o.Customer.Name, o.Lines.Count))
            .ToListAsync(ct);

    // When the related rows come from elsewhere: one query by key list, then join in memory.
    public async Task<Dictionary<int, string>> GetCustomerNamesAsync(IReadOnlyCollection<int> ids, CancellationToken ct) =>
        await db.Customers
            .Where(c => ids.Contains(c.Id))          // translated to OPENJSON / IN, one round trip
            .ToDictionaryAsync(c => c.Id, c => c.Name, ct);
}
namespace Shop.Tests;

using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;

// Register with options.AddInterceptors(counter) in the test host, then assert a query budget.
public sealed class CommandCounter : DbCommandInterceptor
{
    private int _count;
    public int Count => _count;

    public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
        DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = default)
    {
        Interlocked.Increment(ref _count);
        return ValueTask.FromResult(result);
    }
}

⚠ Common mistakes

  • Mistake: Leaving lazy loading proxies on in an API. Why it is wrong: every navigation access becomes a hidden query, and JSON serialisation touches them all. Instead: keep lazy loading off and load data explicitly with projection or Include.
  • Mistake: Testing with three seeded rows and concluding the endpoint is fast. Why it is wrong: N+1 scales with data; it looks fine until production volume. Instead: assert a query count per request in integration tests.
  • Mistake: Fixing N+1 by adding Include for every navigation. Why it is wrong: several collection Includes in one query cause cartesian explosion. Instead: project only what the endpoint returns, or use AsSplitQuery() for multiple collections.
  • Mistake: Running the per-row queries in parallel with Task.WhenAll on one DbContext. Why it is wrong: a DbContext is not thread-safe and throws on concurrent operations; even with separate contexts it multiplies load. Instead: replace N queries with one set-based query.
  • Mistake: Building a huge IN list by string concatenation. Why it is wrong: SQL injection risk and a new plan per list length. Instead: use Contains on a collection, which EF Core parameterises.
  • Mistake: Only looking at total request time. Why it is wrong: 200 fast queries each look healthy in isolation. Instead: look at dependency count per operation in Application Insights.

🏛 Senior insight: trade-offs

N+1 is a design smell more than a query bug: it appears when data access is hidden behind properties, repositories that return single entities, or mappers. The durable fix is to make each use case fetch its data in a known, bounded number of queries and to enforce that with a query budget in tests. I also review new endpoints by looking at the Application Insights dependency count, not just duration, because count is what grows with data.

Fix When it fits Cost When not to
Select projection into a DTO Read endpoints Least data, no tracking When you need to modify and save the entities
Include / ThenInclude Loading an aggregate to change it Pulls full entities; tracked by default Several collections at once (use split query)
Contains(ids) then dictionary Related data from another context or service Two round trips, simple Very large key sets (batch them)
AsSplitQuery() Multiple collection navigations One query per collection When you need a consistent snapshot without a transaction

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions lazy loading proxies as a cause Why: Checks they can debug the lazy-loading variant, including JSON cycles from returning entities
    How to answer

    Both symptoms come from serialising lazy-loading entities. System.Text.Json reads every public property; each virtual navigation triggers a SQL query on first access (N+1), and back-references such as Order.Customer.Orders form a cycle, so the serialiser throws ("A possible object cycle was detected") or goes very deep.

    I diagnose by counting SQL commands per request (EF Core command logging or Application Insights dependencies), then fix it properly: project to a DTO with Select so the response shape is explicit and EF Core sends one query, and turn lazy loading off (or make lazy loads throw) so it can't come back.

    Setting ReferenceHandler.IgnoreCycles stops the exception but leaves the dozens of queries in place.

  2. When: Candidate suggests adding Include for every navigation Why: Checks they know the over-correction leads to cartesian explosion and how split queries help
    How to answer

    Cartesian explosion happens when one query Includes two or more sibling collections: SQL returns one row per combination, so an order with 50 lines and 20 payments becomes 1,000 rows, each repeating the order's columns. EF Core logs a warning when it sees this.

    AsSplitQuery() makes EF Core send one root query plus one query per collection Include (orders; then lines joined to the same filtered orders; then payments) and stitch the results together in memory. For that order, rows transferred become 1 (root) + 50 (lines) + 20 (payments) = 71 instead of 1,000.

    The trade-offs: an extra round trip per collection (it adds up with network latency), and the statements are not one consistent snapshot unless you wrap them in a transaction with snapshot isolation. Often the better answer is a projection that loads only what's needed.

  3. When: Candidate mentions projecting into DTOs Why: Checks they understand the SQL and tracking difference between Include and Select
    How to answer

    For read-only endpoints I project with Select into a DTO. Include loads whole entities: every column of the root and of each included table, all materialised and (by default) tracked. A projection makes EF Core select only the columns the DTO references, turns o.Lines.Count() or Sum into SQL subqueries, and returns DTOs that are never tracked, so there's no snapshot cost.

    • Navigations used inside Select are joined automatically; no Include is needed (and Include is ignored there).
    • Include is still right when I load an aggregate to modify and save it, because I need tracked entities.

    The trade-off: projection means writing a DTO per use case, in exchange for less I/O, less memory and no tracking.

🛠 Real-world problems: how you handle them

Order history page making 201 queries per request
Situation
A customer portal on ASP.NET Core and EF Core against Azure SQL [in Australia East]. The order history endpoint served [about 40 requests per second] at peak. A recent change returned customer and address details with each order.
Signals
p95 latency for the endpoint rose from [about 120 ms] to [about 900 ms]; Azure SQL CPU and DTU climbed; Application Insights showed hundreds of SQL dependencies under each request; no errors.
Investigation
Opened an end-to-end transaction in Application Insights and saw the same parameterised `SELECT ... FROM Customers WHERE Id = @p` repeated for each order. Reproduced locally with `LogTo` and confirmed lazy loading proxies firing while System.Text.Json serialised the entity graph. Counted commands with a test interceptor: 201 for 100 orders.
Resolution
Immediately: limited the page size to bring the query count down. Real fix: replaced the entity return with a `Select` projection into an `OrderSummary` DTO, giving one query, and removed `UseLazyLoadingProxies()` from the API context.
Prevention
Added an integration test with a command-counting `DbCommandInterceptor` asserting at most 2 queries for the endpoint; an Application Insights alert on SQL dependency count per request; a review checklist item to never return entities from controllers.

How to tell it (STAR)

**S:** Our order history page in [the customer portal] went from about [120 ms] to [900 ms] at p95 after a release, and the database CPU climbed with it. **T:** I was asked to find the cause before the [end-of-month] traffic peak. **A:** In Application Insights I opened a slow request and saw about 200 near-identical SQL calls under one operation. Locally, EF Core logging showed lazy loading firing for every order's customer and address while the JSON serialiser walked the entities. I replaced the entity response with a DTO projection, which produced one query, turned lazy loading off for the API, and added an integration test that fails if the endpoint runs more than two queries. **R:** p95 dropped to around [60 ms], SQL load for that endpoint fell by roughly [two thirds], and the query-budget test has since caught [two] similar regressions in review.

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me