Kestrel Web Server Architecture: Connection Handling and Performance :👈 👉:Building Resilient Applications Using Polly

ASP.NET Core HttpClientFactory: Managing HTTP Connections and Resilience

ASP.NET Core HttpClientFactory: Managing HTTP Connections and Resilience

1. What is HttpClientFactory?

IHttpClientFactory is a built-in .NET feature used to create and manage HttpClient instances efficiently.

It helps applications communicate with external APIs and services while managing underlying HTTP connections, DNS changes, connection pooling, logging, and resilience.

It is available through dependency injection using the AddHttpClient() extension method.

2. Why do we need HttpClientFactory?

Consider an application that calls an external payment API, customer API, and inventory API.

A common mistake is creating a new HttpClient for every request:

public async Task<string> GetData()
{
    using var client = new HttpClient();
    return await client.GetStringAsync(
        "https://api.example.com/products");
}

This approach can cause problems when used repeatedly because each HttpClient may create its own underlying connection pool. Disposing clients frequently can close connections and contribute to socket exhaustion.

Another approach is keeping one static HttpClient forever. Although this reuses connections, it can retain outdated DNS information because existing connections may continue using an old destination.

HttpClientFactory addresses these problems by managing and reusing underlying HTTP handlers.

3. HttpClientFactory Architecture

ASP.NET Core Application Dependency Injection IHttpClientFactory HttpClient HttpMessageHandler Connection Pool External API

Important components:

  • IHttpClientFactory: Creates configured HttpClient instances.
  • HttpClient: Sends HTTP requests and receives responses.
  • HttpMessageHandler: Handles the underlying HTTP communication.
  • SocketsHttpHandler: Manages connections, connection pooling, DNS-related connection behavior, and transport settings.
  • Connection Pool: Reuses established connections instead of repeatedly creating new ones.

4. Registering HttpClientFactory

Register HttpClientFactory in Program.cs.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();

Now inject IHttpClientFactory wherever an HTTP client is required.

5. Using IHttpClientFactory

Example: Calling an external product API.

public class ProductService
{
    private readonly IHttpClientFactory _httpClientFactory;
    public ProductService(
        IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }
    public async Task<string> GetProductsAsync()
    {
        var client = _httpClientFactory.CreateClient();
        var response = await client.GetAsync(
            "https://api.example.com/products");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

What happens?

  1. The application requests an HttpClient from the factory.
  2. The factory creates a client with its configured settings.
  3. The client uses a managed HTTP handler.
  4. The handler reuses connections from its connection pool where possible.
  5. The response is returned to the application.

6. Named HttpClient

Named clients are useful when an application communicates with multiple external APIs that require different configurations.

Registration:

builder.Services.AddHttpClient("ProductApi", client =>
{
    client.BaseAddress =
        new Uri("https://products.example.com/");
    client.Timeout = TimeSpan.FromSeconds(30);
    client.DefaultRequestHeaders.Add(
        "Accept", "application/json");
});
builder.Services.AddHttpClient("PaymentApi", client =>
{
    client.BaseAddress =
        new Uri("https://payments.example.com/");
    client.Timeout = TimeSpan.FromSeconds(20);
});

Usage:

public class ProductService
{
    private readonly IHttpClientFactory _factory;
    public ProductService(IHttpClientFactory factory)
    {
        _factory = factory;
    }
    public async Task<string> GetProductsAsync()
    {
        var client = _factory.CreateClient("ProductApi");
        var response = await client.GetAsync("api/products");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

The URL becomes:

https://products.example.com/api/products

7. Typed HttpClient

A typed client provides a dedicated class for communicating with a particular external API.

It improves maintainability, testability, and separation of concerns.

Step 1: Create a typed client.

public class ProductApiClient
{
    private readonly HttpClient _httpClient;
    public ProductApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    public async Task<List<Product>?> GetProductsAsync(
        CancellationToken cancellationToken = default)
    {
        return await _httpClient.GetFromJsonAsync<List<Product>>(
            "api/products",
            cancellationToken);
    }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 2: Register the typed client.

builder.Services.AddHttpClient<ProductApiClient>(client =>
{
    client.BaseAddress =
        new Uri("https://products.example.com/");
    client.Timeout = TimeSpan.FromSeconds(30);
});

Step 3: Inject and use it.

public class ProductsController : ControllerBase
{
    private readonly ProductApiClient _productClient;
    public ProductsController(ProductApiClient productClient)
    {
        _productClient = productClient;
    }
    [HttpGet]
    public async Task<IActionResult> Get(
        CancellationToken cancellationToken)
    {
        var products = await _productClient.GetProductsAsync(
            cancellationToken);
        return Ok(products);
    }
}

Advantages:

  • Dedicated API communication class.
  • Centralized configuration.
  • Easy dependency injection.
  • Easy unit testing by replacing or mocking dependencies.
  • Less HTTP communication code inside controllers.

8. Connection Pooling

Connection pooling means reusing existing network connections instead of creating a new connection for every HTTP request.

Creating new connections repeatedly involves additional work such as TCP connection establishment and, for HTTPS, TLS negotiation.

HttpClientFactory manages handler instances that own connection pools.

Request 1 Request 2 Request 3 HttpClientHandler Processes HTTP requests Connection Pool Connection 1 Connection 2 Connection 3 Multiple requests are handled by the same handler. Reuse available connections when possible

Benefits:

  • Reduces unnecessary connection creation.
  • Reduces connection-management overhead.
  • Helps avoid socket exhaustion caused by repeatedly creating and disposing clients.
  • Improves efficiency when communicating with external services.

9. Handler Lifetime and DNS Changes

HttpClientFactory creates and caches handlers. By default, a factory-created handler has a lifetime of two minutes.

After its configured lifetime expires, the handler is no longer used for new clients. It is eventually disposed when no longer needed.

This allows new handlers and connections to be created, helping the application respond to DNS changes.

Configuration:

builder.Services.AddHttpClient("ProductApi")
    .SetHandlerLifetime(TimeSpan.FromMinutes(5));

Important distinction:

  • HttpClient.Timeout controls how long an HTTP operation may take before timing out.
  • SetHandlerLifetime() controls how long the factory uses a handler for newly created clients.
  • PooledConnectionLifetime controls how long an individual pooled connection can be reused before it is replaced.

These settings solve different problems and should not be confused.

10. Configure SocketsHttpHandler

For more control over connection pooling, configure SocketsHttpHandler.

builder.Services.AddHttpClient("ProductApi")
    .ConfigurePrimaryHttpMessageHandler(() =>
        new SocketsHttpHandler
        {
            PooledConnectionLifetime =
                TimeSpan.FromMinutes(5),
            PooledConnectionIdleTimeout =
                TimeSpan.FromMinutes(2),
            MaxConnectionsPerServer = 50
        });

Important properties:

Property Purpose
PooledConnectionLifetime Limits how long a pooled connection can be reused.
PooledConnectionIdleTimeout Controls how long an unused connection stays in the pool.
MaxConnectionsPerServer Limits concurrent connections to a server for the handler.
ConnectTimeout Limits the time allowed to establish a connection.

Choose limits based on the downstream service, expected concurrency, and HTTP protocol. Do not set arbitrary low connection limits because they can create request queues.

11. What is HTTP Resilience?

Resilience means designing an application to continue operating reliably when external services are slow, temporarily unavailable, or returning errors.

For example, imagine an e-commerce application calling a payment service.

The payment service may temporarily experience:

  • Network failures.
  • Temporary server errors (HTTP 5xx).
  • Rate limiting (HTTP 429).
  • Slow responses and timeouts.
  • Temporary service unavailability.

Without resilience, temporary failures may cause application requests to fail immediately or overload the downstream service through uncontrolled retries.

12. Common Resilience Strategies

12.1 Retry Pattern

Retry means attempting an operation again when a temporary failure occurs.

Example: A service returns HTTP 503. The client waits briefly and retries the request.

Request External API Temporary failure? YES Wait Retry Request Retry NO Return Response

Best practices:

  • Retry only appropriate transient failures.
  • Use a limited number of attempts.
  • Use exponential backoff.
  • Add jitter to avoid synchronized retries.
  • Respect the downstream service's Retry-After guidance when applicable.

Warning: Do not blindly retry payment operations or other non-idempotent operations. A request may have succeeded on the server even if the client did not receive the response. Use idempotency keys or another safe deduplication mechanism where supported.

12.2 Circuit Breaker Pattern

Circuit breaker temporarily stops sending requests to a failing service.

It prevents repeated requests from overwhelming an unhealthy downstream service.

It generally has three states:

  • Closed: Requests are allowed. Failures are monitored.
  • Open: Requests are blocked temporarily.
  • Half-open: A limited number of test requests are allowed to check recovery.
CLOSED Failures exceed threshold OPEN Wait duration HALF-OPEN Success Failure CLOSED OPEN

12.3 Timeout

A timeout limits how long the application waits for an HTTP operation.

builder.Services.AddHttpClient("ProductApi", client =>
{
    client.Timeout = TimeSpan.FromSeconds(10);
});

Timeouts prevent requests from waiting indefinitely. Choose a timeout appropriate for the operation and downstream service.

Remember that a client-side timeout does not necessarily mean the server stopped processing the request.

12.4 Rate Limiting

Rate limiting controls how many requests are sent within a specified period or how much concurrent work is allowed.

It helps protect downstream services from excessive traffic.

For example, an external API may allow only 100 requests per minute for a particular account. The application should respect that limit and handle HTTP 429 responses appropriately.

13. Implementing Resilience with Microsoft.Extensions.Http.Resilience

Modern .NET applications can use Microsoft.Extensions.Http.Resilience to configure HTTP resilience policies.

The package is built on Polly resilience capabilities and integrates with HttpClientFactory.

Step 1: Install the package.

dotnet add package Microsoft.Extensions.Http.Resilience

Step 2: Register a resilient HttpClient.

builder.Services
    .AddHttpClient<ProductApiClient>(client =>
    {
        client.BaseAddress =
            new Uri("https://products.example.com/");
        client.Timeout = TimeSpan.FromSeconds(30);
    })
    .AddStandardResilienceHandler();

The standard resilience handler provides a combination of strategies, including:

  • Rate limiting for outgoing requests.
  • Total request timeout.
  • Retry for eligible transient failures.
  • Circuit breaker.
  • Attempt timeout.

Exact defaults can vary by package version. Review the package documentation and configure the strategies to match your application's requirements.

Important: Avoid adding multiple overlapping resilience handlers without understanding their combined behavior. Also, do not blindly retry non-idempotent requests.

14. Custom Resilience Configuration

You can customize the standard resilience handler.

builder.Services
    .AddHttpClient("ProductApi", client =>
    {
        client.BaseAddress =
            new Uri("https://products.example.com/");
    })
    .AddStandardResilienceHandler(options =>
    {
        options.TotalRequestTimeout.Timeout =
            TimeSpan.FromSeconds(20);
        options.AttemptTimeout.Timeout =
            TimeSpan.FromSeconds(5);
        options.Retry.MaxRetryAttempts = 2;
        options.CircuitBreaker.FailureRatio = 0.5;
        options.CircuitBreaker.MinimumThroughput = 10;
        options.CircuitBreaker.SamplingDuration =
            TimeSpan.FromSeconds(30);
        options.CircuitBreaker.BreakDuration =
            TimeSpan.FromSeconds(15);
    });

Configuration explanation:

  • TotalRequestTimeout: Maximum time for the complete operation, including retries.
  • AttemptTimeout: Maximum time for an individual attempt.
  • MaxRetryAttempts: Number of retry attempts after the initial request.
  • FailureRatio: Failure proportion used by the circuit breaker.
  • MinimumThroughput: Minimum number of requests needed before evaluating the failure ratio.
  • SamplingDuration: Time window used to evaluate failures.
  • BreakDuration: How long the circuit remains open.

These values are examples, not universal production defaults.

15. CancellationToken Support

Always consider cancellation tokens when making HTTP requests from ASP.NET Core applications.

If the user cancels a request or the server request is aborted, cancellation can stop unnecessary downstream work.

public async Task<Product?> GetProductAsync(
    int id,
    CancellationToken cancellationToken)
{
    return await _httpClient.GetFromJsonAsync<Product>(
        $"api/products/{id}",
        cancellationToken);
}

In a controller:

[HttpGet("{id}")]
public async Task<IActionResult> Get(
    int id,
    CancellationToken cancellationToken)
{
    var product = await _productClient.GetProductAsync(
        id, cancellationToken);
    if (product == null)
        return NotFound();
    return Ok(product);
}

16. Logging and Monitoring

HttpClientFactory supports logging for outgoing HTTP requests.

Useful information includes:

  • Request URL and HTTP method.
  • HTTP response status code.
  • Request duration.
  • Connection and transport errors.
  • Retry and circuit-breaker events.

For production applications, consider OpenTelemetry to collect distributed traces and metrics.

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddOtlpExporter();
    });

Configure an appropriate OpenTelemetry exporter and endpoint for your monitoring platform.

Monitor these metrics:

  • Outgoing request count.
  • HTTP error rate.
  • Request duration and latency percentiles.
  • Timeout count.
  • Retry count.
  • Circuit-breaker state changes.
  • Connection pool and socket usage where available.

17. HttpClientFactory Best Practices

  • Prefer IHttpClientFactory over creating and disposing HttpClient for every request.
  • Use typed clients for dedicated external API integrations.
  • Use named clients when multiple configurations are needed.
  • Configure appropriate timeouts.
  • Pass CancellationToken through application layers.
  • Use resilience strategies for transient failures.
  • Retry only operations that are safe to repeat.
  • Use idempotency keys for supported non-idempotent operations such as payment requests.
  • Monitor outgoing HTTP calls with logs, metrics, and distributed tracing.
  • Store API credentials securely; do not hardcode secrets.
  • Do not disable TLS certificate validation in production.
  • Do not create a new HttpClientHandler for every request.
  • Avoid storing typed clients in singleton services because typed clients are generally transient.
  • Do not capture typed clients in long-lived singleton objects.

18. Common Mistakes to Avoid

Mistake Better approach
Creating HttpClient for every request Use IHttpClientFactory.
No timeout configuration Set suitable operation timeouts.
Retrying every failure Retry only eligible transient failures.
Retrying payment requests blindly Use idempotency support and safe retry rules.
Ignoring cancellation Pass CancellationToken through the call chain.
Using a typed client in a singleton Use appropriate service lifetimes or a factory.
Ignoring HTTP 429 Respect rate limits and Retry-After.
Disabling certificate validation Use valid certificates and proper trust configuration.

19. HttpClient vs HttpClientFactory

Feature HttpClient HttpClientFactory
Purpose Sends HTTP requests. Creates and configures HttpClient instances.
Connection management Depends on the underlying handler lifecycle. Manages and reuses handlers.
Dependency injection Can be registered manually. Integrates directly with DI.
Named clients Not built in. Supported.
Typed clients Not built in. Supported.
Logging integration Requires configuration. Built-in logging integration.
Resilience integration Can be configured. Integrates with resilience handlers.

20. Real-World Microservices Example

Consider an e-commerce application with separate services:

E-Commerce API Product Service IHttpClientFactory Inventory API Payment API Resilience Handler Resilience Handler Inventory DB Payment System

Each typed client can have its own base address, timeout, authentication configuration, and resilience policy.

For example:

  • Product API calls Inventory API to check stock.
  • Order API calls Payment API to process payments.
  • Shipping API calls a third-party delivery service.

HttpClientFactory helps centralize HTTP communication configuration while resilience policies help handle temporary downstream failures.

21. Interview Questions and Answers

Q1. What is IHttpClientFactory?

It is a .NET factory service that creates configured HttpClient instances and manages their underlying HTTP handler lifetimes.

Q2. Why should we use HttpClientFactory?

It helps manage connection pooling, reduces socket exhaustion risks, supports DNS-related handler recycling, and integrates with dependency injection and logging.

Q3. What is socket exhaustion?

It is a condition where an application uses too many network sockets or connections, potentially preventing new connections from being established.

Q4. What is connection pooling?

Connection pooling reuses existing network connections instead of creating a new connection for every request.

Q5. What is the default handler lifetime?

The default factory handler lifetime is two minutes. It can be changed using SetHandlerLifetime().

Q6. What is the difference between named and typed clients?

Named clients are configured using a string name. Typed clients use dedicated classes that encapsulate communication with an external API.

Q7. What is a retry policy?

It retries an operation after an eligible temporary failure, usually with a limited number of attempts and backoff.

Q8. What is a circuit breaker?

It temporarily blocks requests to an unhealthy service to prevent repeated failures and allow recovery.

Q9. What is the difference between timeout and retry?

Timeout limits how long an operation can take. Retry attempts the operation again after an eligible failure.

Q10. What is Microsoft.Extensions.Http.Resilience?

It is a .NET package that integrates resilience strategies such as retry, timeout, and circuit breaker with HttpClientFactory.

Q11. Why should we use CancellationToken?

It allows HTTP operations to stop when the calling request is cancelled or the application no longer needs the result.

Q12. Can we use HttpClientFactory with microservices?

Yes. It is commonly used by microservices to communicate with other services and external APIs.

Q13. Should every HTTP request be retried?

No. Retries should be limited to appropriate transient failures and operations that are safe to repeat.

Q14. What is PooledConnectionLifetime?

It controls how long an individual pooled connection can be reused before it is replaced.

Q15. What is the difference between SetHandlerLifetime and PooledConnectionLifetime?

SetHandlerLifetime controls the lifetime of factory-managed handlers. PooledConnectionLifetime controls the reuse lifetime of individual pooled connections.

22. Final Summary

  • IHttpClientFactory: Creates and configures HttpClient instances.
  • Named Client: Multiple clients with different configurations.
  • Typed Client: Dedicated class for external API communication.
  • Connection Pooling: Reuses network connections.
  • Handler Lifetime: Controls how long factory-managed handlers are reused.
  • Retry: Handles eligible temporary failures.
  • Circuit Breaker: Prevents repeated calls to unhealthy services.
  • Timeout: Limits waiting time.
  • CancellationToken: Stops unnecessary work when cancellation is requested.
  • OpenTelemetry: Helps monitor outgoing HTTP requests.
🔙
Kestrel Web Server Architecture: Connection Handling and Performance :👈 👉:Building Resilient Applications Using Polly