Designing Request Timeouts in ASP.NET Core: Managing Slow Clients and Long-Running Operations

Designing Request Timeouts in ASP.NET Core: Managing Slow Clients and Long-Running Operations

An HTTP request failing does not always mean that the application is broken. An external service may be slow, a database query may exceed its expected duration, or a client may upload the request body extremely slowly. If these requests remain open indefinitely, they consume thread-pool work, connection-pool capacity, database connections, and memory.

In ASP.NET Core, timeout design is more than setting HttpClient.Timeout. A reliable implementation defines separate limits for the client connection, the endpoint, outbound calls, and database commands. It also ensures that a timeout can actually stop downstream work by propagating CancellationToken correctly.

The real problem: a report endpoint slows down the system

Consider GET /api/reports/daily in a sales application. The endpoint reads the day’s sales from a database, calls an external exchange-rate service, and builds the final report.

Under normal conditions, the operation completes in 500 milliseconds. When the exchange-rate service becomes slow, requests remain open for 20 or 30 seconds. With 100 concurrent requests, several resources are affected:

  • Incomplete tasks accumulate inside the application.
  • Database connections remain occupied for longer.
  • Outbound connections stay busy in the HTTP connection pool.
  • Clients may start their own retries because the response is taking too long.

A single slow dependency can therefore affect unrelated endpoints. The solution is to define explicit, measurable limits at each layer.

Separate the timeout layers

LayerPurposeExample limit
KestrelLimit clients that send headers or bodies too slowly30 seconds for request headers
EndpointLimit the total execution time of an HTTP request5 seconds
HttpClientLimit how long an outbound HTTP call waits2 seconds
DatabasePrevent an expensive command from consuming resources indefinitely3 seconds

These values do not have to be identical. If the endpoint budget is five seconds, allowing an outbound service call to wait ten seconds is not useful. Dependency timeouts should normally be shorter than the total endpoint budget.

Use request timeouts at the endpoint level

ASP.NET Core’s request-timeout middleware supports global and endpoint-specific policies. When a timeout is reached, the middleware cancels HttpContext.RequestAborted. This does not automatically stop arbitrary application code; downstream operations must observe the token.

using Microsoft.AspNetCore.Http.Timeouts;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRequestTimeouts(options =>
{
    options.AddPolicy("report", TimeSpan.FromSeconds(5));
});

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

var app = builder.Build();

app.UseExceptionHandler();
app.UseRouting();
app.UseRequestTimeouts();

app.MapGet("/api/reports/daily", async (
    HttpContext httpContext,
    DailyReportService reportService) =>
{
    var report = await reportService.CreateAsync(
        httpContext.RequestAborted);

    return Results.Ok(report);
}).WithRequestTimeout("report");

app.Run();

The endpoint has a five-second total budget, while the exchange-rate call waits for at most two seconds. Running the timeout middleware after routing allows endpoint metadata to be evaluated correctly.

Do not break the CancellationToken chain

Configuring a timeout without passing its token only causes the application to return a late error. The underlying work may continue in the background. Service and repository methods should therefore accept a cancellation token and pass it to asynchronous operations.

public sealed class DailyReportService(
    SalesDbContext db,
    ExchangeRateClient exchangeRateClient)
{
    public async Task<DailyReport> CreateAsync(
        CancellationToken cancellationToken)
    {
        var sales = await db.Sales
            .AsNoTracking()
            .Where(x => x.SoldAt >= DateTime.UtcNow.Date)
            .ToListAsync(cancellationToken);

        var rate = await exchangeRateClient
            .GetUsdRateAsync(cancellationToken);

        return new DailyReport(
            sales.Count,
            sales.Sum(x => x.Total),
            rate);
    }
}

public sealed class ExchangeRateClient(HttpClient httpClient)
{
    public async Task<decimal> GetUsdRateAsync(
        CancellationToken cancellationToken)
    {
        using var response = await httpClient.GetAsync(
            "latest?base=TRY",
            cancellationToken);

        response.EnsureSuccessStatusCode();

        var result = await response.Content
            .ReadFromJsonAsync<ExchangeRateResponse>(
                cancellationToken);

        return result?.Usd ?? throw new InvalidOperationException(
            "The exchange-rate response did not contain USD.");
    }
}

Both ToListAsync and GetAsync receive the same token. If the endpoint times out, the database query and outbound request receive the cancellation signal. Libraries may react at different speeds, but failing to pass the token guarantees that the operation cannot respond cooperatively.

HttpClient timeout is not request timeout

HttpClient.Timeout limits an outbound HTTP operation made by a particular client. An endpoint timeout controls the complete application request, which may include database work, external calls, mapping, and serialization.

A practical budget might look like this:

  • Total endpoint duration: 5 seconds
  • Database query: approximately 3 seconds
  • External exchange-rate service: 2 seconds
  • Serialization and network overhead: the remaining budget

If retries are added, the entire budget must be recalculated. A two-second timeout with three attempts may exceed a five-second endpoint budget after connection and scheduling overhead are included. For side-effecting operations such as payments, inventory updates, or order creation, automatic retries should only be considered after idempotency has been designed.

Protect against slow clients with Kestrel settings

Endpoint timeouts protect application work after request processing begins. If a client sends request headers or a body very slowly, Kestrel-level timeouts and minimum data-rate settings become important.

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.RequestHeadersTimeout =
        TimeSpan.FromSeconds(30);

    options.Limits.KeepAliveTimeout =
        TimeSpan.FromSeconds(120);
});

These values must reflect the traffic profile. Setting extremely low limits without considering mobile networks, large request bodies, HTTP/2 multiplexing, and proxy behavior can reject legitimate users. The goal is to remove connections that are inactive or unreasonably slow, not to punish normal network variability.

Design timeout responses and logging

Timeout responses should be predictable for clients. 504 Gateway Timeout can be appropriate for an endpoint that cannot complete because a dependency failed to respond. However, clients must not assume that the server-side operation continues successfully after receiving a timeout response. If the work cannot be cancelled safely, it should be moved out of the HTTP request and into a durable background job.

Without recording sensitive data, timeout logs should include:

  • Endpoint name and HTTP method
  • Correlation or trace identifier
  • Timeout category: endpoint, outbound service, or database
  • The stage where cancellation occurred
  • Elapsed time and resulting status code

OperationCanceledException is not always an application error. The client may have disconnected, or the server may have enforced its timeout. Logging every cancellation as an error creates alert noise. Expected request cancellations can use a lower log level, while dependency failures and unexpected exceptions should be recorded separately.

When should the work move to a background job?

If an operation cannot reliably complete within a few seconds, increasing the HTTP timeout indefinitely is usually the wrong solution. A report that processes 500,000 rows can use this workflow instead:

  1. The API validates the request and places a job in a queue.
  2. The API returns 202 Accepted with a job identifier.
  3. A background worker generates the report and writes it to controlled storage.
  4. The client checks a status endpoint for progress.
  5. When ready, the API provides a time-limited download link.

This design avoids keeping an HTTP connection open for a long-running operation. It still requires careful handling of durable job state, retries, duplicate execution, failure recovery, and authorization for the resulting file.

Implementation checklist

  • Does every endpoint have a realistic total duration budget?
  • Do outbound HTTP calls use explicit timeouts?
  • Is HttpContext.RequestAborted passed to database and external-service layers?
  • Are Kestrel slow-client settings appropriate for the traffic profile?
  • Can retries exceed the total request budget?
  • Can logs distinguish client disconnects from server-enforced timeouts?
  • Should long-running work be removed from the HTTP request entirely?

Reliable timeout design is not about choosing one magic number. It is about defining the responsibility and lifetime of every resource involved in a request. When endpoint budgets, dependency timeouts, Kestrel protections, and cancellation propagation work together, a slow service is less likely to become a system-wide bottleneck.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published