Interview question
Propagate request cancellation through an EF Core query
Carries the ASP.NET Core request token into a bounded EF Core query while keeping cancellation separate from business rollback guarantees.
TL;DR
Carries the ASP.NET Core request token into a bounded EF Core query while keeping cancellation separate from business rollback guarantees.
Cancellation propagation, async materialization, bounded results, read versus write semantics, and expected API behavior.
Practice the problem like a real interview: restate, reason, implement, and test.
An ASP.NET Core endpoint receives a CancellationToken bound to request abort. Query active customers by prefix, project a small result, cap it at 50, and pass the token into EF Core. Do not catch and convert normal request cancellation into a 500 response.
When the caller disconnects during a slow database read, the provider gets a cancellation request and the server can release work sooner when supported.
OperationCanceledException as expected when the request token is cancelled.I accept the request token at the endpoint and pass it all the way to ToListAsync. Cancellation reduces waste, but query shape, indexes, and timeouts still matter. For a read, abandoning work is usually straightforward; for writes, cancellation can leave commit outcome uncertain and needs idempotency or reconciliation.
[HttpGet("customers/search")]
public async Task<ActionResult<IReadOnlyList<CustomerSearchItem>>> SearchCustomers(
[FromQuery] string prefix,
CancellationToken cancellationToken)
{
var normalized = prefix.Trim();
if (normalized.Length < 2)
return BadRequest("Enter at least two characters.");
var customers = await db.Customers
.AsNoTracking()
.Where(customer => customer.Name.StartsWith(normalized))
.OrderBy(customer => customer.Name)
.ThenBy(customer => customer.Id)
.Select(customer => new CustomerSearchItem(
customer.Id,
customer.Name))
.Take(50)
.ToListAsync(cancellationToken);
return Ok(customers);
}
The provider receives one bounded query and a cancellation token for the asynchronous command. Whether cancellation is immediate depends on provider and database support. Track cancelled dependency calls separately from genuine failures so normal client disconnects do not create noisy error alerts.
Next in EF Core Labs: Bounded EF Import