C# Interview Question #194
How would you prevent duplicate records when two requests arrive at the same time?
Senior .NET Practical Scenarios Senior Advanced
Quick Interview Answer
Application-level existence checks alone are insufficient because two concurrent requests can both pass the check before either inserts a row.
Detailed Explanation
Application-level existence checks alone are insufficient because two concurrent requests can both pass the check before either inserts a row.
The database should enforce the uniqueness invariant using a UNIQUE constraint or unique index. The application can perform an early check for user experience, but it must still handle a database uniqueness violation caused by a race.
For workflows requiring stronger coordination, transactions, concurrency tokens, idempotency keys, or distributed coordination may also be appropriate depending on the business requirement.
Code Example
// EF Core model configuration
modelBuilder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();