HTTP connections are usually something developers do not think about once an application is running. You create an HttpClient, send requests, and expect the networking stack to take care of the rest.
That works well until an application runs for days or weeks.
Long-lived .NET services can encounter stale connections, DNS changes, backend failovers, load-balancer changes, and network infrastructure changes while the application itself continues running. If connections are kept alive for too long, the application may continue communicating with an endpoint that is no longer the best destination.
This is where HTTP connection lifetime becomes an operational concern.
This article explains how to benchmark HTTP connection eviction in .NET, how connection lifetime affects long-running applications, and how to design a test that produces useful production-oriented measurements rather than a misleading microbenchmark.
Why HTTP Connection Lifetime Matters
Modern .NET applications commonly use HttpClient through IHttpClientFactory. Under the hood, HTTP connections are managed by SocketsHttpHandler.
A connection can remain available for reuse instead of establishing a new TCP connection for every request. Connection reuse is important because repeatedly creating connections can introduce unnecessary DNS lookups, TCP handshakes, TLS negotiation, latency, and resource consumption.
However, connection reuse also creates an important trade-off.
Consider a service that initially resolves:
api.example.internal -> 10.0.1.20
Later, DNS changes the destination:
api.example.internal -> 10.0.2.20
If an existing HTTP connection remains reusable, the application may continue using that connection rather than immediately establishing a new connection to the newly resolved address.
Connection lifetime controls how long an established connection can remain in service before it is eventually replaced.
The goal is not simply to make the lifetime as short as possible. Short lifetimes increase connection establishment overhead. Very long lifetimes can reduce the application's ability to react quickly to infrastructure changes.
The right value depends on the workload and network architecture.
Understanding SocketsHttpHandler Connection Lifetime
A common configuration is:
services.AddHttpClient("OrdersApi")
.UseSocketsHttpHandler((handler, _) =>
{
handler.PooledConnectionLifetime = TimeSpan.FromMinutes(5);
});
The important setting here is:
handler.PooledConnectionLifetime = TimeSpan.FromMinutes(5);
It tells the HTTP connection pool how long an established connection is allowed to remain in the pool before it becomes eligible for replacement.
The setting should not be interpreted as "close every connection exactly after five minutes." Connection eviction and reuse depend on the connection pool and request activity.
For a more explicit setup, you can register the handler yourself:
services.AddHttpClient("OrdersApi")
.ConfigurePrimaryHttpMessageHandler(() =>
new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
MaxConnectionsPerServer = 100
});
These properties solve different problems:
| Setting | Purpose |
|---|---|
| PooledConnectionLifetime | Limits how long pooled connections are retained |
| PooledConnectionIdleTimeout | Removes connections that remain unused for too long |
| MaxConnectionsPerServer | Controls concurrent connections to a server |
| ConnectTimeout | Limits how long establishing a connection can take |
A common mistake is to treat idle timeout and connection lifetime as interchangeable. They are not.
A connection can be actively reused while approaching its configured lifetime. An idle connection can be removed because it has been unused even if its maximum lifetime has not been reached.
Designing a Useful Benchmark
A meaningful benchmark should test more than request throughput.
For connection eviction, the important questions are:
How quickly does the application stop using an old connection?
How much connection churn does a short lifetime introduce?
Does request latency increase when connections are frequently recreated?
How does TLS affect connection establishment cost?
What happens when the backend destination changes?
Does the chosen lifetime provide an acceptable balance between reuse and endpoint freshness?
A useful experiment can compare several configurations:
Experiment A: No intentional lifetime restriction
Experiment B: 1-minute connection lifetime
Experiment C: 5-minute connection lifetime
Experiment D: 15-minute connection lifetime
Experiment E: 30-minute connection lifetime
The exact values are workload-dependent. They are useful as experimental points, not universal recommendations.
Building the Benchmark Application
A simple .NET worker can generate continuous HTTP traffic.
using System.Diagnostics;
using System.Net.Http;
var handler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2)
};
using var client = new HttpClient(handler);
while (true)
{
var stopwatch = Stopwatch.StartNew();
try
{
using var response = await client.GetAsync(
"https://localhost:5001/health");
stopwatch.Stop();
Console.WriteLine(
$"Status: {(int)response.StatusCode}, " +
$"Latency: {stopwatch.ElapsedMilliseconds} ms");
}
catch (Exception ex)
{
stopwatch.Stop();
Console.WriteLine(
$"Request failed after {stopwatch.ElapsedMilliseconds} ms: {ex.Message}");
}
await Task.Delay(TimeSpan.FromSeconds(1));
}
The important part is that the same HttpClient remains alive for the entire experiment.
Creating a new HttpClient inside the loop would test a completely different scenario and would make the connection-pooling experiment difficult to interpret.
Measuring Connection Eviction
Request latency alone is not enough.
Suppose a benchmark reports:
Average latency: 14 ms
That does not tell us whether the application reused one connection for the entire test or repeatedly created new connections.
You should collect several measurements.
Request Latency
Record at least:
Average latency
Median latency
p95 latency
p99 latency
Failed requests
Timeout count
Tail latency is particularly useful because connection establishment can create occasional latency spikes.
Connection Establishment
Track connection establishment events through .NET networking diagnostics.
A benchmark can also use structured logging around connection-related events rather than relying only on application-level request logs.
For example:
using var activity = new Activity("HTTP Benchmark");
activity.Start();
var stopwatch = Stopwatch.StartNew();
try
{
using var response = await client.GetAsync(url);
stopwatch.Stop();
Console.WriteLine(
$"StatusCode={(int)response.StatusCode} " +
$"ElapsedMs={stopwatch.ElapsedMilliseconds}");
}
finally
{
activity.Stop();
}
Join the conversation! Your thoughts help the community grow.