Enforcing Uniqueness Across Concurrent Inserts

Checking for an existing row before inserting one can be useful feedback. Durable uniqueness needs coordination at the storage boundary.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a simultaneous creation
  2. Choose a caller outcome
  3. Show why two absence checks can both succeed
  4. Make the rejected or concurrent result meaningful

Trace a simultaneous creation

Two transactions can each find no row for code A and then attempt an insert. A unique constraint can reject one conflicting result under the database's rules. See SQL uniqueness.

Choose a caller outcome

The losing attempt can return an existing record or a conflict according to the operation's meaning. Repeated request identities can distinguish repeat intent from genuinely competing inserts.[1]

Show why two absence checks can both succeed

Two requests ask to create the same code in one project. Each independently reads before either has inserted. Both can see absence. A database uniqueness constraint enforces the invariant at insertion or commit despite the initial agreement. See unique column combinations.

A checks code amber → absent
B checks code amber → absent
Both try inserting (project 3, amber)
One committed row under the uniqueness rule

Make the rejected or concurrent result meaningful

A repeated logical request may fetch the existing row, while an independent conflicting request may report a duplicate. Verify both outcomes with concurrency and confirm final row count.

References

  1. PostgreSQL Global Development Group, Concurrency Control ↩