Terminating Database Functions When an ASP.NET Core Client Disconnects
Sometimes an API request is unsuccessful. A mobile application could lose its network connection, a user might shut a tab in their browser, or an HTTP client might cancel a request while the server is still processing it.
Think about an API endpoint that queries thousands of database entries to provide a report. After a few seconds, the client disconnects, but because the application never sends the request cancellation token to the database operation, the database query keeps executing.
The server is now doing work that nobody is waiting for. Under heavy traffic, these unnecessary queries can consume database connections, CPU, memory, and connection-pool capacity. They can also delay requests from users who are still connected.
ASP.NET Core provides request cancellation through HttpContext.RequestAborted. When this cancellation token is propagated through the application layers and into supported database operations, work can stop when the request is cancelled.
However, cancellation is cooperative: it requests that an operation stop; it does not guarantee that every database provider or command will terminate immediately. Understanding where to pass the token, how EF Core handles cancellation, and how to distinguish client disconnects from application failures is essential for building responsive APIs.
Why Database Queries Continue After a Client Disconnects
Consider an API that retrieves customer orders and returns them to a mobile application.
[HttpGet("customers/{customerId}/orders")]
public async Task<IActionResult> GetOrders(int customerId)
{
var orders = await _context.Orders
.Where(o => o.CustomerId == customerId)
.ToListAsync();
return Ok(orders);
}
The endpoint works correctly when the client stays connected.
However, imagine that the database takes 15 seconds to execute the query and the user closes the application after 3 seconds.
What happens next?
The HTTP connection may be closed, but the database operation has no cancellation token. The application has not explicitly requested that the query stop.
Depending on the database provider and execution state, the query can continue consuming resources even though its result is no longer needed by the client.
This becomes a serious concern when the application handles many concurrent requests.
For example:
- Users repeatedly navigate away from pages that trigger expensive queries.
- Mobile applications cancel requests when network connectivity changes.
- Frontend applications cancel previous searches when users enter new search terms.
- API gateways terminate requests after their configured timeout.
- Clients cancel requests when users switch between screens.
Without cancellation propagation, the application may continue executing unnecessary database operations.
The solution is to connect the lifetime of the HTTP request to the lifetime of the database operation.
Understand HttpContext.RequestAborted
ASP.NET Core provides the RequestAborted property through HttpContext.
It exposes a CancellationToken that is triggered when the underlying HTTP request is aborted by the client or server.
For example:
CancellationToken cancellationToken =
HttpContext.RequestAborted;
You can use this token to notify long-running operations that the request is no longer active.
A simplified execution flow looks like this:
Client sends HTTP request
|
v
ASP.NET Core receives request
|
v
Controller starts database query
|
v
Client disconnects
|
v
RequestAborted is triggered
|
v
CancellationToken is propagated
|
v
EF Core / Database Provider
|
v
Database operation receives cancellation
The important point is that ASP.NET Core does not automatically cancel every database operation just because a client disconnects.
The application must pass the cancellation token to the operations that support it.
RequestAborted is also not limited to browser disconnections. It can be triggered when the server itself aborts the request.
Pass CancellationToken Directly to Controller Actions
One of the simplest ways to implement request cancellation is to accept CancellationToken as an action parameter.
ASP.NET Core binds this parameter to the request cancellation token.
You do not need to access HttpContext manually.
For example:
[HttpGet("customers/{customerId}/orders")]
public async Task<IActionResult> GetOrders(
int customerId,
CancellationToken cancellationToken)
{
var orders = await _context.Orders
.Where(o => o.CustomerId == customerId)
.ToListAsync(cancellationToken);
return Ok(orders);
}
The cancellation token is now passed directly to ToListAsync.
When the request is cancelled, EF Core receives the cancellation request and passes it to the underlying database provider.
This is a small code change, but it can make a significant difference in applications that execute expensive queries.
Why use a CancellationToken parameter instead of HttpContext?
There are two ways to obtain the request cancellation token:
var token = HttpContext.RequestAborted;
Or:
public async Task<IActionResult> GetOrders(
CancellationToken cancellationToken)
The second approach is generally cleaner for controller actions because it makes cancellation an explicit dependency of the operation.
It also avoids passing HttpContext into application services, which should generally remain independent of ASP.NET Core request infrastructure.
For Minimal APIs, a CancellationToken parameter is also bound to the request cancellation token.
app.MapGet(
"/orders/{customerId:int}",
async (
int customerId,
AppDbContext context,
CancellationToken cancellationToken) =>
{
var orders = await context.Orders
.Where(o => o.CustomerId == customerId)
.ToListAsync(cancellationToken);
return Results.Ok(orders);
});
This makes request cancellation straightforward in both controller-based APIs and Minimal APIs.
Propagate Cancellation Through Every Application Layer
Passing a cancellation token to the controller is not enough if the application service ignores it.
Consider a typical application architecture:
Controller
|
v
Application Service
|
v
Repository
|
v
Entity Framework Core
|
v
Database
If the controller receives a cancellation token but the repository does not accept it, the cancellation request cannot reach the database operation.
A common mistake is to implement a service like this:
public async Task<List<Order>> GetOrdersAsync(int customerId)
{
return await _context.Orders
.Where(o => o.CustomerId == customerId)
.ToListAsync();
}
The method does not accept a cancellation token.
A better implementation is:
public async Task<List<Order>> GetOrdersAsync(
int customerId,
CancellationToken cancellationToken)
{
return await _context.Orders
.Where(o => o.CustomerId == customerId)
.ToListAsync(cancellationToken);
}
The controller can then call the service:
[HttpGet("customers/{customerId}/orders")]
public async Task<IActionResult> GetOrders(
int customerId,
CancellationToken cancellationToken)
{
var orders = await _orderService.GetOrdersAsync(
customerId,
cancellationToken);
return Ok(orders);
}
The service and repository should continue passing the same token until it reaches the database operation.
A consistent method signature makes cancellation easier to maintain throughout the application.
For example:
public interface IOrderRepository
{
Task<List<Order>> GetOrdersAsync(
int customerId,
CancellationToken cancellationToken);
}
Avoid creating a new CancellationTokenSource inside every repository method unless there is a specific reason to introduce a separate cancellation boundary.
The original request token should normally be propagated rather than replaced.
Understand How EF Core Handles Cancellation
EF Core provides asynchronous versions of database operations, including:
- ToListAsync
- FirstOrDefaultAsync
- SingleAsync
- AnyAsync
- CountAsync
- SaveChangesAsync
- ExecuteUpdateAsync
- ExecuteDeleteAsync
These methods accept CancellationToken parameters.
For example:
var order = await _context.Orders
.FirstOrDefaultAsync(
o => o.Id == orderId,
cancellationToken);
For a database update:
var affectedRows = await _context.Orders
.Where(o => o.Status == "Pending")
.ExecuteUpdateAsync(
setters => setters.SetProperty(
o => o.Status,
"Expired"),
cancellationToken);
For saving tracked changes:
await _context.SaveChangesAsync(cancellationToken);
In each case, the cancellation token is passed through EF Core to the database provider.
However, there is an important limitation: database providers may or may not honor cancellation in every situation.
Even when a provider supports cancellation, the database may need some time to receive and process the cancellation request.
Therefore, cancellation should be treated as a request to stop work, not an absolute guarantee that the database immediately terminates the operation.
You should also keep command timeouts configured appropriately. Cancellation and command timeout solve related but different problems.
- Cancellation allows the caller to request that an operation stop.
- Command timeout limits how long a database command can execute before the provider reports a timeout.
Using both provides better control over database operations.
Handle Cancellation Exceptions Without Logging Them as Application Failures
When a database operation is cancelled, the application may receive an OperationCanceledException or a provider-specific cancellation exception.
This is expected behavior.
Consider this implementation:
try
{
var orders = await _context.Orders
.ToListAsync(cancellationToken);
return Ok(orders);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve orders");
return StatusCode(500);
}
This catches every exception, including expected request cancellation.
As a result, normal client disconnections may appear as application errors in production logs.
A better approach is to handle cancellation separately:
try
{
var orders = await _context.Orders
.ToListAsync(cancellationToken);
return Ok(orders);
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
_logger.LogInformation(
"Order retrieval was cancelled because the request ended.");
throw;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An unexpected error occurred while retrieving orders.");
return StatusCode(500);
}
This implementation distinguishes request cancellation from unexpected application errors.
You generally should not attempt to return a normal HTTP response after the client has disconnected. Rethrowing allows the request pipeline to finish handling the cancelled operation.
Also, do not assume every OperationCanceledException means the client disconnected. An operation may have been cancelled by an application-level timeout or another cancellation source.
Check the relevant token to understand why cancellation occurred.
Use Cancellation with Long-Running Queries and Large Result Sets
Cancellation is particularly useful when an API retrieves large datasets.
Consider an endpoint that returns customer transaction history:
[HttpGet("transactions")]
public async Task<IActionResult> GetTransactions(
int customerId,
CancellationToken cancellationToken)
{
var transactions = await _context.Transactions
.Where(t => t.CustomerId == customerId)
.OrderByDescending(t => t.CreatedAt)
.ToListAsync(cancellationToken);
return Ok(transactions);
}
The application waits for the complete result set before returning the response.
If the query returns hundreds of thousands of records, the operation may consume significant database and application resources.
Passing a cancellation token allows EF Core to request cancellation while executing the query.
However, cancellation is only one part of the solution.
You should also consider:
- Adding pagination.
- Selecting only the required columns.
- Applying appropriate indexes.
- Avoiding unnecessary entity tracking.
- Limiting the maximum number of returned records.
For example:
var transactions = await _context.Transactions
.AsNoTracking()
.Where(t => t.CustomerId == customerId)
.OrderByDescending(t => t.CreatedAt)
.Select(t => new TransactionResponse
{
Id = t.Id,
Amount = t.Amount,
CreatedAt = t.CreatedAt,
Status = t.Status
})
.Take(100)
.ToListAsync(cancellationToken);
This reduces the amount of data retrieved and avoids unnecessary tracking.
Cancellation helps stop unnecessary work when the request ends, while query optimization reduces the work required when the request is still active.
Use AsAsyncEnumerable for Incremental Database Processing
Sometimes an application does not need to load the complete result set into memory.
EF Core supports asynchronous enumeration, allowing the application to process results incrementally.
For example:
public async Task ProcessTransactionsAsync(
int customerId,
CancellationToken cancellationToken)
{
var query = _context.Transactions
.AsNoTracking()
.Where(t => t.CustomerId == customerId)
.OrderBy(t => t.Id)
.AsAsyncEnumerable();
await foreach (var transaction in query
.WithCancellation(cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
await ProcessTransactionAsync(
transaction,
cancellationToken);
}
}
This approach avoids creating a complete List of transaction entities before processing starts.
The application reads and processes records as they become available.
It is useful for:
- Exporting large datasets.
- Processing reports.
- Generating CSV files.
- Transforming records.
- Sending data to another service.
However, streaming does not mean that the database connection is released after every row. The data reader and database connection generally remain active while enumeration is in progress.
If processing each record involves slow external operations, the query can keep a database connection occupied for a long time.
For large processing jobs, consider fetching records in smaller batches using pagination and releasing the database context between batches.
Also, EF Core does not support multiple parallel operations on the same DbContext instance. Avoid starting another query on the same context while the current asynchronous enumeration is still active.
Combine Request Cancellation with an Application-Level Timeout
A client may remain connected even when a database query takes too long.
For example, a frontend may have a 10-second response expectation, but the database query may continue running for 60 seconds.
Request cancellation alone does not help if the client never cancels the request.
You can introduce an application-level timeout by combining the request cancellation token with a separate timeout token.
[HttpGet("reports")]
public async Task<IActionResult> GetReport(
CancellationToken requestCancellation)
{
using var timeoutSource =
new CancellationTokenSource(
TimeSpan.FromSeconds(20));
using var linkedSource =
CancellationTokenSource.CreateLinkedTokenSource(
requestCancellation,
timeoutSource.Token);
try
{
var report = await _reportService.GenerateAsync(
linkedSource.Token);
return Ok(report);
}
catch (OperationCanceledException)
when (requestCancellation.IsCancellationRequested)
{
_logger.LogInformation(
"Report generation was cancelled because the request ended.");
throw;
}
catch (OperationCanceledException)
when (timeoutSource.IsCancellationRequested)
{
_logger.LogWarning(
"Report generation exceeded the application timeout.");
return StatusCode(
StatusCodes.Status504GatewayTimeout,
"Report generation timed out.");
}
}
This example handles two different cancellation conditions:
- The client or server aborts the HTTP request.
- The application-defined timeout expires.
The linked token is cancelled when either source is cancelled.
This is useful when an API has a defined response-time budget.
Remember that a database command timeout can still be useful as an additional safeguard. Application-level cancellation and database command timeout are not interchangeable.
Use Cancellation with Raw ADO.NET Commands
Not every application uses EF Core. Some applications use Dapper or direct ADO.NET commands for database operations.
The same cancellation principle applies.
For example, consider a direct SQL Server command using Microsoft.Data.SqlClient:
public async Task<List<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
var customers = new List<Customer>();
await using var connection =
new SqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT Id, Name FROM Customers",
connection);
await using var reader = await command.ExecuteReaderAsync(
cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
customers.Add(new Customer
{
Id = reader.GetInt32(0),
Name = reader.GetString(1)
});
}
return customers;
}
The token is passed to:
- OpenAsync
- ExecuteReaderAsync
- ReadAsync
This ensures that cancellation can be requested during connection opening, query execution, and result reading.
For Dapper, pass the token through CommandDefinition:
public async Task<IEnumerable<Customer>> GetCustomersAsync(
CancellationToken cancellationToken)
{
await using var connection =
new SqlConnection(_connectionString);
var command = new CommandDefinition(
"SELECT Id, Name FROM Customers",
cancellationToken: cancellationToken);
return await connection.QueryAsync<Customer>(command);
}
The important detail is that the cancellation token must reach the actual database command. Simply accepting a CancellationToken in the repository method does not provide cancellation if the underlying database call ignores it.
Understand Cancellation During SaveChangesAsync
Cancellation becomes more important when the application modifies database records.
Consider this example:
await _context.Orders
.Where(o => o.Id == orderId)
.ExecuteUpdateAsync(
setters => setters.SetProperty(
o => o.Status,
"Completed"),
cancellationToken);
What happens if the client disconnects while the update is executing?
EF Core passes the cancellation token to the database provider. The provider may attempt to cancel the command.
However, you should not assume that the database operation definitely did not happen.
The command may have completed just before cancellation was observed. The server may have committed the transaction even though the application did not receive confirmation.
This is an important distinction:
<text weight=”semibold”>Cancellation does not guarantee that a write operation was rolled back.</text>
For example, the following sequence is possible:
- The API sends an update command.
- The database executes the update.
- The database commits the transaction.
- The client disconnects before receiving the response.
- The application observes cancellation or a connection-related failure.
The user may believe the operation failed, even though the database successfully updated the record.
This is why important write operations should be designed to handle uncertain outcomes.
For payments, order creation, inventory updates, and other critical business operations, consider:
- Idempotency keys.
- Unique business identifiers.
- Transaction boundaries.
- Durable operation status.
- Safe retry behavior.
- Reconciliation processes.
Do not automatically retry a write operation just because the HTTP request was cancelled.
First determine whether the operation might already have succeeded.
Decide Which Operations Should Follow Request Cancellation
Not every operation should be cancelled when the client disconnects.
Consider an API that creates an order and then sends a confirmation email.
Client Request
|
v
Create Order
|
v
Save to Database
|
v
Send Confirmation Email
|
v
Return Response
If the client disconnects after the order has been saved, should the application cancel the confirmation email?
The answer depends on the business requirement.
If sending the email is an independent business obligation, tying it to the HTTP request lifetime is risky.
The same applies to:
- Payment settlement.
- Order fulfillment.
- Audit logging.
- Background report generation.
- Message publication.
- Important notifications.
- Long-running data synchronization.
A better design separates request-bound work from durable business work.
For example:
HTTP Request
|
v
Validate Order
|
v
Save Order and Outbox Message
|
v
Return Response
Background Worker
|
v
Read Outbox Message
|
v
Send Confirmation Email
The HTTP request can be cancelled after the order is saved, but the background worker continues processing the durable message independently.
This is one reason the transactional outbox pattern is useful in systems that must reliably publish messages after database changes.
Use RequestAborted for work that exists only to produce the current HTTP response. Use durable background processing for business operations that must continue even when the client disconnects.
Test Request Cancellation Properly
A cancellation implementation should be tested rather than assumed to work.
You can test a long-running service using a CancellationTokenSource:
[Fact]
public async Task Operation_Stops_When_Cancellation_Is_Requested()
{
using var source = new CancellationTokenSource();
var operation = _service.RunAsync(source.Token);
source.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => operation);
}
This test verifies that the service responds to cancellation.
However, it does not prove that a real database provider cancels an executing query.
For database-level testing, use an integration test with the actual provider and a query that takes long enough to observe cancellation.
For example, SQL Server supports WAITFOR DELAY:
WAITFOR DELAY '00:00:30';
SELECT 1;
You can execute this command through the actual database provider, cancel the token while it is running, and observe whether the provider interrupts the command.
Be careful when using artificial delays. Run these tests against a dedicated test database, not a production database.
Also test the behavior when:
- The client disconnects during query execution.
- The client disconnects while results are being read.
- The application-level timeout expires.
- The database command timeout expires.
- The database operation completes just before cancellation.
- The operation is a write rather than a read.
The last scenario is particularly important because cancellation and transaction completion can produce uncertain outcomes.
Common Mistakes to Avoid
| Mistake | Why it causes problems | Better approach |
|---|---|---|
| Ignoring RequestAborted | Database operations may continue unnecessarily | Pass CancellationToken through the application |
| Passing a token only to the controller | The repository or database operation may ignore cancellation | Propagate it to the actual I/O operation |
| Using synchronous database methods | The operation cannot participate in asynchronous cancellation in the same way | Use supported asynchronous methods |
| Catching all exceptions as server errors | Normal request cancellations appear as application failures | Handle OperationCanceledException separately |
| Assuming cancellation always stops SQL immediately | Provider and database behavior can vary | Test with the actual database provider |
| Assuming a cancelled write did not commit | The database may have completed the operation before cancellation was observed | Use idempotency and operation-status checks |
| Cancelling durable business work | Important operations may be abandoned when a client disconnects | Move independent work to a background worker |
| Ignoring command timeouts | A connected client can still wait too long | Configure appropriate database command timeouts |
| Running parallel queries on one DbContext | EF Core does not support concurrent operations on the same context | Await each operation or use separate contexts |
Best Practices for Production Applications
For reliable request cancellation in ASP.NET Core, follow these practices:
- Accept CancellationToken in controller actions and Minimal API handlers.
- Propagate the same token through application services and repositories.
- Pass cancellation tokens to EF Core asynchronous methods.
- Use cancellation-aware ADO.NET and Dapper commands.
- Handle OperationCanceledException separately from unexpected failures.
- Distinguish client cancellation from application-level timeouts.
- Configure database command timeouts independently.
- Test cancellation using the actual database provider.
- Do not assume cancelled write operations were rolled back.
- Use idempotency for critical operations that clients may retry.
- Move durable business operations into background processing.
- Monitor long-running queries and database connection usage.
Cancellation should be part of the application’s design rather than something added only when performance problems appear.
Summary
When a client disconnects, ASP.NET Core can notify the application through HttpContext.RequestAborted. However, database operations do not automatically stop unless the application propagates that cancellation token to the underlying database calls.
Passing CancellationToken through controllers, services, repositories, and EF Core asynchronous methods allows the application to request cancellation when the HTTP request ends.
For production applications, remember that cancellation is cooperative and provider-dependent. It does not guarantee immediate query termination, and it does not guarantee that a write operation was rolled back.
Use request cancellation for work that exists only to serve the current HTTP request. Keep durable business operations independent through background workers and reliable messaging patterns.
The result is an application that uses database resources more efficiently, handles disconnected clients gracefully, and avoids performing unnecessary work under heavy traffic.
ASP.NET Core 11.0 Hosting Recommendation
HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.
