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.
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.
"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.
MaxConcurrentConnectionsis null, meaning unlimited; if you set it, extra connections are refused, not queued.MaxRequestBodySizeis 30 million bytes, roughly 28.6 MB, and I lower it globally and raise it only on upload endpoints with[RequestSizeLimit]orDisableRequestSizeLimit. 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:RequestHeadersTimeoutof 30 seconds andMinRequestBodyDataRateof 240 bytes per second with a 5-second grace stop Slowloris-style clients holding connections open.KeepAliveTimeoutis 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-countersshowed the ThreadPool queue length climbing and thread count growing slowly, which is starvation, not Kestrel. A synchronous.Resulton 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."
| 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 |
| 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 |
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.
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
dotnet-counters.Red flags
MaxConcurrentConnections queues requests.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.
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).
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.
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.ListenOptions.Protocols = Http1AndHttp2AndHttp3, HTTPS, and libmsquic (Linux) or a supported Windows version. Browsers discover it via the Alt-Svc header that Kestrel adds automatically.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.
dotnet-counters monitor -n app System.Runtime Microsoft.AspNetCore.Server.Kestrel Microsoft.AspNetCore.Hosting: current connections, queue lengths, requests/s, ThreadPool queue length, GC.dotnet-trace for CPU hot paths.[RequestSizeLimit] and retry.RequestHeadersTimeout.Task.Delay(100).Wait() to an endpoint, load test at 500 concurrency and watch ThreadPool counters; switch to await and compare.h3 on a second request.tc netem adding 150 ms).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
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.MaxConcurrentConnections to what the pod can hold.IFormFile or ReadToEndAsync. Why it is wrong: Memory or temp disk grows with body size and concurrency. Instead: Stream the body to its destination.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.MinRequestBodyDataRate globally. Why it is wrong: Removes Slowloris protection for every endpoint. Instead: Disable it only for specific streaming endpoints via the feature.h3 in browser dev tools and open UDP on the port.maxAllowedContentLength, the ingress proxy-body-size or FormOptions reject the request before Kestrel's setting matters. Instead: Align limits across every hop.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 |
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.
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.
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.
Last updated 23 Nov 2026.