ASP.NET Core Interview Question #233
How would you prevent race conditions when two users update the same record?
Senior ASP.NET Core Real-World Scenarios Senior Advanced
Quick Interview Answer
Use a concurrency strategy appropriate to the business rule. Optimistic concurrency is common: store a concurrency token and include it in the update condition. If another request changed the row first, the second update detects the conflict instead of silently overwriting data.
Detailed Explanation
Use a concurrency strategy appropriate to the business rule. Optimistic concurrency is common: store a concurrency token and include it in the update condition. If another request changed the row first, the second update detects the conflict instead of silently overwriting data.
The application can then reject the update, reload and ask the user to reconcile, or apply a documented merge rule. For invariants that must hold under concurrency, database constraints and appropriate transaction isolation may also be necessary.
Do not rely on βcheck then updateβ in separate unprotected operations when concurrent requests can invalidate the check.
Code Example
public class Product
{
public int Id { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; } = Array.Empty<byte>();
}
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException)
{
// Resolve or report the conflict.
}