In this lesson, you will learn how to make your application more robust by automatically retrying database operations that fail due to temporary network glitches or transient server issues.
Understanding Transient Failures
In distributed systems, connections between your application and your database can occasionally drop or time out for just a split second. These are called transient failures. Without a resiliency policy, your application would crash or return an error to the user the moment a simple "hiccup" occurs.
EF Core provides an Execution Strategy that acts as a safety net. Instead of giving up immediately, the strategy catches the failure, waits a calculated amount of time, and then automatically re-runs your query or SaveChanges() operation.
Implementing an Execution Strategy
You configure these policies when setting up your DbContext in your Startup.cs or Program.cs. By specifying an execution strategy, you tell EF Core how to handle retries during the configuration phase.
For example, using the SQL Server provider, you can enable the built-in strategy like this:
optionsBuilder
.UseSqlServer(connectionString, sqlServerOptions =>
{
// This enables the default execution strategy
sqlServerOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
});
Why This Matters
When you use EnableRetryOnFailure, EF Core handles the state management of your operation. It is important to note that if you are using explicit transactions (like those we discussed in Lesson 1103.3 regarding Transaction Scope), you must be careful; the strategy needs to know how to retry the entire transaction block, not just the individual command, to ensure data consistency.
By implementing this, you move your application from "brittle" to "resilient." You aren't fixing the underlying network instability, but you are creating a graceful experience where the end-user never notices the brief connectivity interruption.
Key Takeaway: Use EnableRetryOnFailure to automatically handle transient database connectivity issues, ensuring your application recovers from temporary errors without manual intervention.