Use insertOrIgnore() to Handle Race Conditions Gracefully

📖 2 minutes read

If you’re logging records to a database table that has a unique constraint — say, tracking processed job IDs or idempotency keys — you’ve probably hit this at some point:

SQLSTATE[23000]: Integrity constraint violation: 1062
Duplicate entry 'abc-123' for key 'jobs_uuid_unique'

This typically happens when two processes try to insert the same record at roughly the same time. Classic race condition. And it’s especially common in queue workers, where multiple workers might process the same failed job simultaneously.

The blunt solution is to wrap it in a try/catch:

try {
    DB::table('processed_jobs')->insert([
        'uuid' => $job->uuid(),
        'failed_at' => now(),
    ]);
} catch (\Illuminate\Database\QueryException $e) {
    // Ignore duplicate
}

But there’s a cleaner way. Laravel’s query builder has insertOrIgnore() — available since Laravel 5.8:

DB::table('processed_jobs')->insertOrIgnore([
    'uuid' => $job->uuid(),
    'failed_at' => now(),
    'payload' => $job->payload(),
]);

Under the hood, this generates INSERT IGNORE INTO ... on MySQL, which silently skips the insert if it would violate a unique constraint. No exception thrown, no try/catch needed.

A few things to keep in mind:

  • insertOrIgnore() will suppress all duplicate key errors, not just the one you’re expecting — so make sure your unique constraints are intentional
  • On MySQL, it also bypasses strict mode checks, which means other data integrity issues might be silently swallowed
  • If you need to update the existing record on conflict, use upsert() instead

Here’s the decision framework I use:

  • “Skip if exists”insertOrIgnore()
  • “Update if exists”upsert()
  • “Fail if exists” → Regular insert() (and let the exception surface)

If you’re writing any kind of idempotent operation — event processing, job tracking, audit logging — insertOrIgnore() is the simplest way to handle the race condition without cluttering your code with try/catch blocks.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *