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

๐Ÿ“š Interview question

Code review: a monthly sales report method loads the whole Orders table with its lines into memory as tracked entities, groups and sums in LINQ to Objects, builds a CSV by concatenating strings in a loop, and runs inside a request with no timeout. What do you flag, in what order, and what does the rewrite look like?

A senior EF Core code review of a slow report: loading a whole table with Include and tracking, in-memory grouping instead of SQL aggregation, string concatenation, no streaming, no cancellation or timeout, ranked by severity with a rewrite.

Senior CodeReview Advanced code-review ef-core memory query-performance reporting streaming

๐ŸŽฏ Key points

  • Severity first: unbounded load of a whole table + lines can OOM the process and lock up the request
  • Push filtering and aggregation to SQL: Where on a month range, GroupBy with Sum/Count translates to GROUP BY
  • Network cost: millions of detail rows versus a few hundred aggregated rows
  • No tracking needed for reports: projection is untracked; AsNoTracking for entities
  • String concatenation in a loop is O(n^2) allocations: use a StreamWriter / StringBuilder
  • Stream the output: AsAsyncEnumerable + write to the response or a blob
  • CancellationToken, command timeout and moving long reports to a background job
  • Index for the month range; consider read scale-out replica or a pre-aggregated table

โฑ 30-second answer

Ranked by severity: (1) unbounded load: Include(o => o.Lines).ToListAsync() over the whole table brings millions of tracked entities into memory, risking OOM and long blocking; (2) aggregation in memory: grouping and summing in LINQ to Objects instead of letting SQL do GROUP BY ... SUM; (3) tracking a read-only report doubles memory; (4) string concatenation in a loop is O(nยฒ) allocations; (5) no CancellationToken, timeout or streaming, so a closed browser keeps the query running. The rewrite filters to the month, projects a GroupBy with Sum so SQL returns one row per group, streams rows with AsAsyncEnumerable into a StreamWriter, honours cancellation, and moves large exports to a background job writing to Blob Storage. The trade-off: SQL aggregation is far cheaper, but very large or complex reports may need a pre-aggregated table or read replica.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd rank findings by what can hurt production first. The worst problem is that it loads the whole Orders table with every line, as tracked entities, on a web request. Today that's [a few hundred thousand rows], next year it's millions; each request allocates hundreds of megabytes, the change tracker doubles it with snapshots, and two people running the report at once can push the pod into an out-of-memory kill. It also holds the connection and a long-running scan against the primary database.

The second finding is that the work belongs in SQL. The method filters by month and groups by product and region in LINQ to Objects after ToListAsync(). EF Core translates Where on a date range and GroupBy with Sum and Count into a single GROUP BY query, so SQL Server reads the month's rows using an index and returns one row per group, maybe a few hundred rows instead of millions. That alone takes it from [minutes] to [around a second] in my experience. Then the smaller items: tracking is pointless for a report, and a projection is untracked anyway; building the CSV with csv += line copies the whole string on every iteration; and there's no cancellation token or timeout, so if the user closes the tab, the query keeps going.

For example, at [company] a report like this [took the API down at month end] when [the finance team ran it in parallel]. I [rewrote it as a SQL aggregation streamed to the response, and moved the full-detail export to a background job writing to Blob Storage]. Memory per run went from [about 1.5 GB] to [under 50 MB]. I'd close the review with the unbounded load and in-memory grouping as blocking, and the rest as suggestions with a checklist item for reports."


Code under review

[HttpGet("reports/sales")]
public async Task<IActionResult> MonthlySales(int year, int month)                       // 5: no CancellationToken
{
    var orders = await db.Orders.Include(o => o.Lines).ToListAsync();                   // 1: whole table + lines, 3: tracked
    var rows = orders
        .Where(o => o.CreatedAt.Year == year && o.CreatedAt.Month == month)              // 2: filter in memory
        .SelectMany(o => o.Lines.Select(l => new { o.Region, l.ProductId, l.Quantity, l.UnitPrice }))
        .GroupBy(x => new { x.Region, x.ProductId })                                     // 2: aggregation in memory
        .Select(g => new { g.Key.Region, g.Key.ProductId, Units = g.Sum(x => x.Quantity),
                           Revenue = g.Sum(x => x.Quantity * x.UnitPrice) });

    var csv = "Region,ProductId,Units,Revenue\n";
    foreach (var r in rows) csv += $"{r.Region},{r.ProductId},{r.Units},{r.Revenue}\n";  // 4: O(n^2) concatenation
    return File(Encoding.UTF8.GetBytes(csv), "text/csv", "sales.csv");                   // 6: whole file buffered
}

Findings by severity

# Severity Finding Fix
1 Crash / stall Unbounded load of all orders and lines into memory Filter in SQL to the month; never ToList a whole table
2 Stall / cost Filtering and grouping in LINQ to Objects Where on a date range + GroupBy with Sum in the query
3 Waste Tracked entities for a read-only report Projection (untracked) or AsNoTracking()
4 Waste csv += in a loop: O(nยฒ) copying, LOH allocations Write to a StreamWriter
5 Reliability No CancellationToken, no command timeout, runs on the request path Pass ct; set a timeout; long exports become background jobs
6 Diagnostics / design Whole file buffered; no query tag; CSV values not escaped Stream the response; TagWith; escape CSV fields (and guard against formula injection)

The rewrite

See the code example: a translated aggregation with a sargable month range, streamed with AsAsyncEnumerable into the response body, cancellable, tagged, with CSV escaping.

How I'd close the review

  • Blocking: findings 1 and 2 (memory and database load), and 5 for the missing cancellation on a long query.
  • Suggested: 3, 4 and 6, plus moving full-detail exports to a background job that writes to Blob Storage and emails a link.
  • Follow-up: an index on (CreatedAt) INCLUDE (Region) and on OrderLines (OrderId) INCLUDE (ProductId, Quantity, UnitPrice); consider a read replica (Business Critical read scale-out) for reporting.
  • Checklist: reports must aggregate in SQL, stream output, take a CancellationToken and have a row or time budget.

Production example

A month-end sales report [in a system I worked on] built this way took about 4 minutes and 1.5 GB per run on [600,000] orders; three finance users running it together caused an OOM restart. The rewritten version returned [about 900] grouped rows in about 1.2 seconds using under 50 MB.

๐Ÿ” What the interviewer is checking

Checks that the candidate can rank performance and reliability risks in EF Core code, push work to SQL correctly, stream output, and see the architectural question behind reporting.

Green flags

  • Ranks the unbounded load and in-memory aggregation first
  • Knows which GroupBy shapes translate to SQL
  • Removes tracking and uses a sargable date range
  • Streams with AsAsyncEnumerable and honours cancellation
  • Mentions background jobs or a read replica for heavy reports

Red flags

  • Starts with the string concatenation
  • Suggests adding AsNoTracking() as the main fix
  • Proposes caching the whole table in memory

๐Ÿ“š Learn in depth

1. Where the original spends its time and memory

SQL Server: scan Orders + OrderLines (all rows, all columns), JOIN, sort by key
   -> network: millions of wide rows (order columns repeated per line)
   -> EF Core: materialise entities + snapshots for tracking + identity resolution
   -> LINQ to Objects: filter 1/36 of it, group, sum
   -> string building: copy the growing CSV on every line

Every stage processes data the result doesn't need. The network part alone is large: 1.8 million detail rows at roughly 200 bytes each is about 360 MB over TDS, against a few hundred aggregated rows of perhaps 50 KB. The memory is the dangerous part: entities, snapshots and a CSV string that ends up on the Large Object Heap (over 85,000 bytes), copied once per line.

2. What the translated aggregation sends

SELECT [o].[Region], [l].[ProductId],
       SUM([l].[Quantity]) AS [Units],
       SUM(CAST([l].[Quantity] AS decimal(18,2)) * [l].[UnitPrice]) AS [Revenue]
FROM [Orders] AS [o]
INNER JOIN [OrderLines] AS [l] ON [o].[Id] = [l].[OrderId]
WHERE [o].[CreatedAt] >= @start AND [o].[CreatedAt] < @end
GROUP BY [o].[Region], [l].[ProductId]
-- Report.MonthlySales

EF Core translates GroupBy followed by aggregate operators (Sum, Count, Average, Min, Max) in the projection into SQL GROUP BY. Since EF Core 7, GroupBy as the final operator (returning the groups with their elements) is also supported, but it is not an aggregation: EF Core fetches every detail row ordered by the key and builds the groups on the client, so for a report it moves exactly the data you were trying to avoid. Project keys and aggregates only.

3. Streaming instead of buffering

AsAsyncEnumerable() reads rows from the DbDataReader one at a time; writing each to a StreamWriter over Response.Body sends the file as it's produced. Memory stays flat regardless of row count. The trade-off: once the headers are sent you can't change the status code, so validate inputs before starting.

4. String concatenation cost

csv += line allocates a new string of the full length each time: for n lines of average length k, total copying is about kยทnยฒ/2 characters. For 100,000 lines that's billions of character copies. StringBuilder grows geometrically; a StreamWriter avoids holding the file at all.

5. Request path vs background job

Anything that might take more than a few seconds, or read large data, is better as a job: the request enqueues it (Azure Service Bus, Hangfire, a queue-triggered Function), a worker writes the file to Blob Storage, and the user gets a link. That isolates the API from report load, allows retries and lets you read from a replica: Azure SQL Premium, Business Critical and Hyperscale offer read scale-out, reached with ApplicationIntent=ReadOnly in the connection string, and geo-replicas are another readable option.

6. Indexing the date range

An index on Orders (CreatedAt) INCLUDE (Region) lets the month filter seek, and OrderLines (OrderId) INCLUDE (ProductId, Quantity, UnitPrice) covers the join. For very large history, partitioning by month or a columnstore index on the lines table can make aggregations dramatically cheaper; measure with the actual plan.

7. CSV safety

Escape commas, quotes and newlines; prefix cells starting with =, +, - or @ to avoid spreadsheet formula injection when finance opens the file in Excel.

Try it yourself

  1. Seed 500,000 orders with 3 lines each and run the original method while watching dotnet-counters monitor System.Runtime (GC heap size, LOH size).
  2. Run the rewritten aggregation and compare duration, rows returned and memory.
  3. Print ToQueryString() for the grouped query and confirm it contains GROUP BY; then try GroupBy as the final operator and compare the SQL.
  4. Benchmark +=, StringBuilder and StreamWriter for 100,000 lines with BenchmarkDotNet.
  5. Cancel the request mid-stream (close the client) and confirm in SQL Server that the query is cancelled.

๐Ÿ’ป Code

The rewrite: SQL aggregation over a sargable month range, streamed as CSV with cancellation.

namespace Shop.Reports;

using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public sealed record SalesRow(string Region, int ProductId, int Units, decimal Revenue);

public sealed class SalesReportQuery(ShopDbContext db)
{
    public IAsyncEnumerable<SalesRow> Run(int year, int month)
    {
        var start = new DateTime(year, month, 1);
        var end = start.AddMonths(1);

        return db.OrderLines
            .TagWith("Report.MonthlySales")
            .Where(l => l.Order.CreatedAt >= start && l.Order.CreatedAt < end) // sargable range
            .GroupBy(l => new { l.Order.Region, l.ProductId })
            .Select(g => new SalesRow(
                g.Key.Region,
                g.Key.ProductId,
                g.Sum(l => l.Quantity),
                g.Sum(l => l.Quantity * l.UnitPrice)))                         // aggregated in SQL
            .OrderBy(r => r.Region).ThenBy(r => r.ProductId)
            .AsAsyncEnumerable();                                              // untracked projection, streamed
    }
}

[ApiController]
[Route("reports")]
public sealed class ReportsController(SalesReportQuery query) : ControllerBase
{
    [HttpGet("sales")]
    public async Task MonthlySales([FromQuery] int year, [FromQuery] int month, CancellationToken ct)
    {
        if (month is < 1 or > 12 || year is < 2000 or > 2100)
        {
            Response.StatusCode = StatusCodes.Status400BadRequest;
            return;
        }

        Response.ContentType = "text/csv";
        Response.Headers.ContentDisposition = $"attachment; filename=sales-{year}-{month:00}.csv";

        await using var writer = new StreamWriter(Response.Body, new UTF8Encoding(false));
        await writer.WriteLineAsync("Region,ProductId,Units,Revenue");
        await foreach (var r in query.Run(year, month).WithCancellation(ct))
        {
            await writer.WriteLineAsync(string.Join(',',
                Csv(r.Region), r.ProductId.ToString(CultureInfo.InvariantCulture),
                r.Units.ToString(CultureInfo.InvariantCulture), r.Revenue.ToString("0.00", CultureInfo.InvariantCulture)));
        }
    }

    // Escape quotes and separators; neutralise spreadsheet formula injection.
    private static string Csv(string value)
    {
        if (value.Length > 0 && "=+-@".Contains(value[0])) value = "'" + value;
        return value.AsSpan().IndexOfAny(",\"\n\r") >= 0 ? $"\"{value.Replace("\"", "\"\"")}\"" : value;
    }
}
// Program.cs: a sensible command timeout for reporting queries (seconds).
builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(
    builder.Configuration.GetConnectionString("Shop"), sql => sql.CommandTimeout(60)));
builder.Services.AddScoped<SalesReportQuery>();

โš  Common mistakes

  • Mistake: ToListAsync() on a whole table before filtering. Why it is wrong: memory and time grow with the table, not the result, until the process runs out of memory. Instead: filter, aggregate and page in the query.
  • Mistake: Grouping in LINQ to Objects. Why it is wrong: every detail row crosses the network to compute a few hundred sums. Instead: GroupBy with aggregate projections, which EF Core translates to GROUP BY.
  • Mistake: Using GroupBy as the final operator and summing the groups afterwards. Why it is wrong: since EF Core 7 this runs, but it fetches every detail row ordered by the key and groups on the client, so it is the in-memory version in disguise. Instead: project only keys and aggregates (g.Sum(...), g.Count()) inside the query.
  • Mistake: Filtering by .Year and .Month. Why it is wrong: non-sargable, so the month filter scans. Instead: a half-open date range.
  • Mistake: Building large strings with +=. Why it is wrong: quadratic copying and LOH churn. Instead: write to a StreamWriter (or StringBuilder for small output).
  • Mistake: Running long reports on the request path without cancellation. Why it is wrong: closed browsers leave queries running and threads busy. Instead: pass CancellationToken, set a command timeout, and move big exports to a background job.
  • Mistake: Writing CSV fields without escaping. Why it is wrong: commas break columns and leading = enables formula injection in Excel. Instead: escape and neutralise.

๐Ÿ› Senior insight: trade-offs

A report is a set-based question, so the database should answer it; the application's job is to ask precisely and stream the answer. Beyond fixing the code, I'd ask whether reporting belongs on the transactional database at all: at month end, a read replica, a pre-aggregated summary table updated by a job, or a proper analytics store (Fabric, Synapse) may be the right home. That's a conversation with the product owner about freshness versus cost.

Option When it fits Cost When not to
SQL aggregation streamed on request Results of hundreds to thousands of rows, seconds to run Index tuning Long-running or very large detail exports
Background job to Blob Storage Large exports, minutes to run Queue, worker, notification Small interactive reports
Read replica (ApplicationIntent=ReadOnly) Heavy reporting on Business Critical or Hyperscale Slight replication lag Need read-your-writes consistency
Pre-aggregated table or analytics store Repeated reports over large history Pipeline to maintain, data freshness One-off or rarely run reports

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions loading every column or AsEnumerable before filtering Why: Checks their understanding of over-fetching and client evaluation in general
    How to answer

    Over-fetching is loading more than the use case needs: whole entities when the screen uses three columns, or rows you then filter away in memory. Client evaluation makes it worse: everything after AsEnumerable() or ToList() runs in .NET, so a Where or OrderBy placed after it downloads the whole set first. Since EF Core 3, untranslatable expressions throw instead of silently running on the client, except in the final Select, but an explicit AsEnumerable() still moves the work to memory. I fix it by projecting with Select into a DTO, keeping large nvarchar(max) or varbinary(max) columns out of list queries (projection, table splitting or a separate table), and keeping every filter before materialisation. I find it with ToQueryString() and logs. The trade-off: projections mean more DTO types, but each query moves only the data it uses.

  2. When: Candidate proposes AsAsyncEnumerable streaming Why: Checks they know the deferred-execution and DbContext lifetime pitfalls of streaming
    How to answer

    An EF Core IQueryable is a recipe, not data. Each enumeration (foreach, Count(), Any(), ToList()) sends SQL again, so enumerating twice is two round trips, and if rows change in between the two results disagree (a count of 10, then a loop over 11). A query returned from a method runs only when someone enumerates it; if the scope that owned the DbContext has ended and disposed it by then, you get ObjectDisposedException. And while a query is streaming, its DbDataReader holds the connection, so another command on the same context inside the loop fails (unless MARS is on) or is a hidden N+1. The context isn't thread-safe either, so overlapping operations throw.

    ToListAsync() buffers: the connection is freed quickly, but memory holds the whole result. AsAsyncEnumerable() with await foreach streams in constant memory but holds the connection for the whole loop.

    I materialise once, inside the unit of work, and stream only large, read-only, no-tracking results.

  3. When: Candidate mentions the Include of order lines Why: Checks they understand how collection Includes multiply rows and when to use split queries or projection
    How to answer

    With a single query, each collection Include becomes a LEFT JOIN, and sibling collections multiply: 50 orders x 20 lines x 10 notes x 30 status events is 300,000 rows, with the order's columns repeated on every one. That is cartesian explosion: SQL Server, the network and EF Core's materialiser all process far more rows than the result needs. I confirm it by comparing rows returned in the actual execution plan or SET STATISTICS IO with the number of entities, reading the SQL via ToQueryString(), and checking for EF Core's multiple collection Include warning. Then I pick the fix: project only what the screen needs (often aggregates instead of collections), use AsSplitQuery() when I really need the full entities, or load the collections separately. The trade-off: split queries mean more round trips and no consistent snapshot unless you add a transaction.

๐Ÿ›  Real-world problems: how you handle them

Month-end sales report causing out-of-memory restarts
Situation
An internal finance API on ASP.NET Core and EF Core in Azure App Service [P1v3, 2 instances] with Azure SQL. The monthly sales report was run by [the finance team] at month end against [about 600,000] orders and [1.8 million] lines.
Signals
At month end the API restarted repeatedly with out-of-memory errors; App Service memory hit [95%]; the report took about 4 minutes when it completed; Azure SQL showed long-running scans and other endpoints slowed down.
Investigation
dotnet-counters on an instance showed GC heap size climbing past [1.5 GB] during a report run, with large LOH growth. A dotnet-dump showed millions of `Order` and `OrderLine` instances plus change-tracking snapshots. EF Core logs showed a single unfiltered query with a JOIN to `OrderLines`; the code grouped in LINQ to Objects and built the CSV with `+=`.
Resolution
Immediately: limited the endpoint to one concurrent run with a rate limiter. Then rewrote it as a translated `GroupBy` aggregation over a month range, streamed to the response with `AsAsyncEnumerable` and a `StreamWriter`, with cancellation and a command timeout. Large detail exports moved to a background job writing to Blob Storage.
Prevention
Reporting checklist (aggregate in SQL, stream, cancellation, row budget); a load test of the report on production-sized synthetic data before month end; an App Service memory alert; an ADR to move heavy reporting to the read replica.

How to tell it (STAR)

**S:** At month end our [finance API] kept restarting with out-of-memory errors whenever the sales report ran. **T:** I was asked to make the report safe before the next [month-end close]. **A:** dotnet-counters showed the heap passing [1.5 GB] during one run, and a dump was full of tracked orders and lines: the code loaded the whole table, grouped in memory and built the CSV with string concatenation. I rewrote it as a SQL GROUP BY over a sargable date range, streamed the CSV straight to the response with cancellation, and moved full-detail exports to a background job writing to Blob Storage. **R:** The report now runs in about [1.2 seconds] using under [50 MB], month-end restarts stopped, and other endpoints no longer slow down while finance runs it.

More in EF Core Performance

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me