DevPath
Foundation lesson · 12 min

Prevent double booking under concurrency

Enforce a reservation invariant when requests race.

See the race

Two requests can both read 'available' before either writes a booking. A check followed by insert is not safe merely because each line is correct. Define the invariant at the database level where possible, such as a unique resource-and-slot key, then handle the resulting conflict as a normal outcome.

Choose a concurrency control

For a single slot, a unique constraint is simple and robust. For capacity or overlapping ranges, use a transaction with a lock or a carefully designed conditional update. Keep the locked section short and use a consistent lock order. Retry deadlocks only when the whole operation is safe to repeat.

DB::transaction(function () use ($resourceId, $slot) {
    $resource = Resource::whereKey($resourceId)->lockForUpdate()->firstOrFail();
    // Re-check capacity while holding the lock, then insert.
});

Prove the invariant

Run two competing requests against the same slot and assert that exactly one reservation exists. SQLite in-memory tests may not reproduce production locking behavior, so also test the database constraint and, when possible, run a concurrency test on the production database engine.

Check your understanding

Why is checking availability before a transaction insufficient?

Show explanation

Another request can reserve the slot before the first request writes. Re-check under appropriate locking or enforce a constraint.

You can read for free. Create an account to save your progress.

← Previous lesson: Design a job that can safely retry

Try it at foundation level

Draw two requests reserving the last seat at the same time. Choose a database constraint or lock that makes only one commit.

Check your work

The invariant is enforced by the database, the losing request gets a clear conflict response, and a retry does not double-book.

Self-guided practice. This does not record assessed mastery.

Put this lesson into practice

A related activity in this module at mid level.

Try: Deduplicate a payment webhook

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.