Fixing It

Three honest fixes, in order of preference.

Let the database decide. A unique constraint or a CHECK means the second writer simply fails, and you handle the error. This is the most reliable option because it does not depend on anyone remembering.

Lock the row you are deciding about, with SELECT ... FOR UPDATE inside the transaction. The second transaction waits rather than reading stale data.

Use a higher isolation level and be ready to retry on a serialization failure.

What is not a fix is checking more carefully in application code. The gap between the check and the write is where the problem lives, and no amount of care removes it.

Keep transactions short. A transaction held open holds locks, and everything else waits behind it. Never do slow work inside one: no network calls, no waiting on a person, no sending email. Read what you need, write, commit, and do the slow part afterwards.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back