5 min readRishi

Pass the CancellationToken or the Work Continues After the Client Left

Pass the CancellationToken or the Work Continues After the Client Left

The browser closed the tab. The load balancer timed out. The caller retried. Your action is still in ToListAsync, and the connection it borrowed is still checked out. ASP.NET Core already knows the request is over. It exposes that as HttpContext.RequestAborted. A CancellationToken parameter on the action is bound to that token. If you do not pass it down, nothing downstream is listening.

This is not a style rule. Under a disconnect storm it is how the DbContext pool and the HttpClient handler queue saturate while the endpoint still looks healthy in a liveness probe.

Forward the token you were given

[HttpGet("{id}")]
public async Task<IActionResult> Get(Guid id, CancellationToken cancellationToken)
{
    var order = await db.Orders
        .AsNoTracking()
        .FirstOrDefaultAsync(o => o.Id == id, cancellationToken);

    if (order is null) return NotFound();
    return Ok(order);
}

The same argument goes to SaveChangesAsync, HttpClient.SendAsync, ReadAsStreamAsync, and any ChannelReader.ReadAsync you own. A helper that accepts CancellationToken cancellationToken = default and is called without one will run to its own timeout. default is CancellationToken.None. It never fires because the client left.

Minimal APIs are the same shape: take CancellationToken as a parameter. The binder uses RequestAborted. You do not need to touch HttpContext unless you are writing middleware.

Compose a deadline with a linked source

A request token says "the caller is gone." A timeout says "this dependency is too slow even if the caller is still waiting." SendAsync takes one token. Link them.

using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
linked.CancelAfter(TimeSpan.FromSeconds(3));
await client.SendAsync(request, linked.Token);

The three-second cap still applies when the client is waiting. The request token still applies when the client is not. Do not create a second CancellationTokenSource that ignores the request token and only has CancelAfter. That is how a disconnected client still holds a connection for the full timeout.

Dispose the linked source. A leaked CancellationTokenSource is a timer and a list of callbacks. In a hot action that is a memory leak with a polite name.

A cancel is not a server failure

RequestAborted throws OperationCanceledException (often as TaskCanceledException) out of the call you passed it to. If a broad catch (Exception) turns that into HTTP 500, two things go wrong:

  1. Logs fill with errors for people who navigated away.
  2. The client's retry treats a disconnect as a failed write.

Let the exception propagate when cancellationToken.IsCancellationRequested is true. ASP.NET Core will complete the response as an abort, not as an application fault. If you have exception-handling middleware, exclude OperationCanceledException:

app.UseExceptionHandler(error =>
{
    error.Run(async context =>
    {
        var feature = context.Features.Get<IExceptionHandlerFeature>();
        if (feature?.Error is OperationCanceledException)
        {
            context.Response.StatusCode = StatusCodes.Status499ClientClosedRequest; // or 400
            return;
        }
        context.Response.StatusCode = StatusCodes.Status500InternalServerError;
        await context.Response.WriteAsJsonAsync(new { error = "unexpected" });
    });
});

Status 499 is nginx's convention, not an official HTTP code. Some teams use 400. Either is better than 500. Do not return 200 with an empty body — the caller that retried will assume success.

HttpClient wraps many cancels as TaskCanceledException. Check ex.CancellationToken.IsCancellationRequested or ex.InnerException is TimeoutException if you need to tell "client left" from "deadline expired." A timeout you set is a server-side decision and may deserve a 504. A client abort does not.

The awkward case: SaveChangesAsync

If the token fires after the command reached the database, the client sees a cancel and the row may have committed. You cannot tell from the exception alone. A retry of that POST needs an idempotency key, or the retry inserts a second row. The key design is the same one in write APIs.

Practical rule: pass the token into SaveChangesAsync so a cancel before the command is sent does not open a transaction. After the command is sent, treat the operation as maybe-completed and make the next POST safe to repeat.

Background work is a different token

IHostedService / BackgroundService receive stoppingToken from the host. That token fires on shutdown, not when a user closes a tab. Do not pass RequestAborted into a queue worker you kicked off with _ = DoWorkAsync(...) from an action. That work will cancel when the request ends, which is the opposite of "enqueue and return 202."

If the request starts work that must outlive the request, copy the data you need, enqueue it, and let the worker use stoppingToken. If the work is only useful while the client is connected (a stream, a long poll), pass RequestAborted and let it die with the socket.

What you are actually saving

Each abandoned request holds a pooled connection until the query finishes. That is how the pool saturates. HttpClient has the same shape: a call that ignores cancellation sits until the handler times out, which is the pressure case next to creating a client per request.

Passing the token does not make the database faster. It lets the work stop when nobody is waiting for it. Grep the action for Async( and ask, of each call, "does this listen?" If the signature has no token parameter, you cannot cancel it — wrap it only if you accept that cancel means abandoning the wait, not the work.

Keep reading

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.