Module 1 · Runtime, Dependency Injection, and Async Foundations · Lesson 2 of 9
Async, Cancellation, and Timeout Budgets
Diagnose before reading
An endpoint promises a two-second objective. Inventory takes 800 ms; pricing then receives a fresh two-second timeout. How much budget should pricing receive if 100 ms is reserved for the final response? Write the calculation, then identify what the token can and cannot guarantee.
Write your answer first. Then use this trace to check the boundary you chose.
| Point on the path | Budget accounting | What remains uncertain |
|---|---|---|
| Request enters | 2,000 ms total objective | Queueing before this boundary must be measured separately |
| Inventory returns after 800 ms | 1,200 ms remains | Token-aware work can still need cleanup time |
| Reserve 100 ms for the response | At most 1,100 ms for the next stage in this simplified trace | Real elapsed routing/serialization work also consumes the budget |
| Cancellation is requested | Observe completion and release resources | Cancellation does not prove a remote effect was rolled back |
Cancellation is cooperative
A CancellationToken is a signal, not a thread abort. Code must pass the token to operations that support it and check it in long CPU loops. Cancellation can race with successful completion, so design the operation to remain correct in either outcome.
Controller boundary
An ASP.NET Core action can accept a CancellationToken. The framework binds it to HttpContext.RequestAborted. Normally propagate it through the request-bound work instead of replacing it with CancellationToken.None. If work must survive the request, hand it off through an explicit durable workflow with its own lifetime and cancellation policy.
public async Task<IResult> GetOrder(
Guid id,
CancellationToken requestAborted)
{
var order = await service.GetAsync(id, requestAborted);
return order is null ? Results.NotFound() : Results.Ok(order);
}A service method should normally accept the token as its final parameter. Repository calls must pass it to EF Core terminal operators such as SingleOrDefaultAsync, ToListAsync, and SaveChangesAsync. HTTP calls should pass it to SendAsync.
Deadlines and timeout budgets
A request often crosses several dependencies. Giving every dependency a separate 30-second timeout can turn a 30-second user budget into minutes. Start with one end-to-end budget and allocate smaller limits to downstream calls.
public async Task<Quote> GetQuoteAsync(
QuoteRequest request,
CancellationToken callerToken)
{
using var budget = CancellationTokenSource.CreateLinkedTokenSource(callerToken);
budget.CancelAfter(TimeSpan.FromSeconds(2));
return await pricingClient.GetAsync(request, budget.Token);
}The linked source requests cancellation when the caller token is cancelled or its local timer expires. This example starts a two-second budget at method entry, not at initial request arrival; pass the remaining end-to-end budget instead of resetting it at each hop. Cancellation remains cooperative: a dependency that ignores the token can run longer, and timer scheduling or cleanup can add latency. In a mature system, prefer a deadline value propagated between services because it lets each hop calculate the remaining budget rather than resetting a full timeout. Account for clock skew with absolute deadlines and constrain untrusted caller-supplied deadlines. A token alone communicates cancellation but not the original deadline.
HttpClient timeouts
HttpClient.Timeout is a client-wide request timeout policy, not a guaranteed wall-clock upper bound. With ResponseHeadersRead, it covers receiving headers, not subsequent response-body reads. Per-operation linked cancellation is more expressive because different operations can have different budgets. If both cover the same operation, the earlier timeout or cancellation signal normally requests cancellation first; the observed exception may race with caller cancellation, completion or another failure. Body reads may need their own propagated token. Standardize the policy, log the effective deadline, and avoid stacking unrelated timeout mechanisms.
Why Task.WhenAny is easy to get wrong
A common timeout implementation races the work against Task.Delay. If the delay wins but the original operation is not cancelled and observed, the work continues in the background, consumes resources, and may later fault without proper handling.
Incorrect idea:
var completed = await Task.WhenAny(work, Task.Delay(timeout)); if (completed != work) throw new TimeoutException();
Better, when supported: give work a cancellable token, request cancellation when the budget expires, and observe its completion so cleanup and exceptions are accounted for. Awaiting cleanup may itself exceed the waiting budget. Also await the task returned by WhenAny on the success branch to propagate its result or exception; WhenAny itself does not propagate the winning task's failure. For APIs that cannot be cancelled, Task.WhenAny can limit how long the caller waits, but it cannot stop the underlying operation. State that limitation explicitly.
OperationCanceledException semantics
Do not log every OperationCanceledException as an application error. Distinguish expected caller cancellation from a local timeout when your contract and available signals allow it. IsCancellationRequested shows source state, not proof that this source caused a particular exception: cancellation sources and dependency failures can race. The following example deliberately gives caller cancellation precedence if both sources are signalled; a caller token can also represent host shutdown, not only a disconnected client.
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(callerToken, timeout.Token);
try
{
return await dependency.CallAsync(linked.Token);
}
catch (OperationCanceledException) when (callerToken.IsCancellationRequested)
{
logger.LogDebug("Request was cancelled by the caller");
throw;
}
catch (OperationCanceledException ex) when (timeout.IsCancellationRequested)
{
throw new TimeoutException("Pricing dependency exceeded its budget", ex);
}Be careful when translating exceptions: preserve the original exception as InnerException and do not convert host shutdown cancellation into a retryable dependency timeout. This sketch assumes the dependency uses the supplied linked token for cooperative cancellation. An unrelated cancellation exception needs separate handling; the filters alone cannot establish causality. Cancellation and timeout exceptions are not automatically retryable.
CPU-bound work
Async does not make CPU work free. A CPU loop that promises cooperative cancellation should periodically check the token, for example with token.ThrowIfCancellationRequested(). A single long-running library call may not support interruption. The interval is a trade-off: checking every iteration may add overhead; checking too rarely makes shutdown and client cancellation sluggish.
for (var i = 0; i < rows.Count; i++)
{
if ((i & 1023) == 0)
token.ThrowIfCancellationRequested();
Process(rows[i]);
}Do not use Task.Run around arbitrary server work just to make a method appear asynchronous. ASP.NET Core already schedules requests on thread-pool threads. Task.Run can hide blocking I/O and makes capacity harder to reason about.
Background services and graceful shutdown
BackgroundService.ExecuteAsync receives stoppingToken. Pass it to queue reads, delays, network calls, and database operations. Decide what an in-flight message should do on shutdown: abandon safely for redelivery, checkpoint, or finish within a shutdown grace period. Never swallow the shutdown token and start unlimited non-cancellable work.
Cancellation and data consistency
A database cancellation request does not prove the server rolled back every side effect. Define transaction boundaries and idempotency separately. If a request sends a payment then gets cancelled before recording the result, a retry may duplicate the payment unless an idempotency key protects the external call.
Testing cancellation
- Use a controllable fake dependency that waits on the provided token.
- Cancel a
CancellationTokenSourceand assert the method completes promptly. - Verify that cancellation reaches EF Core or HttpClient collaborators. Require token identity only when direct forwarding is the contract; linked tokens are different values but should respond to the intended sources. Database providers may not honor cancellation promptly or at all.
- Test caller cancellation separately from local timeout.
- Avoid error-level noise for expected cancellation, while retaining genuine dependency or cleanup failures even when cancellation also occurs.
- Verify resources and scopes are disposed after cancellation.
Interview scenario
An endpoint has a two-second SLA, calls inventory and pricing in parallel, then writes a quote. Explain the shared deadline, cancellation propagation to both calls, how you observe both tasks, what happens if one call fails, and how the final write is protected against duplicate execution. Task.WhenAll observes completion but does not automatically cancel siblings; request cancellation explicitly when appropriate, then observe every task. Mention telemetry fields such as remaining budget, dependency duration, cancellation source, and correlation ID.
Check the boundary
Work ignores its cancellation token. Task.WhenAny returns the timeout task, and the method throws TimeoutException. What can you conclude?
Show answer
Correct answer: B
WhenAny selects a completed task; it does not terminate the other task. Request cooperative cancellation when supported, observe completion/faults and define ownership when the operation cannot stop.
Hint: Separate ending the wait from ending the operation.
Two-minute interview practice
Attempt both before comparing. State the assumption, the repair and one limit of your evidence.
- Both caller and local-budget tokens are signalled before the exception filters run. Which branch in this lesson wins, and what does that prove?
- A downstream API receives a linked token different from the caller token. What should your fake dependency test?
Hint. Revisit the ownership, time, transaction or measurement boundary in the trace table.
Check your reasoning.
- The caller-cancellation filter comes first and therefore wins in this example. It implements a classification precedence; flags alone do not establish which signal caused the exception.
- Test that cancelling each intended source reaches the operation and that completion/faults and cleanup are observed. Require token identity only when direct forwarding, rather than linkage, is the contract.
Evidence for the repair
For the opening arithmetic, 2,000 − 800 − 100 = 1,100 ms. This is budget bookkeeping, not evidence that a provider obeys cancellation or that the response completes within two seconds.
Practice
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·