Skip to content

EF Core Connection Resiliency — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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 EnableRetryOnFailure for SQL Server, SQL Azure, and PostgreSQL providers.
  • Configure maxRetryCount based on your SLA (typically 3-5 retries).
  • Configure maxRetryDelay to control the maximum wait between retries.
  • Handle OperationCanceledException separately from transient failures.
  • Use CreateExecutionStrategy for 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

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

What is a transient error?

A transient error is a temporary condition that resolves on retry: network timeout, deadlock victim, connection pool exhaustion, database failover, or throttling. These are different from permanent errors like invalid SQL syntax or missing tables.

Does retry affect idempotent operations only?

EnableRetryOnFailure retries the entire operation. If the operation is not idempotent (e.g., INSERT with auto-generated key), retry could produce duplicate records. For non-idempotent operations, check for duplicates or use application-level idempotency keys.

Can I use Polly with EF Core instead of EnableRetryOnFailure?

Yes. Polly provides more flexible retry policies (circuit breaker, timeout). Use Polly at the application level and EnableRetryOnFailure at the EF Core level for layered resiliency. Polly wraps the EF Core execution strategy.

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