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

📚 Interview question

Tell me about Kestrel limits and tuning. What do MaxConcurrentConnections, MaxRequestBodySize, the header and timeout limits, and the HTTP/2 and HTTP/3 settings control, what are the defaults, and in practice what actually limits the throughput of an ASP.NET Core service?

Kestrel server limits and tuning in .NET 10: connection limits, request body size and per-endpoint overrides, header limits, KeepAliveTimeout, RequestHeadersTimeout and MinRequestBodyDataRate, HTTP/2 stream and window settings, enabling HTTP/3 with QUIC, and how to find the real throughput bottleneck (ThreadPool, CPU, allocations, downstream I/O) with measurement.

Senior Theory Advanced aspnet-core http2 http3 kestrel performance server-limits

🎯 Key points

  • KestrelServerLimits are protective limits, not throughput knobs; defaults suit most apps
  • MaxConcurrentConnections and MaxConcurrentUpgradedConnections are unlimited (null) by default; excess connections are rejected, not queued
  • MaxRequestBodySize defaults to 30,000,000 bytes (~28.6 MB); override per endpoint with [RequestSizeLimit] or IHttpMaxRequestBodySizeFeature
  • MaxRequestHeadersTotalSize 32 KB and MaxRequestHeaderCount 100; RequestHeadersTimeout 30 s and MinRequestBodyDataRate 240 B/s protect against slow-client (Slowloris) attacks
  • KeepAliveTimeout defaults to 130 s and must exceed the proxy's idle timeout
  • HTTP/2: MaxStreamsPerConnection 100, connection and stream flow-control windows; HTTP/3 needs HTTPS, Protocols including Http3 and libmsquic on Linux
  • Real throughput limits are usually downstream I/O, ThreadPool starvation from blocking, CPU from serialisation, allocations and GC, and connection pool limits
  • Measure with load tests plus dotnet-counters (Kestrel, ThreadPool, GC) before changing limits

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

🗣 Full answer (senior)

How I would answer this in an interview

"I start by saying that Kestrel's limits are there to protect the server, not to make it faster. Most of the defaults are sensible. MaxConcurrentConnections is null, meaning unlimited; if you set it, extra connections are refused, not queued. MaxRequestBodySize is 30 million bytes, roughly 28.6 MB, and I lower it globally and raise it only on upload endpoints with [RequestSizeLimit] or DisableRequestSizeLimit. Header limits are 32 KB total and 100 headers, which large cookies or JWTs occasionally hit and cause a 431. The timeouts matter for security: RequestHeadersTimeout of 30 seconds and MinRequestBodyDataRate of 240 bytes per second with a 5-second grace stop Slowloris-style clients holding connections open. KeepAliveTimeout is 130 seconds and has to be longer than the load balancer's idle timeout.

For HTTP/2, each connection allows 100 concurrent streams by default, and the connection and stream flow-control windows decide how much data can be in flight; for large downloads over high-latency links, like Sydney to a US region, bigger windows help. HTTP/3 runs over QUIC, so it needs HTTPS, Protocols = Http1AndHttp2AndHttp3, UDP open on the port and libmsquic installed on Linux.

For example, [at company] a team asked me to tune Kestrel because [a catalogue API] plateaued at [3,000 RPS]. dotnet-counters showed the ThreadPool queue length climbing and thread count growing slowly, which is starvation, not Kestrel. A synchronous .Result on an HTTP call in a filter was the cause; fixing it took the service to [9,000 RPS] on the same hardware with no Kestrel changes. The mistake I see is raising limits blindly. Kestrel can do millions of plaintext requests per second in benchmarks; your code, your database and your allocations are the limit."


Key limits and defaults (.NET 10)

Setting Default Purpose
MaxConcurrentConnections null (unlimited) Cap open connections; excess are refused
MaxConcurrentUpgradedConnections null (unlimited) WebSockets and other upgraded connections
MaxRequestBodySize 30,000,000 bytes Reject large bodies (413)
MaxRequestHeadersTotalSize 32 KB Reject huge headers (431)
MaxRequestHeaderCount 100 Header count cap
MaxRequestLineSize 8 KB Long URLs (414)
KeepAliveTimeout 130 s Idle connection lifetime
RequestHeadersTimeout 30 s Time to receive headers
MinRequestBodyDataRate 240 B/s, 5 s grace Slow upload protection
Http2.MaxStreamsPerConnection 100 Concurrent streams per connection
Http2.InitialConnectionWindowSize / InitialStreamWindowSize 128 KB / 96 KB Flow control

What actually limits throughput

Bottleneck Signal Tool
Downstream latency (SQL, HTTP) High request duration, low CPU Application Insights dependencies
ThreadPool starvation Queue length rising, slow thread injection dotnet-counters System.Runtime
CPU (JSON, mapping, logging) CPU near 100% dotnet-trace, PerfView
Allocations and GC High gen0/1 rate, GC pause % dotnet-counters, dotnet-gcdump
Connection pools Timeouts acquiring connections SqlClient/HttpClient metrics
Container CPU limits Throttling container_cpu_cfs_throttled_seconds

Production example

A file-intake service accepting 200 MB scanned documents set MaxRequestBodySize to 1 MB globally, [RequestSizeLimit(250_000_000)] on the single upload endpoint, and streamed the body to Blob Storage; memory per upload stayed under 1 MB instead of buffering the whole file, and a burst of oversized junk requests was rejected with 413 before touching application code.

🔍 What the interviewer is checking

Checks whether the candidate understands what Kestrel's limits are for, knows the important defaults, and diagnoses throughput with measurement rather than folklore.

Green flags

  • Calls the limits protective and knows key defaults (body ~28.6 MB, keep-alive 130 s, headers 32 KB).
  • Uses per-endpoint body size overrides and streaming for uploads.
  • Knows HTTP/3 requirements and HTTP/2 flow control basics.
  • Points at ThreadPool starvation, I/O, CPU and GC as the real limits, measured with dotnet-counters.

Red flags

  • Raises limits globally to 'make it faster'.
  • Thinks MaxConcurrentConnections queues requests.
  • Has never measured before tuning.

📚 Learn in depth

1. Where limits are enforced

TCP accept ─► [MaxConcurrentConnections] ─► TLS handshake ─► protocol (HTTP/1.1, h2, h3)
   ─► headers [RequestHeadersTimeout, MaxRequestLineSize, MaxRequestHeadersTotalSize, MaxRequestHeaderCount]
   ─► body [MaxRequestBodySize, MinRequestBodyDataRate]
   ─► your pipeline
   ─► response [MinResponseDataRate]
   ─► idle [KeepAliveTimeout]

Violations produce specific status codes (413, 414, 431, 408) or a closed connection, and are logged by Microsoft.AspNetCore.Server.Kestrel at Debug/Information level.

2. Per-request body size

MaxRequestBodySize is checked lazily when the body is read. Per endpoint: [RequestSizeLimit(n)], [DisableRequestSizeLimit], or in Minimal APIs .WithMetadata(new RequestSizeLimitAttribute(n)); at runtime IHttpMaxRequestBodySizeFeature.MaxRequestBodySize can change it before the body is read. FormOptions.MultipartBodyLengthLimit (128 MB default) also applies to forms, and IIS has its own maxAllowedContentLength (about 28.6 MB default).

3. Slow-client protection

MinRequestBodyDataRate enforces an average rate after a grace period; a client trickling bytes is disconnected. Disable it only for endpoints that legitimately receive slow streams (e.g. long-lived streaming uploads) via IHttpMinRequestBodyDataRateFeature.

4. HTTP/2 and HTTP/3

  • HTTP/2 multiplexes streams over one TCP connection; MaxStreamsPerConnection caps concurrency per client connection. Flow-control windows limit bytes in flight: throughput per stream ≈ window / RTT. With 96 KB and a 150 ms RTT, that is about 640 KB/s per stream, so large transfers across regions benefit from larger windows.
  • HTTP/3 uses QUIC over UDP, removing TCP head-of-line blocking. Kestrel needs ListenOptions.Protocols = Http1AndHttp2AndHttp3, HTTPS, and libmsquic (Linux) or a supported Windows version. Browsers discover it via the Alt-Svc header that Kestrel adds automatically.

5. Why Kestrel is rarely the bottleneck

Kestrel uses System.IO.Pipelines, pooled memory and the socket transport's async I/O; it does no blocking. Requests run on the ThreadPool. If your code blocks a thread (.Result, Thread.Sleep, synchronous I/O), the pool must inject threads (slowly, via hill climbing), and throughput collapses while CPU stays low. Large per-request allocations raise GC frequency. These dominate long before Kestrel's own limits.

6. Measuring

  • dotnet-counters monitor -n app System.Runtime Microsoft.AspNetCore.Server.Kestrel Microsoft.AspNetCore.Hosting: current connections, queue lengths, requests/s, ThreadPool queue length, GC.
  • Load test with k6, bombardier or Azure Load Testing at increasing concurrency; find the knee in the latency curve.
  • dotnet-trace for CPU hot paths.

Try it yourself

  1. Post a 40 MB body to a default endpoint and read the 413; add [RequestSizeLimit] and retry.
  2. Write a client that sends one header byte per second and observe the disconnect after RequestHeadersTimeout.
  3. Add Task.Delay(100).Wait() to an endpoint, load test at 500 concurrency and watch ThreadPool counters; switch to await and compare.
  4. Enable HTTP/3 locally, then check in browser dev tools that the protocol column shows h3 on a second request.
  5. Increase HTTP/2 window sizes and measure a 100 MB download across a high-latency link (or with tc netem adding 150 ms).

💻 Code

Setting limits deliberately, per-endpoint body sizes, and enabling HTTP/3.

// Program.cs
using Microsoft.AspNetCore.Server.Kestrel.Core;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(kestrel =>
{
    kestrel.AddServerHeader = false;
    var limits = kestrel.Limits;
    limits.MaxRequestBodySize = 1 * 1024 * 1024;                  // 1 MB default for JSON APIs
    limits.MaxConcurrentConnections = 10_000;                     // protect memory; excess connections refused
    limits.MaxConcurrentUpgradedConnections = 2_000;              // WebSockets cap
    limits.KeepAliveTimeout = TimeSpan.FromMinutes(5);            // longer than the load balancer idle timeout
    limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);      // Slowloris protection
    limits.Http2.InitialConnectionWindowSize = 1 * 1024 * 1024;   // larger windows for high-RTT clients
    limits.Http2.InitialStreamWindowSize = 768 * 1024;

    kestrel.ListenAnyIP(8443, listen =>
    {
        listen.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;   // HTTP/3 needs HTTPS and libmsquic on Linux
        listen.UseHttps();
    });
});

var app = builder.Build();

// Upload endpoint: raise the limit only here and stream rather than buffer
app.MapPost("/documents", async (HttpRequest request, CancellationToken ct) =>
{
    await using var target = File.Create(Path.GetTempFileName());
    await request.Body.CopyToAsync(target, ct);                   // streamed, constant memory
    return TypedResults.Accepted((string?)null);
})
.WithMetadata(new RequestSizeLimitAttribute(250_000_000))         // 250 MB for this endpoint only
.DisableAntiforgery();

app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new { id }));
app.Run();
# Watch the real bottleneck under load instead of guessing
dotnet-counters monitor -n Shop.Api System.Runtime Microsoft.AspNetCore.Hosting Microsoft.AspNetCore.Server.Kestrel
# Key counters: threadpool-queue-length, threadpool-thread-count, gc-heap-size, current-connections, requests-per-second

⚠ Common mistakes

  • Mistake: Treating Kestrel limits as performance tuning. Why it is wrong: They protect resources; raising them rarely increases throughput. Instead: Find the bottleneck with counters and traces first.
  • Mistake: Raising MaxRequestBodySize globally for one upload endpoint. Why it is wrong: Every endpoint now accepts huge bodies, so a handful of attackers posting large payloads can exhaust memory or disk (a cheap denial of service). Instead: Keep a small global limit and override per endpoint.
  • Mistake: Leaving connection limits unlimited on internet-facing Kestrel with no proxy in front. Why it is wrong: Each connection costs memory; a connection flood can exhaust the pod even at low request rates. Instead: Put a WAF or load balancer with DDoS protection in front, and set MaxConcurrentConnections to what the pod can hold.
  • Mistake: Buffering large uploads with IFormFile or ReadToEndAsync. Why it is wrong: Memory or temp disk grows with body size and concurrency. Instead: Stream the body to its destination.
  • Mistake: Setting MaxConcurrentConnections low expecting a queue. Why it is wrong: Excess connections are refused, not queued, so clients see connection errors. Instead: Use the rate limiter or concurrency limiter middleware for queuing behaviour.
  • Mistake: Disabling MinRequestBodyDataRate globally. Why it is wrong: Removes Slowloris protection for every endpoint. Instead: Disable it only for specific streaming endpoints via the feature.
  • Mistake: Enabling HTTP/3 without HTTPS, UDP firewall rules or libmsquic. Why it is wrong: It silently falls back to HTTP/2 or fails to bind. Instead: Verify h3 in browser dev tools and open UDP on the port.
  • Mistake: Forgetting other layers' limits. Why it is wrong: IIS maxAllowedContentLength, the ingress proxy-body-size or FormOptions reject the request before Kestrel's setting matters. Instead: Align limits across every hop.
  • Mistake: Blaming Kestrel for low RPS when CPU is low. Why it is wrong: Low CPU with rising latency usually means blocking or downstream waits. Instead: Check ThreadPool queue length and dependency durations.

🏛 Senior insight: trade-offs

A senior answer separates three things: safety limits (body size, headers, timeouts) that you set deliberately for your threat model, protocol tuning (HTTP/2 windows, HTTP/3) that matters only for specific traffic patterns, and throughput, which is almost always decided by your code and dependencies. The framework gives you excellent instrumentation in .NET 8+ (built-in metrics for Kestrel, hosting and the ThreadPool), so the first action is a load test with counters, not a config change. For Australian users hitting a single Australia East region, latency is low and HTTP/2 defaults are fine; cross-region transfers are where window sizes start to matter.

Option When it fits Cost When not to
Lower global body limit + per-endpoint overrides Every public API A few attributes Never wrong
MaxConcurrentConnections cap Memory-constrained pods, many idle clients Refused connections under spikes As a substitute for rate limiting
Larger HTTP/2 windows Large transfers over high RTT More memory per connection Small JSON payloads
HTTP/3 Mobile clients, lossy networks UDP firewall, libmsquic, ops complexity Internal service-to-service traffic
Rate/concurrency limiter middleware Protecting downstreams, fairness Rejections (429) by design When the real problem is blocking code

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says Kestrel is rarely the bottleneck and mentions blocking code. Why: Checks the most common real throughput limit: ThreadPool starvation and how to diagnose it.
    How to answer

    ThreadPool starvation happens when pool threads are blocked faster than the pool can add new ones, so queued work (requests, continuations, timers) waits. Symptoms: latency rises sharply while CPU stays low, the pool queue length grows, thread count climbs slowly, health checks time out and Kestrel logs heartbeat warnings mentioning possible starvation. I confirm it with dotnet-counters (queue length and thread count), then take dotnet-stack snapshots or a dump to see what the threads are blocked on, usually .Result, .Wait(), synchronous I/O or locks. The fix is to make that code asynchronous; raising SetMinThreads only buys time.

  2. When: Candidate mentions KeepAliveTimeout and load balancer idle timeouts. Why: Checks how keep-alive and shutdown behaviour interact with load balancers during deployments.
    How to answer

    A burst of 502s on every rollout is almost always a shutdown or start-up race, not a code bug. On termination, Kubernetes sends SIGTERM to the container and removes the pod from the Service endpoints at the same time, so the ingress keeps sending requests for a few seconds to a process that is closing. I fix it in layers, with numbers that must add up: a preStop sleep (about 10 s) so routing updates first; HostOptions.ShutdownTimeout sized from the measured p99.9 request duration (say 15 s) so in-flight requests drain; and terminationGracePeriodSeconds larger than both together (35 s). Then readiness probes that only pass when the app is warm and fail once ApplicationStopping fires, separate from liveness, plus maxUnavailable: 0. I also check keep-alive timeouts: if Kestrel closes idle connections before the proxy does, the proxy reuses a dead connection and returns 502. The trade-off is slightly slower deployments for zero dropped requests.

🛠 Real-world problems: how you handle them

Catalogue API plateaued at 3,000 RPS and the team wanted to tune Kestrel
Situation
A product catalogue API [at company] on [AKS, 4 pods of 2 vCPU] needed to handle a [Black Friday] forecast of [8,000 RPS]. Load tests plateaued at [3,000 RPS] with p99 latency over [2 s], and the team proposed raising Kestrel connection limits and HTTP/2 stream counts.
Signals
CPU sat at [35%] during the plateau; latency rose sharply above [~400] concurrent users; Application Insights showed SQL and Redis calls fast; no 413/431 errors or connection refusals.
Investigation
Ran `dotnet-counters` during an Azure Load Testing run: `threadpool-queue-length` climbed into the thousands and `threadpool-thread-count` grew by about one per second. A `dotnet-dump` showed most threads blocked in `Task.Wait` inside a custom authorisation filter calling a feature-flag service synchronously.
Resolution
Made the filter async end to end and cached feature flags for [30 s]. Left Kestrel limits at defaults except a lower global body limit. Re-ran the load test: [9,000 RPS] with p99 under [150 ms] on the same pods.
Prevention
Added the Microsoft.VisualStudio.Threading analysers to flag sync-over-async, a ThreadPool queue-length alert in Azure Monitor, and a load test stage before major events with counters captured automatically.

How to tell it (STAR)

**S:** Our [catalogue API] plateaued at [3,000 RPS] ahead of [Black Friday] and the team wanted to raise Kestrel limits. **T:** I was asked to tune the server to reach [8,000 RPS]. **A:** Instead of changing limits, I ran a load test with dotnet-counters, saw the ThreadPool queue growing while CPU was low, took a dump, and found a synchronous call in an authorisation filter. I made it async and cached the flags. **R:** Throughput reached [9,000 RPS] with p99 under [150 ms] on the same hardware, with no Kestrel changes, and we added analysers and alerts so it couldn't creep back.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me