InterviewBuddy
All interview questions

How do you prevent duplicate writes under concurrency?

Advanced

Answer

Enforce the invariant in the database using unique constraints and transactions, and handle conflicts deliberately. An application-level check followed by an insert is vulnerable to races.

Explanation

Two requests can both observe that a row is absent. A database constraint remains the final guard even if the UI prevents duplicate submissions.

Example

UNIQUE (user_id, question_id)