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

πŸ“š Interview question

Show me how you stream a large response from an ASP.NET Core API without buffering it all in memory, for example a 2 million row export. Use IAsyncEnumerable results, explain what can cause buffering anyway, and how you stop the work when the client disconnects using RequestAborted.

Streaming large responses in ASP.NET Core .NET 10: returning IAsyncEnumerable from Minimal APIs and controllers, System.Text.Json streaming serialisation and flushing, EF Core AsAsyncEnumerable and AsNoTracking, NDJSON and CSV with PipeWriter, things that cause buffering (ToListAsync, middleware, proxies), and cancelling on client disconnect with RequestAborted.

Mid-Level Coding Intermediate aspnet-core cancellation ef-core iasyncenumerable performance streaming

🎯 Key points

  • Return IAsyncEnumerable<T> (Minimal API or controller): System.Text.Json writes the JSON array as items arrive, flushing when its buffer (JsonSerializerOptions.DefaultBufferSize, 16 KB) fills
  • Source must stream too: EF Core AsNoTracking().AsAsyncEnumerable() with a DTO projection, not ToListAsync()
  • Buffering creeps in from ToList/ToArray, response caching or compression middleware, output buffering in proxies, and IIS or nginx settings
  • Cancellation: the serialiser enumerates with HttpContext.RequestAborted and EF honours it; in custom loops pass the token explicitly so SQL Server stops when the client disconnects
  • For huge exports use NDJSON or CSV written to Response.BodyWriter (PipeWriter) using GetSpan/Advance, with FlushAsync every few thousand rows
  • Once the first byte is sent, status code and headers are fixed: errors mid-stream can't become a 500, so log once and abort the connection
  • Memory stays flat: watch with dotnet-counters (GC heap size, gen 2 collections, LOH) versus the buffered version
  • Keep logging out of the hot loop (log start, end, row count and errors); use a background export to Blob Storage for very long jobs

⏱ 30-second answer

To stream, every link in the chain must stream. Return IAsyncEnumerable<T> from the endpoint. System.Text.Json then writes the JSON array element by element and flushes as it goes, instead of building a list. Feed it from a streaming source: EF Core AsNoTracking().AsAsyncEnumerable(), not ToListAsync(). Bind the endpoint's CancellationToken, which is HttpContext.RequestAborted, and pass it to the query, so a closed browser tab cancels the SQL command instead of reading 2 million rows into nowhere. For really large exports, write NDJSON or CSV straight to Response.BodyWriter and flush every few thousand rows. Watch for hidden buffering: ToList(), response compression or caching middleware, and proxies such as nginx.

The trade-off: memory stays flat, but once bytes are sent you can no longer change the status code, so mid-stream errors need a different strategy.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"The goal is constant memory regardless of row count, so I check that nothing in the chain materialises the whole result. In .NET 10, if a Minimal API or controller action returns IAsyncEnumerable<T>, the System.Text.Json output path enumerates it asynchronously and writes the JSON array incrementally, flushing as its buffer fills. The source has to cooperate. With EF Core I use AsNoTracking() so the change tracker doesn't hold every entity, and AsAsyncEnumerable() so rows are read from the DbDataReader one at a time. If someone writes await query.ToListAsync() and then returns it, you're back to holding 2 million objects, and they end up on the large object heap.

Cancellation is the other half. In Minimal APIs a CancellationToken parameter binds to HttpContext.RequestAborted. Kestrel cancels it when the client disconnects. If I pass it into the EF query, the async enumeration throws OperationCanceledException, EF disposes the reader, and SQL Server gets an attention signal and stops the query. Without that, a user who closes the tab leaves the server reading and serialising rows for minutes.

For exports measured in hundreds of megabytes, I skip the JSON array and write NDJSON or CSV directly to Response.BodyWriter, which is a PipeWriter, flushing every few thousand rows. I set Content-Disposition so the browser downloads it. The things that silently re-buffer are response compression on the route, response caching or output caching, and proxies: nginx buffers by default, and IIS can too. And once the first byte is out, the status code is committed. If the database fails halfway, you can't return a 500 any more, so I log it and abort the connection so the client sees a truncated download, not a 'successful' half file. The mistake I see is people believing IAsyncEnumerable alone guarantees streaming, while the source or the middleware buffers everything anyway."


Buffered vs streamed

Buffered (ToListAsync + Ok(list)) Streamed (IAsyncEnumerable / PipeWriter)
Memory O(rows): every entity plus the serialised output O(1): one row plus the write buffer
Time to first byte After the whole query and serialisation After the first row
Client disconnect Work completes anyway (unless token passed) Query cancelled via RequestAborted
Error mid-way Clean 500 with ProblemDetails Status already sent; must abort the connection
Content-Length Known Chunked transfer encoding (HTTP/1.1) or DATA frames (HTTP/2)

What causes buffering anyway

Culprit Why Fix
ToList, ToArray, ToListAsync Materialises the source AsAsyncEnumerable() end to end
Change tracking Holds every entity AsNoTracking()
Response compression middleware Buffers to compress efficiently Exclude the route, or accept compression flushing in blocks
Response caching or output caching Must capture the full body Don't cache streaming endpoints
nginx, IIS, API gateways Proxy buffering proxy_buffering off, X-Accel-Buffering: no
Synchronous I/O Blocks threads, and is disabled by default (AllowSynchronousIO = false) Async writes only

Production example

A [transactions export] endpoint used ToListAsync() for up to [2 million] rows. Each export allocated about [1.8 GB], the pod hit its memory limit and was OOMKilled during month-end. Switching to AsNoTracking().AsAsyncEnumerable() with CSV written to BodyWriter kept the working set under [150 MB] per export, and the first byte arrived in [under 200 ms] instead of [40 seconds].

πŸ” What the interviewer is checking

Checks that the candidate can build a truly streaming endpoint end to end, knows what silently re-buffers, and handles cancellation and mid-stream errors.

Green flags

  • Returns IAsyncEnumerable and uses AsNoTracking().AsAsyncEnumerable()
  • Passes RequestAborted so the database query stops on disconnect
  • Names compression, caching and proxies as hidden buffering
  • Knows the status code is committed after the first byte and aborts on failure
  • Suggests background exports for very large files

Red flags

  • Uses ToListAsync() then returns IAsyncEnumerable and calls it streaming
  • No cancellation
  • Believes they can return a 500 halfway through a stream

πŸ“š Learn in depth

1. The chain that has to stream

SQL Server ──TDS packets──▢ SqlDataReader ──row──▢ EF Core materialiser (no tracking) ──entity──▢
IAsyncEnumerable<T> ──▢ System.Text.Json writer (buffer ~16 KB, flush when full) ──▢
Response.BodyWriter (PipeWriter) ──▢ middleware (must not buffer) ──▢ Kestrel ──chunks / DATA frames──▢
proxy (must not buffer) ──▢ client

Any link that collects everything before passing it on turns the whole pipeline into a buffered one.

2. How IAsyncEnumerable is serialised

When the result value is an IAsyncEnumerable<T>, JsonSerializer.SerializeAsync writes [, then awaits MoveNextAsync() for each element, serialises it into its buffer, and flushes to the response stream when the buffer passes a threshold, then writes ]. In MVC before .NET 6, IAsyncEnumerable results were buffered into a list by the output formatter. Since .NET 6 they stream with System.Text.Json; older code and some custom formatters still buffer.

3. Cancellation path

browser closes tab β†’ TCP FIN/RST β†’ Kestrel detects β†’ RequestAborted cancelled
   β†’ EF Core's await foreach (WithCancellation) throws OperationCanceledException
   β†’ SqlDataReader disposed, SqlCommand.Cancel β†’ TDS attention β†’ SQL Server stops the query

Kestrel only notices a disconnect when it reads from or writes to the socket, so detection can lag by up to one write. Writes to a disconnected client also throw, so even without the token the loop eventually stops, but only after the next row is produced.

4. Errors after the response has started

HttpResponse.HasStarted becomes true on the first flush. After that, the exception handler middleware can't write a ProblemDetails body or change the status. The honest options are to log the error and call HttpContext.Abort(), so the client gets a reset connection and knows the download failed, or to write a trailing error record in formats you control (an NDJSON {"error":...} line). Never let a truncated file end cleanly with a 200.

5. When not to stream over HTTP

If the export takes minutes, a mobile network drop restarts it from zero. For exports above roughly [a few hundred MB], or taking longer than a minute, use a background job that writes to Azure Blob Storage and returns a short-lived SAS link. That is more robust and lets the user leave the page.

Try it yourself

  1. Seed 1 million rows and compare /export/buffered and /export/streamed with dotnet-counters monitor System.Runtime (GC heap size, LOH size, gen 2 count).
  2. Use curl -N and look at time to first byte with -w "%{time_starttransfer}".
  3. Start a download, press Ctrl+C on curl, and confirm in SQL Server (sys.dm_exec_requests) that the query disappears.
  4. Enable app.UseResponseCompression() for the route and see whether time to first byte changes.
  5. Throw an exception at row 500,000 and observe what the client receives with and without HttpContext.Abort().

πŸ’» Code

Three streaming endpoints: JSON via IAsyncEnumerable, CSV via PipeWriter, and the controller equivalent.

// Program.cs (.NET 10)
using System.Buffers;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<LedgerDb>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Ledger")));
builder.Services.AddControllers();
var app = builder.Build();

// 1. JSON array streamed by System.Text.Json. The serialiser enumerates the sequence with
//    HttpContext.RequestAborted, and EF Core's async enumerator honours that token.
app.MapGet("/accounts/{id:int}/transactions", (int id, LedgerDb db) =>
    db.Transactions
      .AsNoTracking()                                  // don't hold 2M entities in the change tracker
      .Where(t => t.AccountId == id)
      .OrderBy(t => t.Id)
      .Select(t => new TransactionDto(t.Id, t.PostedAt, t.Amount, t.Description))
      .AsAsyncEnumerable());

// 2. CSV export written straight into the PipeWriter's buffer, flushed in batches.
app.MapGet("/accounts/{id:int}/transactions.csv", async (int id, LedgerDb db, HttpContext http, ILogger<Program> log) =>
{
    var ct = http.RequestAborted;                      // our own loop, so pass the token explicitly
    http.Response.ContentType = "text/csv";
    http.Response.Headers.ContentDisposition = $"attachment; filename=transactions-{id}.csv";
    var writer = http.Response.BodyWriter;
    var count = 0;

    log.LogInformation("Export started for account {AccountId}", id); // log start/end, not every row
    try
    {
        WriteLine(writer, "id,posted_at,amount,description");
        await foreach (var t in Query(db, id, ct))
        {
            WriteLine(writer, $"{t.Id},{t.PostedAt:O},{t.Amount},\"{t.Description.Replace("\"", "\"\"")}\"");
            if (++count % 5_000 == 0)
                await writer.FlushAsync(ct);           // hand the bytes to Kestrel; the pipe's memory is reused
        }
        await writer.FlushAsync(ct);
        log.LogInformation("Export finished for account {AccountId}: {Rows} rows", id, count);
    }
    catch (OperationCanceledException) when (ct.IsCancellationRequested)
    {
        log.LogInformation("Client disconnected after {Rows} rows for account {AccountId}", count, id);
    }
    catch (Exception ex) when (http.Response.HasStarted)
    {
        // Status 200 is already sent: abort so the client sees a failed download, not a short "valid" file.
        log.LogError(ex, "Export failed mid-stream after {Rows} rows for account {AccountId}", count, id);
        http.Abort();
    }
});

app.MapControllers();
app.Run();

// Encodes directly into memory owned by the pipe: no intermediate byte[] per row.
static void WriteLine(PipeWriter writer, string line)
{
    var maxBytes = Encoding.UTF8.GetMaxByteCount(line.Length + 1);
    var span = writer.GetSpan(maxBytes);               // the pipe sizes the segment; large rows get a bigger one
    var written = Encoding.UTF8.GetBytes(line, span);
    span[written++] = (byte)'\n';
    writer.Advance(written);                           // the pipe tracks unflushed bytes and applies backpressure on FlushAsync
}

static async IAsyncEnumerable<TransactionDto> Query(LedgerDb db, int id, [EnumeratorCancellation] CancellationToken ct)
{
    await foreach (var t in db.Transactions.AsNoTracking()
                       .Where(t => t.AccountId == id).OrderBy(t => t.Id)
                       .Select(t => new TransactionDto(t.Id, t.PostedAt, t.Amount, t.Description))
                       .AsAsyncEnumerable().WithCancellation(ct))
        yield return t;
}

// 3. Controller version: returning IAsyncEnumerable streams too (since .NET 6).
[ApiController, Route("api/[controller]")]
public sealed class ExportsController(LedgerDb db) : ControllerBase
{
    [HttpGet("{id:int}")]
    public IAsyncEnumerable<TransactionDto> Get(int id) =>
        db.Transactions.AsNoTracking().Where(t => t.AccountId == id).OrderBy(t => t.Id)
          .Select(t => new TransactionDto(t.Id, t.PostedAt, t.Amount, t.Description))
          .AsAsyncEnumerable(); // the output formatter enumerates with RequestAborted
}

public sealed record TransactionDto(long Id, DateTimeOffset PostedAt, decimal Amount, string Description);
public sealed class Transaction { public long Id { get; set; } public int AccountId { get; set; } public DateTimeOffset PostedAt { get; set; } public decimal Amount { get; set; } public string Description { get; set; } = ""; }
public sealed class LedgerDb(DbContextOptions<LedgerDb> o) : DbContext(o) { public DbSet<Transaction> Transactions => Set<Transaction>(); }

⚠ Common mistakes

  • Mistake: Calling ToListAsync() and returning the list. Why it is wrong: Every row is materialised (often on the LOH) before the first byte is sent. Instead: Return AsAsyncEnumerable() or write rows as you read them.
  • Mistake: Forgetting AsNoTracking(). Why it is wrong: The change tracker keeps every entity alive, so memory grows with row count even while streaming. Instead: AsNoTracking() and project to a DTO.
  • Mistake: Not passing RequestAborted (the endpoint's CancellationToken). Why it is wrong: A closed tab leaves the server reading and serialising millions of rows. Instead: Bind the token and pass it with WithCancellation or to the query.
  • Mistake: Enabling response compression or caching on the streaming route. Why it is wrong: They buffer the response, defeating streaming. Instead: Exclude streaming routes, or compress in a background export.
  • Mistake: Testing only against Kestrel locally. Why it is wrong: nginx, IIS or an API gateway may buffer the whole response in production. Instead: Test through the real proxy path and disable buffering for the route.
  • Mistake: Letting a mid-stream exception end the response normally. Why it is wrong: The client receives a 200 with a truncated file that looks complete. Instead: Log and call HttpContext.Abort(), or write an error record the client checks.
  • Mistake: Flushing after every row. Why it is wrong: Each flush is a syscall and a network write, so throughput collapses. Instead: Flush every few thousand rows or let the serialiser flush when its buffer fills.
  • Mistake: Streaming multi-minute exports over HTTP. Why it is wrong: Any network drop restarts from zero and holds a connection and a database query for minutes. Instead: Generate in the background to Blob Storage and return a SAS link.

πŸ› Senior insight: trade-offs

Streaming is the right default for large reads, but it changes the contract. You lose Content-Length, a clean error status after the first byte, and response caching. For an export a person downloads, those trade-offs are fine. For an API consumed by other services, a paged API with continuation tokens is often better: each page is retryable, cacheable and has a proper status code.

Option When it fits Cost When not to
IAsyncEnumerable JSON array Moderate result sets, JSON clients Errors after start can't be reported cleanly Very large exports where clients need line-by-line parsing
NDJSON or CSV via PipeWriter Large exports, data pipelines Custom format code, client must parse lines Clients that need one JSON document
Keyset pagination Service-to-service, retryable reads Many requests Single-shot bulk downloads
Background export to Blob plus SAS link Minutes-long jobs, very large files Job infrastructure, storage Small, fast responses

Measure it: peak working set and LOH size per export with dotnet-counters, time to first byte, SQL Server query duration after client cancel (should drop to zero), and pod OOMKilled events.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate uses async iterators with [EnumeratorCancellation]. Why: Checks deeper understanding of async streams and cancellation.
    How to answer

    IAsyncEnumerable<T> is a sequence whose items arrive asynchronously. You produce one with an async iterator method that uses both await and yield return, and consume it with await foreach, which awaits MoveNextAsync() for each item and disposes the enumerator asynchronously. Cancellation is passed with .WithCancellation(ct) and received in the iterator through a parameter marked [EnumeratorCancellation]. It lets you process large or slow data item by item instead of buffering everything, for example EF Core AsAsyncEnumerable() or streaming JSON responses from ASP.NET Core. .NET 10 includes LINQ operators for it in the base library (System.Linq.AsyncEnumerable).

  2. When: Candidate mentions streaming request bodies or uploads. Why: Checks the upload side: IFormFile buffering versus MultipartReader streaming.
    How to answer

    With IFormFile, ASP.NET Core buffers the whole multipart body before your handler runs: in memory up to 64 KB per file (FormOptions.MemoryBufferThreshold), then to temp files on disk. That's fine for small files, but for 2 GB uploads it means disk, I/O, latency and a denial-of-service risk. Instead I stream: read the body with MultipartReader (or the raw Request.Body) and copy each section straight to Blob Storage, so memory stays flat regardless of size. Then I align limits at every hop: Kestrel MaxRequestBodySize (~28.6 MB default), MultipartBodyLengthLimit (128 MB), IIS and the ingress or gateway, raising them per endpoint only. For truly large files, the best option is often a SAS URL so the client uploads directly to storage. The trade-off: streaming is more code but scales; buffering is simple but only for small files.

  3. When: Candidate mentions pushing incremental updates to the browser. Why: Checks Server-Sent Events as the streaming option for live updates.
    How to answer

    Server-Sent Events is one long-lived HTTP response with Content-Type: text/event-stream. The server writes id:, event: and data: lines, and the browser's EventSource parses them and reconnects automatically, sending the last id in a Last-Event-ID header. In .NET 10 it is built in: return TypedResults.ServerSentEvents(stream), where stream is an IAsyncEnumerable<SseItem<T>>. The framework sets the headers, serialises T to JSON and flushes each item. You pass the request's CancellationToken so the loop ends when the client goes away, read Last-Event-ID to replay missed events, and send heartbeats so proxies don't cut idle streams.

    SSE beats WebSockets when data flows one way: it is plain HTTP, so auth, HTTP/2, proxies and logging all just work. It is the wrong tool when the client must send a lot back.

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

Month-end transaction exports OOMKill the API pods
Situation
A [banking] API on [AKS] with a 2 GiB memory limit per pod offered a transactions export for business customers. At [month-end], [dozens] of customers exported up to [2 million] rows each.
Signals
Pods restarted with `OOMKilled` during month-end mornings. Exports took [40+ seconds] before any data arrived, and some failed in the browser with network errors. Azure SQL showed export queries still running after users had given up.
Investigation
Ran `dotnet-counters monitor System.Runtime` against a pod during a test export and saw GC heap size climb to [1.8 GB] with large LOH growth. A memory dump (`dotnet-dump analyze`, `dumpheap -stat`) showed millions of tracked `Transaction` entities and a huge `List<TransactionDto>`. The code used `ToListAsync()` with tracking and never passed the request's cancellation token. `sys.dm_exec_requests` confirmed queries continued after client disconnects.
Resolution
Immediate: limited exports to one per customer at a time with a rate limiter and raised the memory limit temporarily. Real fix: rewrote the endpoint with `AsNoTracking()`, a DTO projection and `AsAsyncEnumerable()`, wrote CSV to `Response.BodyWriter` with batched flushes, passed `RequestAborted`, and aborted the connection on mid-stream errors. Exports over [500,000] rows moved to a background job writing to Blob Storage with an emailed SAS link valid for [24 hours].
Prevention
A load test that exports 2 million rows and asserts the pod's working set stays under [300 MB]. An analyser rule or code-review checklist flagging `ToListAsync()` on export endpoints. Alerts on OOMKilled pods and on long-running SQL queries without an active request.

How to tell it (STAR)

**S:** At month-end our [transactions export] was OOMKilling API pods, because customers were exporting up to [2 million] rows each. **T:** I had to make exports reliable before the next month-end, [about two weeks away]. **A:** dotnet-counters and a dump showed we were loading every row into tracked entities and a list before writing anything, and queries kept running after users gave up. I rewrote it to stream: no tracking, a DTO projection, `AsAsyncEnumerable`, CSV straight to the PipeWriter with batched flushes, and the request's cancellation token passed to the query. Very large exports moved to a background job that writes to Blob Storage. **R:** Memory per export dropped from about [1.8 GB] to under [150 MB], first bytes arrived in [under 200 ms], and we had zero OOMKills at the next month-end.

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me