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?

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

Scenarios where resources are expensive

Microservices or distributed systems

Where NOT to Use CancellationToken

Short and quick operations

Fire-and-forget jobs

Critical operations

Pros of Using CancellationToken

Cons of Using CancellationToken

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.