Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson3 / 9

    EF Core Query Performance and N+1 Diagnosis

    Diagnose before reading

    A dashboard executes one order query and then repeatedly selects a customer by ID. A proposed fix adds AsNoTracking() without changing the navigation loop. Predict whether that change alone removes the repeated commands. Choose the measurements you would collect before changing query shape.

    Write your answer first. Then use this trace to check the boundary you chose.

    EvidenceWhat it supportsWhat it does not establish
    Repeated customer commands during navigation accessA possible lazy/explicit-loading N+1 patternExactly one extra command per order when customers can be shared or already loaded
    One projected command with required columnsA bounded candidate read modelA faster plan on every provider/data distribution
    Split queries for included collectionsA deliberate alternative to duplicated joined rowsN+1 merely because command count exceeds one
    Low command time but slow requestInvestigate uncovered waits/materialization/response sizeA database root cause from the endpoint duration alone

    Recognizing N+1 queries

    N+1 occurs when code loads a list and then issues one additional query per item, often through explicit or lazy loading.

    C#
    var orders = await db.Orders
        .Where(o => o.CreatedAt >= from)
        .ToListAsync(token);
    
    foreach (var order in orders)
    {
        Console.WriteLine(order.Customer.Name);
    }

    If lazy loading is enabled and the navigation has not already been loaded or populated through tracking/fix-up, accessing Customer can cause additional queries, potentially one per order. Shared/already-loaded related entities may reduce the actual count. The visible symptom is usually many nearly identical commands with different parameter values.

    Instrument first

    Enable command logging in a safe environment and use structured observability in production. Record request route, trace ID, command duration, and a normalized query identifier. Do not log sensitive parameter values by default; query text, tags and exception messages can also contain sensitive literals or identifiers. Apply appropriate redaction, access and retention controls. Add a DbCommandInterceptor or OpenTelemetry instrumentation to count database commands per request. A sudden endpoint query-count increase can suggest N+1, but retries and intentional split queries also raise counts. Correlate commands with requests and inspect the calling pattern.

    During local diagnosis, call ToQueryString() on an IQueryable for a debugging representation without executing it. It is not necessarily the exact command later executed, especially after terminal operators or query-shape changes; confirm actual commands in logs/interceptors. In a profiler, look for repeated commands. At the database, inspect the actual execution plan and logical reads for the representative query.

    Projection is usually the default read model

    If the endpoint returns a summary, project only required columns.

    C#
    var rows = await db.Orders
        .Where(o => o.CreatedAt >= from)
        .OrderByDescending(o => o.CreatedAt)
        .ThenByDescending(o => o.Id)
        .Select(o => new OrderSummary(
            o.Id,
            o.Customer.Name,
            o.Total,
            o.Items.Count))
        .Take(100)
        .AsNoTracking()
        .ToListAsync(token);

    Projection often translates navigation access and aggregates into one SQL query. It avoids materializing full entities and large unused columns. Verify actual commands and results because translation details depend on provider and model. These snippets assume application-defined Order, OrderSummary constructors and variables. A scalar-only DTO projection contains no entities to track, so AsNoTracking() is redundant there; a projection that contains entity instances can still track them by default.

    Include is not a universal fix

    Include eagerly loads related entities, but including sibling collections can create a cartesian explosion in a single joined query. If an order has ten items and five adjustments, a single joined result can repeat order data fifty times. The database may return far more rows than the object graph contains.

    AsSplitQuery asks EF Core to load included collections using multiple SQL queries. It can reduce duplicated rows but adds round trips and has consistency considerations if data changes between queries. Use it deliberately and measure. AsSingleQuery requests a single query for the related graph; it can be expensive for wide sibling-collection graphs. A split query is not N+1 by definition: its query count normally follows the included collection shape, not one query per parent.

    For API read models, projection often avoids unnecessary data, but measure rather than assuming it wins. Use Include when you need related entities; both tracked update graphs and no-tracking read-only graphs can be legitimate.

    Tracking choices

    Tracking allows SaveChanges to detect modifications and provides identity resolution. Tracking has overhead, but identity resolution can avoid duplicate entity materialization, so no-tracking is not always faster or smaller. Consider AsNoTracking for read-only entity queries and measure the relevant shape. If a no-tracking graph contains repeated entity references and you need reference identity, AsNoTrackingWithIdentityResolution can help, but it has its own allocation cost.

    Do not add AsNoTracking to a query whose entities will be modified later without understanding attach/update semantics. Performance advice must preserve correctness.

    Pagination

    Offset pagination with Skip and Take becomes expensive at large offsets because the database still locates and discards earlier rows. Prefer keyset pagination for sequential feeds and stable ordered lists when suitable; it does not directly support jumping to an arbitrary page number. The example assumes an integral long key and matching cursorId, a non-null timestamp, and a validated bounded positive pageSize.

    C#
    var page = await db.Orders
        .Where(o => o.CreatedAt < cursorTime ||
            (o.CreatedAt == cursorTime && o.Id < cursorId))
        .OrderByDescending(o => o.CreatedAt)
        .ThenByDescending(o => o.Id)
        .Select(o => new OrderSummary(o.Id, o.Customer.Name, o.Total))
        .Take(pageSize)
        .AsNoTracking()
        .ToListAsync(token);

    The ordering must be unique and the cursor must include every ordering component. Consider a matching composite index and verify the provider's translated predicate and plan. For other key types, use a translatable comparison consistent with the database ordering. Keyset pagination is not a snapshot: concurrent changes to ordering values can still move rows across page boundaries.

    Indexes and query shape

    An ORM does not remove the need to evaluate database access paths. An index is not always the best plan: small tables or low-selectivity scans may be appropriate. Derive indexes from actual predicates, joins, and ordering. Avoid wrapping indexed columns in functions when it prevents index seeking. Inspect parameterization and cardinality estimates. When performance depends on a filtered or provider-specific index, manage it explicitly in migrations and document the workload it supports.

    Compiled queries

    EF Core caches query compilation internally. Explicit compiled queries bypass repeated query-cache lookup and can help hot, stable query shapes when that overhead is measurable; ordinary cached queries already reuse their compiled plan. Their restrictions include a single EF model and supported scalar parameters. They do not fix slow SQL, excessive rows, missing indexes, or network latency. Benchmark before adding complexity.

    Client evaluation and premature materialization

    Calling ToList too early moves later filtering to memory and may load an entire table. Keep the expression as IQueryable until the final terminal operation. Cross intentionally into client-side processing only when the data volume is understood and bounded. AsEnumerable() changes how subsequent LINQ operators bind but does not itself materialize or execute the query; enumeration does. EF Core generally rejects untranslatable expressions outside the top-level projection rather than silently evaluating the whole query on the client.

    C#
    var query = db.Orders.Where(o => o.Status == status);
    if (minimumTotal is not null)
        query = query.Where(o => o.Total >= minimumTotal);
    
    var result = await query
        .OrderByDescending(o => o.CreatedAt)
        .ThenByDescending(o => o.Id)
        .Select(o => new OrderSummary(o.Id, o.Customer.Name, o.Total))
        .Take(100)
        .AsNoTracking()
        .ToListAsync(token);

    Write-path concerns

    Do not run multiple parallel operations on the same DbContext; it is not thread-safe. For bulk inserts/imports, batch work, keep change tracking bounded and assess provider-appropriate insert facilities. ExecuteUpdate/ExecuteDelete are set-based update/delete APIs, not insert APIs. They execute immediately, bypass tracked entity state and SaveChanges, and do not automatically group separate calls in one transaction. Account explicitly for domain rules, stale tracked instances, concurrency checks and any transaction spanning multiple operations. SaveChanges in a loop usually creates avoidable round trips and fragmented transactions.

    Diagnosis playbook

    1. Reproduce with representative data volume.
    2. Capture query count and normalized SQL.
    3. Measure command time, rows returned, and response size.
    4. Inspect generated SQL and the actual database plan.
    5. Decide whether projection, Include, or split queries match the required shape.
    6. Add or correct indexes based on predicates and ordering.
    7. Bound results with keyset pagination when appropriate.
    8. Load test the endpoint and compare p50, p95, and database reads.
    9. Add a regression test or telemetry threshold for command count.

    Interview scenario

    A dashboard endpoint is fast with ten customers but times out with ten thousand. It loads customers, their latest five orders, and total spend. A strong answer first verifies whether one query is issued per customer, then proposes a set-based projection or window-function-capable query, bounds the result, checks indexes, and compares SQL plans. It also asks whether the dashboard needs all customers synchronously or a precomputed aggregate.

    Check the boundary

    A projection returns only scalar values in an OrderSummary, with no entity instance anywhere in the result. What is the role of AsNoTracking() on that query?

    A It prevents tracking of those DTOs; otherwise EF tracks every DTO.
    B It changes a lazy-loading loop into a join.
    C It guarantees the query uses an index seek.
    D It is redundant for tracking in that entity-free result; still inspect SQL, result shape and performance.
    Show answer

    Correct answer: D

    EF tracks entity instances, not arbitrary scalar-only DTOs. AsNoTracking cannot repair query shape, create indexes or guarantee a faster execution plan.

    Hint: Ask whether an entity instance is actually materialized into the projection.

    Two-minute interview practice

    Attempt both before comparing. State the assumption, the repair and one limit of your evidence.

    1. Ten orders share one already-loaded customer. Is exactly eleven commands a safe prediction?
    2. A descending feed orders by CreatedAt and Id. What must the cursor contain, and which concurrent change can still move a row?

    Hint. Revisit the ownership, time, transaction or measurement boundary in the trace table.

    Check your reasoning.

    1. No. Tracking fix-up or an already-loaded shared customer can reduce extra loads. Count actual commands and inspect their call sites.
    2. Include both ordering components and use a predicate consistent with both directions. A unique order avoids tie ambiguity, but an update to CreatedAt can still move a row across the cursor boundary; keyset pagination is not a snapshot.

    Evidence for the repair

    Measure commands per request and representative SQL/rows/latency before and after. Keep tenant authorization and returned data identical. A shorter application stopwatch alone does not establish the database access path.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·