Web API  

Using CancellationToken in Web API: A Complete Guide

Introduction

When building web APIs, please note that some requests may take longer than expected due to heavy processing, lengthy database queries, or network delays. In such cases, users or clients may cancel the request (for example, closing the browser tab or clicking 'Stop').

By default, your API will continue executing the request in the background even if the client has already disconnected. This wastes server resources.

This is where CancellationToken comes in. It allows the API to detect when a request has been cancelled and stop execution gracefully.

What is CancellationToken?

  • CancellationToken is a mechanism in .NET that signals when an operation should be cancelled.

  • In Web APIs, it is automatically available through the request context.

  • Developers can pass it into long-running methods and use it to stop unnecessary work when the client no longer needs the response.

Example: Using CancellationToken in Web API

  
    [HttpGet("get-data")]
public async Task<IActionResult> GetDataAsync(CancellationToken cancellationToken)
{
    try
    {
        // Simulating a long-running task
        await Task.Delay(10000, cancellationToken);

        return Ok("Data fetched successfully!");
    }
    catch (OperationCanceledException)
    {
        return StatusCode(StatusCodes.Status499ClientClosedRequest, "Request was cancelled.");
    }
}
  

How this works

- If the client waits, the API responds after 10 seconds.

- If the client cancels the request before 10 seconds, the OperationCanceledException is thrown, and we return a cancellation response.

Where to Use CancellationToken

 Long-running operations

  • Database queries

  • File uploads/downloads

  • Background tasks triggered by API calls

  Scenarios where resources are expensive

  • CPU-intensive calculations

  • Third-party API calls

  • Stream processing

  Microservices or distributed systems

  • When calling other services that may also take time

Where NOT to Use CancellationToken

 Short and quick operations

  • Simple CRUD operations that take milliseconds

 Fire-and-forget jobs

  • If the work must always be completed regardless of client cancellation (e.g., logging, auditing)

  Critical operations

  • Payment transactions

  • Database writes that must not be interrupted

Pros of Using CancellationToken

  • Improves performance → Frees resources when the request is no longer needed.

  •   Reduces server load → No wasted work on abandoned requests.

  •  Graceful handling → API responds properly instead of hanging.

  •   Better scalability → Handles multiple users more efficiently.

Cons of Using CancellationToken

  • Added complexity → Need to check for cancellation in multiple places.

  •  Error handling required → Must handle OperationCanceledException.

  • Not suitable everywhere → Some operations must be completed even if the client cancels.

Best Practices

1. Always pass CancellationToken to async operations when available.

2. Check cancellationToken.IsCancellationRequested in loops or long-running methods.

3. Handle OperationCanceledException gracefully.

4. Don’t use cancellation for critical operations that must complete.

5. Document behaviour so clients know what happens if they cancel.

Conclusion

CancellationToken is a powerful feature in Web APIs that helps improve performance, scalability, and resource management. By using it wisely, you can avoid wasting resources on requests that no longer matter and provide a smoother experience for clients.

However, it should be applied carefully. For critical or short-lived operations, cancellation may not be appropriate. The key is to use it where it adds real value—especially for long-running, resource-heavy API calls.