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

📚 Interview question

What is cartesian explosion in EF Core, and how do split queries help? Explain what AsSplitQuery() changes in the SQL, the consistency and round-trip trade-offs, and how you decide between single queries, split queries and projection.

Covers cartesian explosion from multiple collection Includes, how AsSplitQuery() and UseQuerySplittingBehavior change the generated SQL, consistency and ordering caveats, round-trip costs, and choosing between single, split and projected queries.

Mid-Level Theory Intermediate cartesian-explosion ef-core include performance split-queries sql-server

🎯 Key points

  • Sibling collection Includes multiply rows: a × b per parent, root columns duplicated
  • EF Core warns (MultipleCollectionIncludeWarning) when it detects this without a splitting choice
  • AsSplitQuery(): one root query plus one query per collection Include, stitched in memory
  • Global default: UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); AsSingleQuery() per query
  • Each extra statement costs a round trip: ~1 ms in-region, far more cross-region
  • Split queries are not a consistent snapshot without a snapshot-isolation transaction
  • Paging with split queries needs a unique, stable OrderBy
  • Measure with statement count in EF logs and rows/duration in Query Store; projection often beats both

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

🗣 Full answer (senior)

How I would answer this in an interview

"When I Include a collection, EF Core adds a LEFT JOIN, so each parent appears once per child. That's fine for one collection. With two sibling collections, say order.Lines and order.Payments, the SQL can only express it as a join of both, so every line is paired with every payment. Fifty lines and twenty payments give a thousand rows for one order, each carrying the order's columns again. Across a page of orders that can be hundreds of thousands of rows for data that is really a few thousand. EF Core detects this and logs MultipleCollectionIncludeWarning if you haven't chosen a splitting behaviour.

AsSplitQuery() changes the strategy: EF Core runs the root query, then one query per collection that re-applies the same filter and ordering and joins to the root to fetch only the children, and it fixes the objects up in memory. Rows go from multiplied to added. I can set it globally with UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) and opt back in per query with AsSingleQuery().

It isn't free. Each collection is an extra round trip, which hurts when latency to Azure SQL is high, and the queries run at different moments, so with the default read-committed isolation a concurrent write can make the lines and payments disagree. If I need a consistent picture I wrap them in a transaction with snapshot isolation. Paging also needs a unique, stable OrderBy, otherwise the child queries can pick different parents. The mistake I see is turning on split queries globally and calling it solved. Usually the real fix is a projection that fetches the line count and payment total, not every row. Split queries are for when I genuinely need the full graph."


Single versus split

Single query (default) Split query
SQL statements 1 1 + one per collection Include
Rows for 1 order, 50 lines, 20 payments 1,000 1 + 50 + 20
Duplicated root columns Yes No
Consistency One statement, consistent Separate statements; needs a transaction for a snapshot
Round trips 1 N
Paging Straightforward Needs unique ordering

How to choose

Situation Choice
One collection Include, small children Single query
Two or more collection Includes, many children Split query
Read endpoint needing aggregates or a few fields Projection
High latency to the database, small collections Single query
Must see a consistent snapshot of the graph Split inside a snapshot-isolation transaction, or single query

Configuring it

API Scope
.AsSplitQuery() One query
.AsSingleQuery() One query, overriding a global split default
UseSqlServer(cs, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)) Context-wide default

Production example

A customer dashboard included orders, addresses and contacts for each account. One account with [300 orders, 4 addresses and 6 contacts] returned [7,200] rows and took [~2.5 s]. AsSplitQuery() brought it to [310 rows across three queries and ~180 ms]; a later projection for the dashboard summary got it to [~40 ms].

🔍 What the interviewer is checking

Checks that the candidate understands why multiple collection Includes explode, how split queries change the SQL, and their trade-offs.

Green flags

  • Explains the multiplication with numbers.
  • Names AsSplitQuery(), the global setting and AsSingleQuery().
  • Mentions consistency and unique ordering for paging.
  • Prefers projection where possible.

Red flags

  • "Always use split queries."
  • Unaware of consistency or round-trip costs.
  • Thinks split queries reduce the columns loaded.

📚 Learn in depth

1. Why joins multiply

Relational results are flat. Representing a parent with two independent child sets in one result needs every pairing:

Order 1 ─┬─ Lines   L1..L50
        └─ Payments P1..P20

Single query rows for Order 1:
(O1, L1, P1) (O1, L1, P2) ... (O1, L50, P20)   = 50 × 20 = 1,000 rows

Nested collections (Lines.ThenInclude(l => l.Allocations)) multiply too, but only along one path; sibling collections are the classic explosion.

2. The SQL

Single query (simplified):

SELECT o.*, l.*, p.*
FROM Orders o
LEFT JOIN OrderLines l ON o.Id = l.OrderId
LEFT JOIN Payments p   ON o.Id = p.OrderId
WHERE o.CustomerId = @c
ORDER BY o.Id, l.Id, p.Id

Split query:

SELECT o.* FROM Orders o WHERE o.CustomerId = @c ORDER BY o.Id;

SELECT l.*, o.Id FROM Orders o
INNER JOIN OrderLines l ON o.Id = l.OrderId
WHERE o.CustomerId = @c ORDER BY o.Id;

SELECT p.*, o.Id FROM Orders o
INNER JOIN Payments p ON o.Id = p.OrderId
WHERE o.CustomerId = @c ORDER BY o.Id;

Each child query repeats the root filter, so the root predicate must be cheap and indexed; otherwise you pay for it N times.

3. Consistency

T0  query 1 reads Orders
T1  another transaction inserts a Line and commits
T2  query 2 reads Lines   -> sees the new line

Under READ COMMITTED (the default, or RCSI on Azure SQL), each statement sees its own moment. To get one snapshot, run the split queries inside BeginTransactionAsync(IsolationLevel.Snapshot) (requires ALLOW_SNAPSHOT_ISOLATION ON).

4. Paging and ordering

With Skip/Take, each child query re-applies the paging. If the OrderBy is not unique (e.g. PlacedAt only), ties may order differently between queries and children can attach to the wrong page. Always end with a unique key: OrderBy(o => o.PlacedAt).ThenBy(o => o.Id).

5. Buffering

With split queries on SQL Server without MARS, EF Core buffers earlier results so it can run the next command on the same connection. That costs memory for large result sets; streaming large graphs is a sign you need a different approach.

6. Cost model

single:  1 round trip + rows(∏ collections) × width
split:   (1 + k) round trips + rows(∑ collections) × width + k × root filter cost

At [~1 ms] round trip within an Azure region, extra trips are cheap; across regions or from a laptop, they dominate.

Try it yourself

  1. Seed one order with 50 lines and 20 payments. Run the double Include and count rows with SET STATISTICS IO ON or a profiler.
  2. Add AsSplitQuery() and read the three statements in the log.
  3. Look for the MultipleCollectionIncludeWarning in the logs before choosing a behaviour.
  4. Page with OrderBy(o => o.PlacedAt).Skip(20).Take(10) using duplicate dates; then add ThenBy(o => o.Id).
  5. Rewrite the query as a projection with counts and sums and compare duration and rows.

💻 Code

Single, split and projected versions of the same request.

namespace Shop.Orders;

using System.Data;
using Microsoft.EntityFrameworkCore;

public sealed record OrderSummary(int Id, int LineCount, decimal Paid);

public sealed class OrderGraphQueries(ShopDbContext db)
{
    // Explodes: Lines × Payments rows per order.
    public Task<List<Order>> SingleAsync(int customerId, CancellationToken ct) =>
        db.Orders.AsNoTracking()
          .Where(o => o.CustomerId == customerId)
          .Include(o => o.Lines)
          .Include(o => o.Payments)
          .ToListAsync(ct);

    // Split: 3 statements, rows add instead of multiply. Unique ordering for safe paging.
    public Task<List<Order>> SplitPageAsync(int customerId, int page, CancellationToken ct) =>
        db.Orders.AsNoTracking()
          .Where(o => o.CustomerId == customerId)
          .OrderByDescending(o => o.PlacedAt).ThenBy(o => o.Id)
          .Skip(page * 20).Take(20)
          .Include(o => o.Lines)
          .Include(o => o.Payments)
          .AsSplitQuery()
          .ToListAsync(ct);

    // Consistent split: all statements see one snapshot (needs ALLOW_SNAPSHOT_ISOLATION ON).
    public async Task<List<Order>> SplitConsistentAsync(int customerId, CancellationToken ct)
    {
        await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.Snapshot, ct);
        var orders = await db.Orders.AsNoTracking()
            .Where(o => o.CustomerId == customerId)
            .Include(o => o.Lines).Include(o => o.Payments)
            .AsSplitQuery()
            .ToListAsync(ct);
        await tx.CommitAsync(ct);
        return orders;
    }

    // Often best: only what the screen needs, one statement, no explosion.
    public Task<List<OrderSummary>> SummaryAsync(int customerId, CancellationToken ct) =>
        db.Orders
          .Where(o => o.CustomerId == customerId)
          .Select(o => new OrderSummary(o.Id, o.Lines.Count(), o.Payments.Sum(p => p.Amount)))
          .ToListAsync(ct);
}
// Program.cs: make split the default, opt out with AsSingleQuery() where a single statement is better.
builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(
    builder.Configuration.GetConnectionString("Shop"),
    sql => sql.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)));

⚠ Common mistakes

  • Mistake: Including several sibling collections in one query on large data. Why it is wrong: rows multiply and root columns repeat, so transfer and materialisation explode. Instead: split the query or project.
  • Mistake: Turning on split queries globally and never measuring. Why it is wrong: small graphs pay extra round trips for nothing. Instead: choose per query, or set a default and opt out with AsSingleQuery() where it's slower.
  • Mistake: Assuming split queries are a consistent snapshot. Why it is wrong: each statement sees its own moment under read committed. Instead: use a snapshot-isolation transaction when consistency matters.
  • Mistake: Paging a split query with a non-unique OrderBy. Why it is wrong: child queries may select different parents, attaching children to the wrong page. Instead: end the ordering with a unique key.
  • Mistake: Using split queries with an expensive root filter. Why it is wrong: the filter runs once per statement. Instead: make the root predicate indexed, or materialise root keys first.
  • Mistake: Ignoring the MultipleCollectionIncludeWarning in logs. Why it is wrong: it is EF Core telling you the query may explode. Instead: make an explicit choice and record why.

🏛 Senior insight: trade-offs

Split queries are a tool for loading full graphs, and most endpoints don't need full graphs. My order of preference is: project only what's needed, then single query for one collection, then split query when several collections are genuinely needed. The decision depends on data shape (children per parent), latency to the database and whether consistency matters.

I measure with rows returned and duration in Query Store, and with the EF Core log showing how many statements ran.

Option When it fits Cost When not to
Single query 0–1 collection Includes, or small collections Duplicated root data Several large sibling collections
Split query Full graph with several collections Extra round trips, no snapshot by default High-latency links, tiny collections
Projection Read endpoints, summaries DTO per use case When the full tracked graph is needed for updates
Separate explicit queries Very large graphs, streaming More code Simple screens

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Include and ThenInclude. Why: Checks basic loading strategies first.
    How to answer

    EF Core does not load navigation properties unless you ask. There are three ways:

    • Eager loading: Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().
    • Explicit loading: await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.
    • Lazy loading: with UseLazyLoadingProxies() and virtual navigations, the first access runs a query automatically.

    Filtered Include (EF Core 5+) lets you write Include(c => c.Orders.Where(o => o.IsOpen).OrderBy(o => o.PlacedAt).Take(5)).

    The trade-off: eager is predictable, explicit is precise, lazy is convenient but hides N+1 queries.

  2. When: Candidate mentions wrapping split queries in a transaction for consistency. Why: Checks understanding of isolation levels behind consistency claims.
    How to answer

    New Azure SQL Database databases have READ_COMMITTED_SNAPSHOT (RCSI) on by default (on-premises SQL Server doesn't; check is_read_committed_snapshot_on in sys.databases for your database). With RCSI each statement reads a consistent committed version without blocking writers. For several statements to see the same version, use IsolationLevel.Snapshot (needs ALLOW_SNAPSHOT_ISOLATION ON). The cost is the row-version store (tempdb, or the persistent version store when accelerated database recovery is on, as it always is in Azure SQL Database), a 14-byte versioning tag added to modified rows, and update conflicts (error 3960) under snapshot that you must retry.

🛠 Real-world problems: how you handle them

Account dashboard timed out from a cartesian explosion
Situation
A [B2B portal] on Azure SQL loaded an account with its orders, addresses and contacts for the account dashboard. Most accounts were small, but [a few large customers] had hundreds of orders.
Signals
Timeouts reported only by [the largest customers]; Application Insights showed the dashboard dependency taking [2–5 s] with [~7,000] rows returned; EF Core logs contained `MultipleCollectionIncludeWarning`.
Investigation
Reproduced with the largest account in a staging copy; `ToQueryString()` showed three collection `LEFT JOIN`s; rows returned = orders × addresses × contacts. The execution plan had a large hash join and a sort on the combined keys, spilling to tempdb.
Resolution
Immediate: added `AsSplitQuery()` to the dashboard query, cutting rows to the sum of the collections. Real fix: the dashboard only showed counts and the five latest orders, so it was rewritten as a projection with a filtered sub-select; the full graph is loaded only on the edit screen, with split queries.
Prevention
Treat `MultipleCollectionIncludeWarning` as an error in development (`ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning))`); performance tests use the largest realistic account; Query Store alert on rows returned per execution.

How to tell it (STAR)

**S:** Our [B2B portal]'s account dashboard was timing out, but only for [our three largest customers]. **T:** I had to fix it quickly because [those accounts were most of our revenue]. **A:** I reproduced it in staging and saw one query including three collections, which turned [300 orders, 4 addresses and 6 contacts] into more than 7,000 rows. I switched it to a split query as a hotfix, then rewrote the dashboard as a projection because it only needed counts and the latest orders. I also made EF Core's multiple-collection warning throw in development. **R:** The dashboard went from [up to 5 s] to [~40 ms], and we haven't had a cartesian-explosion regression since.

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me