Checking whether a key exists and then inserting it is two statements, and two requests can both pass the check before either inserts.
// racy, and passes every test written with one worker
if (! IdempotentRequest::where('key', $key)->exists()) {
IdempotentRequest::create(['key' => $key]);
}
// the database decides, which is the only thing that can
try {
IdempotentRequest::create(['key' => $key]);
} catch (QueryException $e) {
if (! $this->isDuplicateKey($e)) { throw $e; }
}
The unique index is what makes any of this work, and without it the catch never fires and the duplicates arrive regardless. Distinguishing a duplicate-key error from every other query error is the fiddly part and deserves a named method rather than a string match inline — the error code is stable and the message is not. This is the same shape as every check-then-act race, and the answer is always to let a constraint decide.