The CancellationToken That Never Propagated: A Subtle ASP.NET Core Timeout Bug I Missed in Code Review
The CancellationToken That Never Propagated: A Subtle ASP.NET Core Timeout Bug I Missed in Code Review In the early stages of my career, I believed that if an HTTP request had a timeout set, the system was safe. I would configure HttpClient.Timeout or use RequestAborted , and I felt protected. I was wrong. Recently, I reviewed a codebase for a .NET Core application that was experiencing…
A potentially catastrophic ASP.NET Core timeout bug slipped through code review due to a subtle cancellation context oversight. The codebase contained an ASP.NET Core API endpoint that quickly returned a 202 Accepted response while initiating a long-running background task. The expectation was that the client would remain connected, but under heavy load, the system began experiencing latency spikes and thread pool exhaustion.
The root cause was the absence of a CancellationToken propagation mechanism. When the client closed the tab or the load balancer timed out the connection, the background task continued running on the ASP.NET Core SynchronizationContext or thread pool context, consuming resources regardless of the client's disconnection. As requests surged to 1,000 per second, the thread pool became saturated due to connection pooling limits and queued CPU-bound work.
The system eventually crashed under the excessive load. The solution required two modifications: passing a CancellationToken from the top-level request into the background task and respecting the token during work execution. By incorporating this cancellation strategy, resource leaks, stale data issues, and shutdown hangs could be prevented.
Developers must always consider who is authorized to cancel tasks, using RequestAborted for request-level cancellation or the CancellationToken passed to HostedService for application lifecycle events. Failure to propagate cancellation tokens can lead to resource exhaustion, inconsistent data, and application instability.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.