ASP.NET Core Interview Question #232
How would you handle transient database failures?
Senior ASP.NET Core Real-World Scenarios Senior Advanced
Quick Interview Answer
First determine whether the failure is actually transient. Temporary connectivity or failover conditions may justify a limited retry strategy, while constraint violations or invalid SQL will not improve by retrying.
Detailed Explanation
First determine whether the failure is actually transient. Temporary connectivity or failover conditions may justify a limited retry strategy, while constraint violations or invalid SQL will not improve by retrying.
EF Core database providers can support retrying execution strategies. Transactions require care because the complete unit of work may need to execute through the strategy. Operations should be designed so an uncertain outcome does not create duplicate business effects.
Log retry exhaustion and monitor the underlying database rather than treating retries as a substitute for fixing infrastructure problems.
Code Example
var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
await using var transaction =
await db.Database.BeginTransactionAsync(ct);
// Perform the complete retryable unit of work.
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
});