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

📚 Interview question

Your ASP.NET Core API uses EF Core with lazy loading proxies. One endpoint returns entities directly and now either throws a JSON 'possible object cycle' exception or runs dozens of SQL queries per request. How do you diagnose and fix it?

Covers diagnosing lazy-loading N+1 queries and serialisation cycles in an ASP.NET Core API with EF Core: SQL logging, Application Insights, the System.Text.Json cycle error, and fixing with DTO projection, explicit loading strategy and turning lazy loading off.

Mid-Level Debugging Intermediate aspnet-core debugging ef-core json-serialisation lazy-loading n-plus-one

🎯 Key points

  • Lazy proxies run a query on each first navigation access, including from the serialiser
  • System.Text.Json walks every public property: navigations trigger loads and cycles (order -> customer -> orders)
  • Diagnose: count commands per request in EF logs / Application Insights dependencies, or a DbCommandInterceptor counter
  • ReferenceHandler.IgnoreCycles hides the symptom, not the N+1
  • Fix: return DTOs from a Select projection, never entities
  • DTOs are the API contract: no leaked internal fields, entity changes don't break clients, versioning is explicit
  • Turn lazy loading off (or ConfigureWarnings to throw on lazy load) and load explicitly
  • Prevent: integration tests asserting query count per endpoint

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

🗣 Full answer (senior)

How I would answer this in an interview

"When I see a JSON cycle error and a high query count on the same endpoint, I suspect the controller is returning EF Core entities with lazy loading on. The proxy overrides each virtual navigation getter so that the first read runs a query. The serialiser reads every public property, so serialising 50 orders touches order.Customer, then customer.Orders, then each of those orders' Lines, and so on. That's one query per navigation per entity, and because Customer.Orders points back to orders, System.Text.Json either detects the cycle and throws, or walks until it hits the max depth of 64.

For example, at [company] our [order history endpoint] started timing out after someone added a Customer.Orders navigation for another feature. To diagnose, I turned on Microsoft.EntityFrameworkCore.Database.Command logging locally and counted [~150] commands for one request; in Application Insights the end-to-end transaction view showed the same fan-out of SQL dependencies. I put a breakpoint in a small DbCommandInterceptor that counted commands, and the stack traces all went through the JSON serialiser into the proxy getters.

The quick fix people reach for is ReferenceHandler.IgnoreCycles. It stops the exception, but the queries still run and the payload still leaks fields like internal notes. The real fix was a DTO projection with Select, so EF Core generated one query with exactly the fields the client needed, and then turning lazy loading off for the API context so a future navigation can't do the same. [p95 went from ~2.5 s to ~80 ms.] My rule: an API should never serialise entities."


Diagnosis steps

Step Tool What you look for
1 EF Core command logging (LogTo, log category Database.Command) Many near-identical SELECT ... WHERE [Id] = @p
2 Application Insights transaction view Dozens of SQL dependencies under one request
3 DbCommandInterceptor counter or MiniProfiler Exact command count per request
4 Stack trace at a command Proxy getter called from System.Text.Json
5 Exception message JsonException: A possible object cycle was detected

Fix options

Option Fixes N+1 Fixes cycle Recommended
ReferenceHandler.IgnoreCycles No Yes (drops the back-reference) Only as a stopgap
[JsonIgnore] on navigations Partly Yes No: couples entities to JSON
Include the needed navigations Yes No Not for API responses
DTO projection with Select Yes Yes Yes
Turn lazy loading off Prevents recurrence n/a Yes

Production example

After one navigation was added, an order history endpoint went from [3] to [~150] queries per request and p95 rose to [~2.5 s]. Projecting to a DTO and disabling lazy loading brought it to [1 query and ~80 ms], and the response stopped exposing [internal customer notes].

🔍 What the interviewer is checking

Checks that the candidate can trace a symptom to lazy loading plus serialisation and fixes the cause, not the exception.

Green flags

  • Explains how the serialiser triggers proxy getters.
  • Measures query count per request with real tools.
  • Recognises IgnoreCycles as hiding the problem.
  • Fixes with DTO projection and disables lazy loading.

Red flags

  • Only adds [JsonIgnore] or IgnoreCycles.
  • Doesn't know lazy loading is involved.
  • Suggests Include everything and keep returning entities.

📚 Learn in depth

1. How lazy loading proxies work

UseLazyLoadingProxies()
  └ at model build: Castle DynamicProxy creates OrderProxy : Order
       override Customer { get { _loader.Load(this, "Customer"); return base.Customer; } }

first access  -> ILazyLoader.Load -> SELECT ... WHERE [c].[Id] = @id
later access  -> IsLoaded == true -> no query

The loader needs the context that materialised the entity. After the scope ends you get an exception (or a warning, depending on configuration) instead.

2. How the serialiser triggers it

JsonSerializer.Serialize(orders)
  for each order:
     write Id, Number ...
     read order.Customer         -> query #1
        write customer fields
        read customer.Orders     -> query #2 (all orders of that customer)
           for each of those orders: read order.Customer -> already loaded -> CYCLE
     read order.Lines            -> query #3
        for each line: read line.Product -> query #4..n

System.Text.Json defaults to throwing on a cycle (ReferenceHandler null, MaxDepth 64). Newtonsoft.Json had ReferenceLoopHandling.Ignore, which is why older projects hid this for years.

3. Why it's worse in production

  • Each query is a round trip (~1 ms in-region, more under load); 150 of them is 150 ms minimum before any work.
  • They run sequentially on the request thread.
  • Data volume grows, so collections fetched by lazy loads grow too.
  • With ASP.NET Core output buffering, the serialiser runs while the scope (and context) are still alive, so it "works" until it doesn't.

4. Detecting lazy loads explicitly

options.ConfigureWarnings(w => w.Throw(CoreEventId.LazyLoadOnDisposedContextWarning));
// In tests, count commands with an interceptor and assert an upper bound.

You can also stop lazy loading per context instance with db.ChangeTracker.LazyLoadingEnabled = false.

5. Why DTOs fix both problems

Select(o => new OrderDto(o.Id, o.Number, o.Customer.Name, o.Lines.Count()))
   -> one SQL statement, joins and subqueries
   -> result objects have no navigations, so no proxies and no cycles
   -> the API contract no longer changes when the entity model changes

Try it yourself

  1. Enable lazy loading, return List<Order> from a controller and count commands in the log.
  2. Add a Customer.Orders navigation and reproduce the JsonException.
  3. Set ReferenceHandler.IgnoreCycles and confirm the query count is unchanged.
  4. Write a DbCommandInterceptor that counts commands per request and logs it.
  5. Replace the action with a DTO projection and compare commands and payload size.

💻 Code

Before: entities with lazy loading. After: DTO projection, lazy loading off, and a command-count test.

// BEFORE: every navigation the serialiser touches is a query; Customer.Orders creates a cycle.
[HttpGet("customers/{id:int}/orders")]
public async Task<List<Order>> GetOrders(int id, CancellationToken ct) =>
    await db.Orders.Where(o => o.CustomerId == id).ToListAsync(ct);
namespace Shop.Api.Orders;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public sealed record OrderLineDto(string Product, int Quantity, decimal UnitPrice);
public sealed record OrderDto(int Id, string Number, string CustomerName, IReadOnlyList<OrderLineDto> Lines);

[ApiController]
[Route("customers/{id:int}/orders")]
public sealed class CustomerOrdersController(ShopDbContext db) : ControllerBase
{
    // AFTER: explicit shape, one SQL statement, nothing lazy, no cycle.
    [HttpGet]
    public async Task<IReadOnlyList<OrderDto>> Get(int id, CancellationToken ct) =>
        await db.Orders
            .Where(o => o.CustomerId == id)
            .OrderByDescending(o => o.PlacedAt)
            .Select(o => new OrderDto(
                o.Id,
                o.Number,
                o.Customer.Name,
                o.Lines.Select(l => new OrderLineDto(l.Product.Name, l.Quantity, l.UnitPrice)).ToList()))
            .Take(50)
            .ToListAsync(ct);
}
// Program.cs: no proxies in the API context.
builder.Services.AddDbContext<ShopDbContext>(o => o
    .UseSqlServer(builder.Configuration.GetConnectionString("Shop")));
// (Removed: .UseLazyLoadingProxies())

// Test helper: count SQL commands so a regression fails CI.
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 base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
    }
}

⚠ Common mistakes

  • Mistake: Returning EF Core entities from API actions. Why it is wrong: the serialiser triggers lazy loads, follows cycles and leaks fields you didn't mean to expose; any entity change silently changes the public contract. Instead: return DTOs built with Select, so the API model is separate from the persistence model and can be versioned on its own.
  • Mistake: Fixing the cycle with ReferenceHandler.IgnoreCycles and stopping there. Why it is wrong: the N+1 queries still run. Instead: treat it as a stopgap and project to DTOs.
  • Mistake: Sprinkling [JsonIgnore] on entity navigations. Why it is wrong: it couples the domain model to one serialiser and still hides the real problem. Instead: keep entities out of the API contract.
  • Mistake: Turning lazy loading on by default "for convenience". Why it is wrong: every navigation access becomes a hidden query. Instead: keep it off in web apps; load explicitly.
  • Mistake: Diagnosing by reading code only. Why it is wrong: the query fan-out is hidden in proxy getters. Instead: count commands with logging, Application Insights or an interceptor.
  • Mistake: Relying on unit tests with mocked repositories or the in-memory provider. Why it is wrong: they never execute SQL, so N+1 and lazy loads are invisible. Instead: integration tests with WebApplicationFactory against real SQL Server (Testcontainers), realistic related data, and an assertion on the maximum command count per endpoint.
  • Mistake: Testing with a tiny dataset. Why it is wrong: 3 orders × 2 navigations looks fine. Instead: seed realistic fan-out (dozens of children per parent) in performance-sensitive tests.

🏛 Senior insight: trade-offs

This is less an EF Core bug than a contract design problem: the API exposed the persistence model. DTO projections fix performance, cycles and data leakage at once, and they make the API independent of entity changes. I also make the failure loud: lazy loading off for web contexts and a query-count assertion in integration tests.

Option When it fits Cost When not to
DTO projection All API responses DTO per endpoint Never a bad default for reads
Include + entity response Internal tools, quick prototypes Over-fetching, contract coupling Public or high-traffic APIs
Lazy loading Desktop apps, long-lived contexts Hidden N+1, AOT incompatible Web APIs
IgnoreCycles Emergency stopgap Queries still run As the permanent fix

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions turning lazy loading off and loading explicitly. Why: Checks knowledge of the alternative loading strategies.
    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 proposes DTO projection. Why: Checks they understand what projection changes in SQL and tracking.
    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

New navigation property turned an endpoint into 150 queries
Situation
An [order management] API on Azure SQL, with lazy loading proxies enabled since [the project started], served an order history endpoint used by [the mobile app]. A developer added `Customer.Orders` for a different feature.
Signals
After the release, p95 for `GET /customers/{id}/orders` rose from [~120 ms] to [~2.5 s]; some requests failed with `JsonException: A possible object cycle was detected`; Application Insights showed [100–200] SQL dependencies per request; Azure SQL DTU usage climbed.
Investigation
Opened an example request in the Application Insights end-to-end transaction view and saw a fan-out of `SELECT ... WHERE [Id] = @p` calls. Reproduced locally with command logging and a counting `DbCommandInterceptor`; a breakpoint in the interceptor showed stacks from `System.Text.Json` into proxy getters. Compared the release diff and found the new back-reference navigation.
Resolution
Immediate: rolled forward with `ReferenceHandler.IgnoreCycles` to stop the errors. Real fix: replaced entity responses with DTO projections on [the affected endpoints], then removed `UseLazyLoadingProxies()` from the API context after fixing the [few] places that relied on it.
Prevention
Integration tests assert a maximum SQL command count per endpoint; an architecture test fails if a controller returns a type from the entities namespace; dashboards on SQL dependency count per request; a checklist item for new navigations.

How to tell it (STAR)

**S:** At [company], our order history endpoint jumped from [120 ms] to [2.5 s] p95 right after a release, and some calls failed with a JSON cycle error. **T:** As [the on-call engineer] I had to stop the errors and find the cause. **A:** Application Insights showed about 150 SQL calls per request. I reproduced it with a command-counting interceptor and saw the serialiser walking lazy-loaded navigations, including a new back-reference from customer to orders. I shipped `IgnoreCycles` as a stopgap, then replaced entity responses with DTO projections and turned off lazy loading in the API. **R:** The endpoint went to [one query and ~80 ms], we stopped leaking [internal fields], and query-count tests have caught [two] similar regressions since.

↩ Usually asked after

More in Querying

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me