Database connection failures are a common challenge in applications that depend on relational databases. Even a well-designed ASP.NET Core application can experience temporary database unavailability, network interruptions, connection timeouts, or server-side resource limitations.
These problems become more complicated when they occur during an Entity Framework Core transaction.
Consider an order processing application that performs several database operations:
- Creates an order.
- Saves order items.
- Updates product inventory.
- Creates a payment record.
- Records order history.
Suppose the database connection drops after the first two operations have executed but before the transaction commits. What happens to the data? Should the application retry the transaction? Can it safely execute the same operations again?
These questions are important because retrying a database operation without understanding its transaction state can create duplicate records or inconsistent business data.
Entity Framework Core provides connection resiliency through execution strategies. These strategies can automatically retry operations when a database provider identifies a failure as transient.
However, applications using explicit transactions need additional handling. Developers must understand how to retry the complete transaction, manage DbContext instances, and handle situations where the connection fails during commit.
Understand Different Types of Database Connection Failures
Not every database error should be handled with an automatic retry.
The first step is to understand the type of failure.
Transient connection failures
Transient failures are temporary problems that may disappear after a short period.
Examples include:
- Temporary database unavailability.
- Network interruptions.
- Database service failover.
- Temporary resource throttling.
- Connection timeouts caused by temporary infrastructure problems.
These failures may be suitable for retrying, depending on the database provider and its execution strategy.
Permanent database failures
Some failures require a code or configuration change rather than another attempt.
Examples include:
- Invalid connection strings.
- Incorrect database credentials.
- Missing database permissions.
- Invalid SQL statements.
- Missing database tables.
- Incompatible database schema.
- Incorrect entity mappings.
Retrying these operations repeatedly will not solve the underlying problem.
Transaction commit failures
A particularly difficult situation occurs when the database connection drops while a transaction is being committed.
The application may receive an exception without knowing whether the database successfully committed the transaction.
For example:
- The application starts a transaction.
- It inserts an order.
- It updates inventory.
- It sends the commit request.
- The database commits successfully.
- The network connection drops before the success response reaches the application.
From the application's perspective, the operation failed.
From the database's perspective, it may have succeeded.
This uncertainty makes transaction retry handling especially important.
Enable Connection Resiliency in EF Core
EF Core provides execution strategies that automatically retry database operations when a provider identifies a failure as transient.
For SQL Server, the provider includes a retrying execution strategy.
Configure it when registering the DbContext:
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection"),
sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(10),
errorNumbersToAdd: null);
});
});
The configuration includes three important settings:
| Setting | Purpose |
|---|
| maxRetryCount | Maximum number of retry attempts |
| maxRetryDelay | Maximum delay between retry attempts |
| errorNumbersToAdd | Additional SQL Server error numbers considered transient |
The SQL Server execution strategy already recognizes several transient database errors. Custom error numbers should only be added when there is a clear reason to treat them as retryable.
The retry strategy uses delays between attempts to avoid immediately sending repeated requests to an unavailable database.
For example, if the database temporarily becomes unavailable during a failover, the application may recover without requiring the user to repeat the operation manually.
However, connection resiliency is not a solution for every database failure. Authentication errors, invalid SQL, and other permanent problems should still be surfaced and investigated.
Understand Why Explicit Transactions Need Special Handling
When retrying execution strategies are enabled, EF Core treats individual database operations as retryable units.
For example:
await _context.Orders
.Where(o => o.Id == orderId)
.FirstOrDefaultAsync();
EF Core can retry this query when the provider identifies a transient failure.
The same applies to a call to SaveChangesAsync().
However, consider an application that starts its own transaction:
await using var transaction =
await _context.Database.BeginTransactionAsync();
_context.Orders.Add(order);
await _context.SaveChangesAsync();
await transaction.CommitAsync();
When a retrying execution strategy is configured, this pattern can produce an InvalidOperationException.
The reason is that EF Core cannot independently retry individual operations inside a user-created transaction. The complete transaction must be treated as one retryable unit.
The solution is to obtain the execution strategy through CreateExecutionStrategy() and execute the entire transaction inside its delegate.
Retry the Complete Transaction With an Execution Strategy
Consider an order operation that needs to create an order and its history record.
Both database changes must succeed together.
A simplified implementation looks like this:
public async Task CreateOrderAsync(
Order order,
CancellationToken cancellationToken)
{
var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
await using var transaction =
await _context.Database.BeginTransactionAsync(
cancellationToken);
_context.Orders.Add(order);
await _context.SaveChangesAsync(cancellationToken);
_context.OrderHistory.Add(new OrderHistory
{
OrderId = order.Id,
Status = "Created"
});
await _context.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
});
}
The important change is that the complete transaction is now inside the execution strategy.
If a retryable failure occurs, the strategy can execute the entire delegate again rather than retrying only one database command.
However, this example reuses the same DbContext and entity instance across retry attempts. That can create problems when an earlier attempt has partially changed the context's tracked state.
For production applications, creating a fresh DbContext for each attempt is a safer approach.
Use a New DbContext for Each Retry Attempt
A DbContext tracks entities and their states.
Suppose the first transaction attempt inserts an order but fails before completion. The context may still contain tracked entities marked as Added or Modified.
If the execution strategy runs the delegate again using the same context, the application may encounter unexpected tracking behavior.
A fresh DbContext gives each attempt a clean unit of work.
Register a DbContext factory:
builder.Services.AddDbContextFactory<AppDbContext>(
options =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString(
"DefaultConnection"),
sqlOptions =>
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(10),
errorNumbersToAdd: null));
});
The application service can then use the factory:
public class OrderService
{
private readonly IDbContextFactory<AppDbContext> _contextFactory;
public OrderService(
IDbContextFactory<AppDbContext> contextFactory)
{
_contextFactory = contextFactory;
}
public async Task CreateOrderAsync(
Order order,
CancellationToken cancellationToken)
{
await using var strategyContext =
await _contextFactory.CreateDbContextAsync(
cancellationToken);
var strategy =
strategyContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
await using var db =
await _contextFactory.CreateDbContextAsync(
cancellationToken);
await using var transaction =
await db.Database.BeginTransactionAsync(
cancellationToken);
db.Orders.Add(order);
await db.SaveChangesAsync(cancellationToken);
db.OrderHistory.Add(new OrderHistory
{
OrderId = order.Id,
Status = "Created"
});
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
});
}
}
Each retry creates a new context and transaction.
The execution strategy controls the retry process, while the new context prevents entity tracking from one attempt from affecting another.
This example assumes that the order identifier is stable across attempts. The next section explains why that matters.
Handle the Unknown Transaction Commit Outcome
Retrying the complete transaction solves many transient connection failures, but it does not automatically solve the unknown commit outcome.
Consider the following situation:
Application
|
|-- Begin Transaction
|
|-- Insert Order
|
|-- Update Inventory
|
|-- Commit Transaction
|
|-- Database commits successfully
|
|-- Connection drops
|
|-- Application receives exception
The execution strategy may retry the transaction because it cannot confirm whether the original commit succeeded.
If the original transaction actually committed, executing the same insert again may create duplicate data.
This is known as the transaction commit ambiguity problem.
One practical solution is to use client-generated identifiers and idempotency keys.
For example, create an order identifier before starting the transaction:
var orderId = Guid.NewGuid();
Use that same identifier for every retry attempt.
db.Orders.Add(new Order
{
Id = orderId,
CustomerId = customerId,
TotalAmount = totalAmount
});
Add a unique constraint to the identifier in the database.
If the first transaction committed successfully, a repeated attempt cannot silently create another order with the same identifier.
However, a unique constraint alone does not provide complete recovery. The application must still determine whether the original operation succeeded.
A stronger approach is to maintain an operation record using a stable idempotency key.
For example:
public class ProcessedOperation
{
public Guid OperationId { get; set; }
public string OperationType { get; set; } = string.Empty;
public DateTime CompletedAt { get; set; }
}
The operation identifier should have a unique database constraint.
Inside the transaction, save the order and its processed-operation record together:
db.Orders.Add(order);
db.ProcessedOperations.Add(new ProcessedOperation
{
OperationId = operationId,
OperationType = "CreateOrder",
CompletedAt = DateTime.UtcNow
});
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
If the connection fails during commit, the application can query the processed-operation record using a fresh DbContext.
- If the record exists, the transaction committed successfully.
- If the record does not exist, the transaction did not persist that operation.
- If the database remains unavailable, the application should report an uncertain outcome and allow reconciliation later.
The unique constraint is important because concurrent requests using the same operation identifier must not create duplicate business operations.
For critical systems, use EF Core's transaction verification capabilities, such as ExecuteInTransactionAsync with a verifySucceeded callback, when they fit the operation. This allows the application to check whether the transaction succeeded after a commit-related transient failure.
Keep Retryable Operations Idempotent
Idempotency means that repeating the same operation does not create additional unintended effects.
Consider an inventory update:
inventory.Quantity -= requestedQuantity;
If this operation executes twice because of an unsafe retry, the inventory will be reduced twice.
A safer approach is to associate the business operation with a unique identifier and record its completion in the same transaction.
Also use conditional updates to protect inventory:
var updatedRows = await db.Inventory
.Where(i =>
i.ProductId == productId &&
i.Quantity >= requestedQuantity)
.ExecuteUpdateAsync(
setters => setters.SetProperty(
i => i.Quantity,
i => i.Quantity - requestedQuantity),
cancellationToken);
if (updatedRows == 0)
{
throw new InvalidOperationException(
"Insufficient inventory or product not found.");
}
The conditional update prevents inventory from becoming negative because of concurrent orders.
For external operations such as payments or email notifications, database idempotency is not enough. Use the external provider's idempotency mechanism where available, or implement a reliable message-processing workflow.
Avoid sending external requests directly inside a transaction retry delegate. If the delegate executes again, the external operation may be repeated.
Monitor Connection Failures and Retry Behavior
Connection resiliency should be observable in production.
Monitor the following information:
- Number of transient database failures.
- Number of retry attempts.
- Total retry duration.
- Transaction commit failures.
- Connection timeout errors.
- Database availability.
- Connection pool utilization.
- Operations that eventually fail after retries.
EF Core logging can help identify database command failures and transaction activity.
For example:
builder.Logging.AddFilter(
"Microsoft.EntityFrameworkCore.Database.Command",
LogLevel.Information);
builder.Logging.AddFilter(
"Microsoft.EntityFrameworkCore.Database.Transaction",
LogLevel.Information);
Use structured logging and monitoring to correlate these events with application requests.
Do not log passwords, connection strings, or sensitive database parameters.
Also remember that enabling retry strategies can cause EF Core to buffer query result sets internally. Applications that retrieve very large result sets should evaluate memory usage when connection resiliency is enabled.
Common Mistakes to Avoid
| Mistake | Better approach |
|---|
| Retrying every database exception | Retry only provider-recognized transient failures |
| Retrying individual commands inside an explicit transaction | Execute the complete transaction through the execution strategy |
| Reusing a failed DbContext for every retry | Create a fresh context for each attempt |
| Assuming a failed commit means the database rolled back | Verify the transaction outcome |
| Using auto-generated identifiers without considering retries | Use stable client-generated identifiers where appropriate |
| Repeating inventory or payment operations blindly | Implement idempotency |
| Increasing retry counts without investigation | Review database availability and infrastructure problems |
| Sending notifications inside a retry delegate | Use an outbox or separate reliable processing |
Summary
Database connection failures can occur even in well-designed applications, particularly when applications depend on cloud-hosted databases or distributed infrastructure.
EF Core provides connection resiliency through execution strategies, allowing supported transient failures to be retried automatically.
However, explicit transactions require special handling. The entire transaction must be executed through the configured execution strategy, and production implementations should consider using a fresh DbContext for each attempt.
The most difficult situation is a connection failure during commit because the application may not know whether the database successfully saved the transaction.
Stable identifiers, unique constraints, idempotency records, and transaction verification help prevent duplicate operations and provide a reliable recovery path.
The key is to design retries as part of the transaction workflow rather than treating them as a simple mechanism for executing failed SQL statements again.
With appropriate retry policies, short transactions, idempotent operations, and production monitoring, applications can handle temporary database failures without compromising data consistency.
Join the conversation! Your thoughts help the community grow.