Checking whether a key exists and then inserting it is two statements and a race, and the race is precisely the concurrent-retry case the key exists to handle.
// passes every test written with one worker
if (! IdempotentRequest::where('key', $key)->exists()) {
IdempotentRequest::create(['key' => $key]);
}
// the database decides
try {
$record = IdempotentRequest::create(['key' => $key]);
} catch (QueryException $e) {
if (! $this->isDuplicateKey($e)) {
throw $e;
}
return $this->handleReplay($key);
}
Insert-and-catch is the only correct shape, and it applies far beyond idempotency keys — any check-then-act against a uniqueness constraint has the same flaw. Distinguishing a duplicate-key error from every other query error deserves a named method: the driver error code is stable and the message is not, and matching on the message breaks on a MySQL upgrade. The catch block must not swallow other query errors, which is the mistake in nearly every version of this found in the wild.