EF Core Connection Resiliency — Complete Guide
In this tutorial, you'll learn about EF Core Connection Resiliency. We cover key concepts, practical examples, and best practices.
Your application runs fine in development but throws random connection errors in production. The database briefly goes unavailable — a network blip, a failover, or a timeout. Without resiliency, your app shows 500 errors to users for temporary issues.
The Problem
public async Task<Order> GetOrderAsync(int id)
{
return await db.Orders.FirstAsync(o => o.Id == id);
// If database is temporarily unavailable, this throws SqlException
}
Output: SqlException: A network-related or instance-specific error occurred... — a transient failure causes a 500 error.
The Fix
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString, options =>
{
options.EnableRetryOnFailure(
maxRetryCount: 3,
maxRetryDelay: TimeSpan.FromSeconds(10),
errorNumbersToAdd: null);
});
}
Output: EF Core retries failed operations up to 3 times with exponential backoff. Transient failures are handled transparently.
For custom execution strategies:
public class CustomExecutionStrategy : ExecutionStrategy
{
protected override bool ShouldRetryOn(Exception exception)
{
return exception is SqlException sqlEx &&
sqlEx.Number is 1205 or -2; // Deadlock or timeout
}
}
Apply to specific queries:
var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
using var tx = await db.Database.BeginTransactionAsync();
// ... operations ...
await tx.CommitAsync();
});
Prevention
- Use
EnableRetryOnFailurefor SQL Server, SQL Azure, and PostgreSQL providers. - Configure
maxRetryCountbased on your SLA (typically 3-5 retries). - Configure
maxRetryDelayto control the maximum wait between retries. - Handle
OperationCanceledExceptionseparately from transient failures. - Use
CreateExecutionStrategyfor custom retry logic. - Test resiliency by simulating transient failures (e.g., using Polly or a custom middleware).
- Log retry attempts for monitoring and alerting.
Common Mistakes with core connection resiliency
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Connection resiliency is critical for DodaTech's cloud-deployed applications. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro