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.
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.
"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 useAsNoTracking()so the change tracker doesn't hold every entity, andAsAsyncEnumerable()so rows are read from theDbDataReaderone at a time. If someone writesawait 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
CancellationTokenparameter binds toHttpContext.RequestAborted. Kestrel cancels it when the client disconnects. If I pass it into the EF query, the async enumeration throwsOperationCanceledException, 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 aPipeWriter, flushing every few thousand rows. I setContent-Dispositionso 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 believingIAsyncEnumerablealone guarantees streaming, while the source or the middleware buffers everything anyway."
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) |
| 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 |
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].
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
IAsyncEnumerable and uses AsNoTracking().AsAsyncEnumerable()RequestAborted so the database query stops on disconnectRed flags
ToListAsync() then returns IAsyncEnumerable and calls it streamingSQL 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.
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.
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.
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.
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.
/export/buffered and /export/streamed with dotnet-counters monitor System.Runtime (GC heap size, LOH size, gen 2 count).curl -N and look at time to first byte with -w "%{time_starttransfer}".sys.dm_exec_requests) that the query disappears.app.UseResponseCompression() for the route and see whether time to first byte changes.HttpContext.Abort().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>(); }
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.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.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.HttpContext.Abort(), or write an error record the client checks.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.
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).
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.
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.
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.
Last updated 23 Nov 2026.