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

📚 Interview question

Your API must accept file uploads of up to 2 GB. How do you handle large uploads and streaming request bodies in ASP.NET Core? Compare IFormFile buffering with streaming through MultipartReader or the raw body, explain the size limits at each layer, and how you keep memory use flat.

Large file uploads in ASP.NET Core: IFormFile buffering to memory and temp disk (FormOptions.MemoryBufferThreshold, MultipartBodyLengthLimit), streaming with MultipartReader or Request.Body/BodyReader, Kestrel MaxRequestBodySize and per-endpoint overrides, MinRequestBodyDataRate, proxy and IIS limits, direct-to-Blob uploads with SAS, validation, malware scanning and anti-forgery.

Senior Theory Advanced aspnet-core azure-blob-storage file-upload kestrel multipart streaming

🎯 Key points

  • IFormFile buffers the whole multipart body before your code runs: in memory up to FormOptions.MemoryBufferThreshold (64 KB) and then to temp files on the pod's local or ephemeral storage
  • Buffering is fine for small files; raising limits does not fix it for large files, it only makes temp storage fill faster and opens a denial-of-service path
  • Streaming: read sections with MultipartReader (or the raw Request.Body / BodyReader) asynchronously and copy each file straight to its destination with constant memory
  • Avoid Request.Form and IFormFile parameters on streaming endpoints, because touching them triggers the buffering you are trying to avoid
  • Limits at every hop: Kestrel MaxRequestBodySize (~28.6 MB default), FormOptions.MultipartBodyLengthLimit (128 MB), IIS maxAllowedContentLength, ingress/Front Door/App Gateway body limits; raise per endpoint only
  • For very large files, prefer direct-to-storage uploads with a SAS URL so bytes never pass through the API
  • Secure SAS: user delegation SAS signed with Entra ID, write/create only, one blob, 10-15 minute expiry, HTTPS only, public blob access disabled on the account
  • Validate by content, not name: size, magic bytes, safe stored names, malware scanning (e.g. Defender for Storage), and anti-forgery for cookie-authenticated forms

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

🗣 Full answer (senior)

How I would answer this in an interview

"The key thing to know about IFormFile is when the bytes are read. Form binding reads the entire multipart body before your handler runs. Each file is held in memory up to 64 KB, then spilled to a temp file. So for a 2 GB upload, the request spends minutes writing to the server's temp disk before my code sees it, ten concurrent uploads need 20 GB of disk, and anyone can exhaust it. IFormFile is fine for avatars and small documents, not for this.

For large files I stream. I disable form binding on that endpoint, read the boundary from the Content-Type, and use MultipartReader to walk the sections. For each file section I validate the declared size, check the first bytes for the expected file signature, then copy the section's stream straight to Blob Storage with BlobClient.UploadAsync(stream), which uploads in blocks. Memory stays at a few buffers per request. Then I deal with limits at every layer: Kestrel's MaxRequestBodySize is about 28.6 MB by default, FormOptions.MultipartBodyLengthLimit is 128 MB, IIS has maxAllowedContentLength, and the ingress or Application Gateway has its own body limit. I raise them only on the upload endpoint with [RequestSizeLimit], and keep MinRequestBodyDataRate on so slow trickling clients can't hold connections forever.

For example, [at company] [a document intake API] crashed pods with No space left on device when [an insurer] bulk-uploaded scanned files through an IFormFile endpoint. I changed it to stream with MultipartReader into Blob Storage and, for files over [100 MB], moved to a two-step flow where the API issues a short-lived, write-only SAS URL and the client uploads directly. [Pod disk use stayed flat and upload success went from about 92% to over 99.5%.] The mistake I see is raising the size limits and keeping IFormFile. The bytes still go to disk; you've just made the disk fill faster."


Buffered vs streamed vs direct-to-storage

IFormFile (buffered) MultipartReader / raw body (streamed) Direct to Blob via SAS
When bytes are read Before the handler runs As your code reads Never through the API
Memory/disk 64 KB memory per file, rest temp disk Constant (buffers only) None on API
Code complexity Lowest Medium Medium (two-step flow)
Good for < ~10 MB files Up to GBs through the API Very large files, high volume
Validation After upload During upload (can abort early) After upload (storage events)

Limits to align

Layer Setting Default
Kestrel MaxRequestBodySize / [RequestSizeLimit] 30,000,000 bytes
Forms FormOptions.MultipartBodyLengthLimit 128 MB
Forms MemoryBufferThreshold 64 KB
IIS requestFiltering/requestLimits maxAllowedContentLength ~28.6 MB
ingress-nginx proxy-body-size annotation 1 MB
Azure Application Gateway (WAF) Max request body / file upload size Depends on SKU and WAF policy

Production example

Switching a 500 MB scan upload from IFormFile to streaming cut peak pod temp disk from about 6 GB under load to near zero and memory per upload to under 1 MB; moving the largest files to SAS direct uploads removed about 70% of ingress bandwidth from the API pods.

🔍 What the interviewer is checking

Checks deep understanding of how request bodies are read and the judgement to design large uploads safely.

Green flags

  • Knows IFormFile buffers before the handler and spills to disk after 64 KB.
  • Streams with MultipartReader or the raw body and keeps memory flat.
  • Aligns limits across Kestrel, forms, IIS and the ingress, per endpoint.
  • Proposes direct-to-storage with SAS and validates content properly.

Red flags

  • 'Just raise the limits.'
  • Reads files into MemoryStream.
  • Trusts client file names and content types.

📚 Learn in depth

1. What IFormFile actually does

Request body (multipart/form-data)
  └► FormFeature.ReadFormAsync()  ← triggered by IFormFile / [FromForm] / Request.Form
        └► MultipartReader over the body
             ├─ form fields ─► memory (limits: ValueCountLimit, ValueLengthLimit)
             └─ file sections ─► FileBufferingReadStream
                                   ├─ ≤ 64 KB: memory
                                   └─ > 64 KB: temp file (ASPNETCORE_TEMP or system temp)
  └► your handler runs ONLY after the whole body has been read

Temp files are deleted at the end of the request. On containers with small ephemeral storage, concurrent large uploads fill the disk and the pod is evicted.

2. Streaming with MultipartReader

MultipartReader(boundary, Request.Body) returns MultipartSections one at a time. Each section has headers (Content-Disposition with name and filename) and a Body stream that reads directly from the request. You must consume or skip each section before reading the next. Form binding must not run first, otherwise the body is already consumed: in MVC remove value providers with a [DisableFormValueModelBinding] resource filter; in Minimal APIs take HttpRequest and don't declare IFormFile parameters.

3. Raw body uploads

For a single file, the simplest streaming option is PUT /files/{name} with the file as the raw body (Content-Type: application/octet-stream) and await request.Body.CopyToAsync(destination, ct), or request.BodyReader with pipelines for maximum efficiency.

4. Direct to storage

Client ─POST /uploads─► API: authorise, create record, issue SAS (write-only, 15 min, one blob)
Client ─PUT (blocks)──► Azure Blob Storage
Storage ─BlobCreated event─► Event Grid ─► worker: scan, validate, mark record ready

Use user delegation SAS (signed with Entra ID) rather than account-key SAS. Defender for Storage malware scanning can scan on upload.

5. Validation and security

  • Never trust FileName or ContentType: generate the stored name, check magic bytes (%PDF, \x89PNG), enforce size while streaming (count bytes and abort).
  • Store outside the web root; serve through an authorised endpoint with Content-Disposition: attachment.
  • Cookie-authenticated form uploads need anti-forgery; Minimal APIs with IFormFile validate anti-forgery tokens by default since .NET 8 (DisableAntiforgery() for token-authenticated APIs).
  • Scanned documents often contain personal information: encryption at rest, access logging and retention policies (APP 11).

6. Timeouts and slow clients

A 2 GB upload at 20 Mbit/s takes about 15 minutes. Check proxy and load balancer timeouts, keep MinRequestBodyDataRate (240 B/s) so stalled clients are dropped, and consider resumable uploads (Blob block lists, or the tus protocol) for unreliable networks.

Try it yourself

  1. Upload a 500 MB file to an IFormFile endpoint and watch the temp directory and dotnet-counters working set.
  2. Rewrite it with MultipartReader and compare memory and disk.
  3. Hit the default Kestrel limit and read the 413; then the ingress limit behind nginx.
  4. Implement a SAS-based upload and verify the SAS can't read or list.
  5. Upload a renamed .exe as .pdf and confirm your magic-byte check rejects it.

💻 Code

Streaming multipart uploads to Blob Storage with size and signature checks, plus a SAS endpoint for direct uploads.

// Program.cs
using Azure.Storage.Blobs;
using Azure.Storage.Sas;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(_ => new BlobServiceClient(
    new Uri(builder.Configuration["Storage:BlobEndpoint"]!), new Azure.Identity.DefaultAzureCredential()));
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 1 * 1024 * 1024); // small global default
var app = builder.Build();

const long MaxFileBytes = 2L * 1024 * 1024 * 1024; // 2 GB

// Streamed upload: no IFormFile, so the framework never buffers the body
app.MapPost("/documents", async (HttpRequest request, BlobServiceClient blobs, CancellationToken ct) =>
{
    if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaType) ||
        !mediaType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
        return Results.Problem("Expected multipart/form-data.", statusCode: 415);

    var boundary = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value!;
    var reader = new MultipartReader(boundary, request.Body);
    var container = blobs.GetBlobContainerClient("incoming");
    var stored = new List<string>();

    while (await reader.ReadNextSectionAsync(ct) is { } section)
    {
        if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var cd) || !cd.IsFileDisposition())
            continue;                                             // skip non-file fields (or read them as needed)

        var blobName = $"{Guid.NewGuid():N}.pdf";                 // never trust the client's file name
        await using var limited = new SignatureCheckingStream(section.Body, MaxFileBytes, "%PDF"u8.ToArray());
        await container.GetBlobClient(blobName).UploadAsync(limited, cancellationToken: ct); // block upload, constant memory
        stored.Add(blobName);
    }
    return Results.Accepted(value: stored);
})
.WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(MaxFileBytes + 1024 * 1024)) // this endpoint only
.RequireAuthorization();

// Direct-to-storage: client gets a short-lived, write-only SAS for one blob
app.MapPost("/uploads", async (BlobServiceClient blobs, CancellationToken ct) =>
{
    var key = await blobs.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddMinutes(15), ct);
    var blob = blobs.GetBlobContainerClient("incoming").GetBlobClient($"{Guid.NewGuid():N}");
    var sas = new BlobSasBuilder(BlobSasPermissions.Create | BlobSasPermissions.Write, DateTimeOffset.UtcNow.AddMinutes(15))
    {
        BlobContainerName = blob.BlobContainerName,
        BlobName = blob.Name
    };
    var uri = new BlobUriBuilder(blob.Uri) { Sas = sas.ToSasQueryParameters(key.Value, blobs.AccountName) }.ToUri();
    return Results.Ok(new { uploadUrl = uri });
}).RequireAuthorization();

app.Run();

// Enforces a size limit and checks the file signature while streaming, so bad uploads abort early
public sealed class SignatureCheckingStream(Stream inner, long maxBytes, byte[] signature) : Stream
{
    private long _read;
    public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken ct = default)
    {
        var n = await inner.ReadAsync(buffer, ct);
        if (_read < signature.Length && n > 0)
        {
            var check = Math.Min(n, signature.Length - (int)_read);
            if (!buffer.Span[..check].SequenceEqual(signature.AsSpan((int)_read, check)))
                throw new BadHttpRequestException("File type not allowed.", 415);
        }
        _read += n;
        if (_read > maxBytes) throw new BadHttpRequestException("File too large.", 413);
        return n;
    }
    public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
    public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false;
    public override long Length => throw new NotSupportedException();
    public override long Position { get => _read; set => throw new NotSupportedException(); }
    public override void Flush() { }
    public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
    public override void SetLength(long value) => throw new NotSupportedException();
    public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}

⚠ Common mistakes

  • Mistake: Raising limits and keeping IFormFile for large files. Why it is wrong: The whole body is still buffered to temp storage before your code runs; on containers that is small ephemeral storage, so pods get evicted. Instead: Stream with MultipartReader or the raw body, or upload directly to storage.
  • Mistake: Raising MaxRequestBodySize globally. Why it is wrong: Every endpoint now accepts huge bodies, an easy denial of service. Instead: Small global limit; [RequestSizeLimit] on the upload endpoint.
  • Mistake: Forgetting other layers' limits. Why it is wrong: The ingress (1 MB default in ingress-nginx), IIS or the gateway rejects the request with a 413 that never reaches your app. Instead: Align limits at every hop and test end to end.
  • Mistake: Trusting FileName and ContentType. Why it is wrong: Both are client-controlled; path traversal and disguised executables follow. Instead: Generate names, check magic bytes, scan for malware.
  • Mistake: Reading Request.Form or declaring IFormFile on a streaming endpoint. Why it is wrong: Accessing the form makes the framework read and buffer the entire body first, so by the time MultipartReader runs the body is consumed and the memory/disk cost has already been paid. Instead: Take HttpRequest only (Minimal APIs) or disable form value binding (MVC).
  • Mistake: Synchronous stream reads (Read, CopyTo) on the request body. Why it is wrong: Kestrel disallows synchronous I/O by default (AllowSynchronousIO = false) and, if enabled, a slow 15-minute upload pins a ThreadPool thread the whole time. Instead: ReadAsync/CopyToAsync with the request's CancellationToken.
  • Mistake: Copying uploads into a MemoryStream or byte[]. Why it is wrong: Memory grows with file size and concurrency, and large arrays land on the LOH. Instead: Stream to the destination.
  • Mistake: Issuing long-lived or account-key SAS tokens with broad permissions. Why it is wrong: A leaked token lets anyone read or overwrite the container for days. Instead: User delegation SAS, write-only, single blob, short expiry, HTTPS only.
  • Mistake: Storing uploads under wwwroot. Why it is wrong: They become publicly downloadable and possibly executable. Instead: Private storage served through an authorised endpoint.

🏛 Senior insight: trade-offs

The senior question isn't 'how do I accept a big file' but 'should these bytes go through my API at all?'. API pods are expensive places to move gigabytes: they tie up connections, bandwidth and disk, and scale poorly. Direct-to-storage with SAS plus an event-driven scan is usually the best design for large files; streaming through the API is right when you must inspect or transform data inline, and IFormFile is right for small files where simplicity wins. Whatever you choose, test with real sizes through the real ingress, and watch disk, memory and upload success rate in production.

Option When it fits Cost When not to
IFormFile Small files (< ~10 MB), low volume Temp disk, buffering latency Large or high-volume uploads
Streaming through API (MultipartReader/raw body) Inline validation or transformation More code, long-lived connections Very high volume of huge files
SAS direct to Blob + events Large files, high volume, mobile clients Two-step flow, async processing When the API must reject content before storing
Resumable uploads (block lists, tus) Unreliable networks, multi-GB files Client complexity Small files

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions MaxRequestBodySize or MinRequestBodyDataRate. Why: Checks Kestrel's body size, data rate and connection limits in more depth.
    How to answer

    Kestrel's KestrelServerLimits are mostly protective limits against resource exhaustion and denial of service, not speed settings. MaxConcurrentConnections and MaxConcurrentUpgradedConnections are unlimited (null) by default; MaxRequestBodySize defaults to about 28.6 MB (30,000,000 bytes) and should be overridden per endpoint for uploads; header limits (32 KB total, 100 headers), RequestHeadersTimeout (30 s) and MinRequestBodyDataRate (240 bytes/s) protect against slow-client attacks; KeepAliveTimeout (130 s) must outlive the proxy's idle timeout. HTTP/2 allows 100 streams per connection with flow-control windows; HTTP/3 must be enabled explicitly and needs HTTPS, UDP open on the port and libmsquic on Linux. In practice, Kestrel is rarely the bottleneck: throughput is limited by downstream I/O, ThreadPool starvation, CPU in serialisation, allocations/GC and connection pools. Tighten limits for safety, but measure with dotnet-counters before tuning for speed.

  2. When: Candidate mentions IFormFile and [FromForm]. Why: Checks how form binding and IFormFile fit into the model binding sources.
    How to answer

    Model binding takes data from the request (route values, query string, headers, form fields, the JSON body) and from DI, converts it, and passes it to your handler's parameters. You can be explicit with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] and [FromServices], or let the framework infer. In Minimal APIs: a parameter named in the route template comes from the route, other simple types from the query, registered services from DI, and complex types from the JSON body. In controllers with [ApiController]: complex types from the body, IFormFile from the form, route names from the route, the rest from the query. Only one parameter can read the body. [AsParameters] groups parameters into a record. The trade-off: inference keeps code short, but explicit attributes make the contract obvious in reviews and OpenAPI.

🛠 Real-world problems: how you handle them

Document intake pods evicted when an insurer bulk-uploaded scans
Situation
A document intake API [at company] on [AKS] accepted scanned claim documents through an `IFormFile` endpoint with limits raised to [1 GB]. Pods had [8 GB] ephemeral storage.
Signals
Pods evicted with `The node was low on resource: ephemeral-storage`; uploads failed with 502s during [an insurer's] bulk upload; Application Insights showed upload durations of [10+ minutes] before handler code ran.
Investigation
Used `kubectl describe pod` to confirm ephemeral storage eviction, `du` on the temp directory during a load test to watch buffered files grow, and traces showing the handler started only after the full body was read.
Resolution
Rewrote the endpoint to stream with `MultipartReader` into Blob Storage with size and signature checks, reset the global body limit to 1 MB with a per-endpoint override, and added a SAS direct-upload flow for files over [100 MB] with Event Grid triggering scanning and processing.
Prevention
Load tests with realistic file sizes through the real ingress; alerts on pod ephemeral storage and upload failure rate; an architecture guideline that files over [10 MB] never use `IFormFile`.

How to tell it (STAR)

**S:** Our [document intake API] used IFormFile with raised limits, and when [an insurer] bulk-uploaded scans, pods were evicted for running out of disk. **T:** I owned making uploads reliable at any size. **A:** I proved the body was buffered to temp disk before our code ran, rewrote the endpoint to stream into Blob Storage with size and signature checks, restored small global limits, and added a SAS direct-upload path for the largest files. **R:** Pod disk use stayed flat, upload success went from [about 92%] to [over 99.5%], and the API pods stopped carrying [most] of the upload bandwidth.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me