| Secure-API-Design :👈 | 👉:HttpClientFactory: Managing HTTP Connections and Resilience |
Kestrel Web Server Architecture: Connection Handling and Performance |
Kestrel Web Server Architecture: Connection Handling and Performance
1. What Is Kestrel?
Kestrel is the built-in, cross-platform web server used by ASP.NET Core. It receives HTTP requests, processes network communication, and sends HTTP responses back to clients.
Key features:
- High-performance asynchronous networking.
- Cross-platform support: Windows, Linux, and macOS.
- Supports HTTP/1.1, HTTP/2, and HTTP/3, depending on configuration and platform.
- Supports HTTPS and TLS.
- Supports WebSockets.
- Integrates directly with the ASP.NET Core middleware pipeline.
- Can run independently or behind a reverse proxy.
2. Kestrel Architecture
Kestrel receives network traffic and passes HTTP requests to the ASP.NET Core application pipeline.
3. How Kestrel Handles a Connection
A connection is a network communication channel between a client and the server. Kestrel uses asynchronous socket operations to handle network activity efficiently.
Connection lifecycle
- Listen: Kestrel listens on configured IP addresses and ports.
- Accept: It accepts an incoming TCP connection.
- TLS handshake: For HTTPS, the connection negotiates encryption.
- HTTP processing: Kestrel identifies and processes the HTTP protocol.
- Request handling: The request enters the ASP.NET Core pipeline.
- Response: The application generates a response.
- Connection reuse or close: The connection may remain open for subsequent requests or be closed.
Connection lifecycle diagram
Note: TLS is negotiated once for a connection, not for every HTTP request. With HTTP/2 and HTTP/3, multiple request streams can share a connection.
4. TCP, HTTP and Kestrel
Understanding these layers helps explain Kestrel's responsibilities.
| Layer / Protocol | Responsibility |
|---|---|
| TCP | Reliable byte-stream communication for HTTP/1.1 and HTTP/2. |
| TLS | Encrypts communication and authenticates the server. |
| HTTP/1.1 | Request-response protocol, generally using one active request at a time per connection. |
| HTTP/2 | Multiplexes multiple request streams over one TCP connection. |
| HTTP/3 | Uses QUIC over UDP and supports multiplexed streams. |
| Kestrel | Implements the server-side HTTP handling and connects requests to ASP.NET Core. |
5. HTTP/1.1 vs HTTP/2 vs HTTP/3
| Feature | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP |
| Multiplexing | No | Yes | Yes |
| Header compression | No standard binary compression | HPACK | QPACK |
| Connection setup | TCP, optionally TLS | TCP, typically TLS | QUIC includes TLS 1.3 |
| Head-of-line blocking | Can occur | TCP-level blocking remains possible | Independent streams avoid TCP-level blocking |
6. Kestrel and Asynchronous Programming
Kestrel uses asynchronous I/O so that threads do not need to remain blocked while waiting for network operations to complete.
Traditional synchronous approach
public IActionResult GetProducts()
{
var products = dbContext.Products.ToList();
return Ok(products);
}
The synchronous database operation occupies a request-processing thread while waiting for the database operation to finish.
Asynchronous approach
public async Task<IActionResult> GetProducts()
{
var products = await dbContext.Products.ToListAsync();
return Ok(products);
}
During the asynchronous database wait, the thread can return to the ThreadPool to perform other work. When the operation completes, execution resumes.
Important: async does not make the database query itself faster. It improves thread utilization and scalability when operations spend time waiting for I/O.
7. ThreadPool and Request Processing
Kestrel uses asynchronous networking and works with .NET's ThreadPool to execute application code.
- Incoming network events are handled asynchronously.
- Application code executes on available ThreadPool threads.
- Asynchronous I/O allows threads to be reused while operations wait.
- CPU-intensive operations still consume CPU and execution time.
Important distinction
Kestrel does not create one dedicated operating-system thread for every incoming request. The number of concurrent requests is not the same as the number of threads.
8. Keep-Alive and Connection Reuse
Keep-Alive allows a connection to remain open after a response so the client can send additional requests without establishing a new connection.
Benefits:
- Reduces repeated connection setup.
- Reduces TCP and TLS handshake overhead.
- Improves efficiency for multiple requests to the same server.
HTTP/1.1 uses persistent connections by default unless the connection is closed. HTTP/2 and HTTP/3 use persistent connections with multiplexed request streams.
9. Kestrel Configuration
Configure Kestrel in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5000);
options.ListenAnyIP(5001, listenOptions =>
{
listenOptions.UseHttps();
});
options.Limits.MaxConcurrentConnections = 1000;
options.Limits.MaxRequestBodySize = 10 * 1024 * 1024;
options.Limits.RequestHeadersTimeout =
TimeSpan.FromSeconds(30);
});
var app = builder.Build();
app.MapControllers();
app.Run();
Important settings:
| Setting | Purpose |
|---|---|
| ListenAnyIP() | Listens on all available network interfaces. |
| MaxConcurrentConnections | Limits concurrent connections where applicable. |
| MaxRequestBodySize | Limits incoming request body size. |
| RequestHeadersTimeout | Limits time allowed to receive request headers. |
| KeepAliveTimeout | Controls how long an idle connection remains open. |
| MaxConcurrentUpgradedConnections | Limits concurrent upgraded connections such as WebSockets. |
Configure limits according to the workload and hosting environment. Avoid selecting arbitrary high connection limits without load testing.
10. Kestrel Behind a Reverse Proxy
In production, Kestrel commonly runs behind a reverse proxy or gateway such as Nginx, IIS, Azure Application Gateway, or YARP.
Architecture
Why use a reverse proxy?
- Centralized TLS termination.
- Load balancing across application instances.
- Request filtering and gateway-level security.
- Routing to multiple backend applications.
- Additional observability and traffic management.
When using forwarded headers, trust only known proxies or networks. Incorrectly trusting arbitrary forwarded headers can allow clients to spoof their original IP address or scheme.
Configure Forwarded Headers
using Microsoft.AspNetCore.HttpOverrides;
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto;
// Configure KnownProxies or KnownNetworks
// for your actual reverse proxy infrastructure.
});
var app = builder.Build();
app.UseForwardedHeaders();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
11. Kestrel Performance Optimization
1. Use Asynchronous I/O
- Use async/await for database and HTTP calls.
- Avoid blocking calls such as .Result and .Wait() in request paths.
- Do not wrap ordinary asynchronous I/O in Task.Run().
2. Configure Connection and Request Limits
- Set appropriate request body size limits.
- Configure header and keep-alive timeouts.
- Set connection limits based on actual resource capacity.
3. Optimize Database Access
- Use database indexes.
- Use pagination for large datasets.
- Avoid unnecessary database round trips.
- Use AsNoTracking() for suitable read-only EF Core queries.
4. Reduce Unnecessary Allocations
- Avoid repeatedly creating unnecessary objects.
- Use efficient serialization and response models.
- Consider streaming for large responses.
5. Use Compression Carefully
Response compression can reduce network traffic, especially for text-based responses. Measure its CPU overhead and configure it appropriately.
6. Use Caching
- Use in-memory caching for suitable single-instance scenarios.
- Use distributed caching when multiple instances need shared cached data.
- Set appropriate cache expiration and invalidation rules.
12. Common Kestrel Performance Problems
| Problem | Possible Cause | Solution |
|---|---|---|
| High CPU | Expensive business logic or serialization | Profile CPU and optimize hot paths. |
| High memory | Large allocations or memory leaks | Analyze memory usage and object lifetimes. |
| Slow API responses | Slow database or external API calls | Profile dependencies and optimize I/O. |
| ThreadPool starvation | Blocking calls or long synchronous work | Use asynchronous I/O and investigate blocked threads. |
| Connection exhaustion | Long-lived or excessive connections | Review connection limits, timeouts and resource usage. |
| High network traffic | Large responses or unnecessary payloads | Use pagination, compression and efficient response models. |
13. Monitoring Kestrel
Monitor the following metrics:
- Request count and request rate.
- Request duration and latency percentiles.
- HTTP response status codes.
- Active connections.
- Request queueing and rejected requests.
- CPU and memory usage.
- ThreadPool queue length and thread count.
- GC collections and allocation rate.
- Database and external service latency.
Useful tools include:
- dotnet-counters
- dotnet-trace
- dotnet-monitor
- Application Insights
- OpenTelemetry
- Visual Studio Profiler
Example: Monitor .NET Runtime Counters
dotnet-counters monitor --process-id <PID> System.Runtime
This helps observe runtime metrics such as CPU usage, GC activity, allocation rate, and ThreadPool behavior.
14. Kestrel vs IIS vs Nginx
| Feature | Kestrel | IIS | Nginx |
|---|---|---|---|
| Type | ASP.NET Core web server | Web server for Windows | Web server / reverse proxy |
| Platform | Cross-platform | Windows | Cross-platform |
| ASP.NET Core integration | Native | ASP.NET Core Module integration | Reverse proxy to Kestrel |
| Reverse proxy | Can be backend | Yes | Yes |
| Common usage | Hosts ASP.NET Core applications | Windows hosting | Linux reverse proxy and load balancing |
15. Best Practices
- Use the current supported .NET release.
- Enable HTTPS in production.
- Use asynchronous I/O for network and database operations.
- Configure appropriate request and connection limits.
- Use a reverse proxy where required by the deployment architecture.
- Trust forwarded headers only from known proxies.
- Monitor latency, CPU, memory and ThreadPool behavior.
- Use load testing before changing performance settings.
- Avoid blocking operations in request-processing paths.
- Keep database and external service calls efficient.
16. Interview Questions
Q1. What is Kestrel?
Kestrel is the cross-platform web server used by ASP.NET Core to handle HTTP requests and responses.
Q2. Does Kestrel support HTTP/2?
Yes. Kestrel supports HTTP/2, subject to protocol and hosting configuration.
Q3. What is the difference between Kestrel and IIS?
Kestrel is the ASP.NET Core web server. IIS is a Windows web server that can host or reverse-proxy ASP.NET Core applications.
Q4. Why is asynchronous programming important in Kestrel?
It allows threads to be reused while operations wait for network or database I/O, improving scalability under concurrent workloads.
Q5. What is Keep-Alive?
Keep-Alive allows a network connection to be reused for multiple HTTP requests instead of establishing a new connection for each request.
Q6. What is HTTP/2 multiplexing?
It allows multiple independent HTTP request and response streams to share one TCP connection.
Q7. What is ThreadPool starvation?
It occurs when available ThreadPool threads are insufficient to process queued work promptly, often because threads are blocked for long periods.
Q8. What is the purpose of MaxRequestBodySize?
It limits the size of incoming HTTP request bodies to help control resource consumption.
Q9. Why use Kestrel behind Nginx or IIS?
A reverse proxy can provide TLS termination, load balancing, routing, filtering and other edge-level capabilities.
Q10. How do you troubleshoot slow Kestrel APIs?
Measure request latency, CPU, memory, ThreadPool behavior, database latency and external service calls. Use profiling and distributed tracing to locate the bottleneck.
Conclusion
Kestrel is the network-facing web server at the core of ASP.NET Core. It uses asynchronous networking, HTTP protocol handling and integration with the ASP.NET Core request pipeline to support high-concurrency APIs.
Key takeaway: Kestrel performance is not determined by the web server alone. Application code, database operations, external dependencies, network behavior, connection management and resource configuration all contribute to overall API performance.
| Secure-API-Design :👈 | 👉:HttpClientFactory: Managing HTTP Connections and Resilience |