Field Manual PHP / Laravel reference
← Financial-system patterns

Pessimistic locking

Pessimistic locking holds database locks while checking and changing state.

What it is

Pessimistic locking holds database locks while checking and changing state.

When to use it

Use on engines supporting row locks for contested invariants.

Syntax

// PostgreSQL/MySQL transactional engine, not SQLite row locking:
Account::whereKey($id)->lockForUpdate()->firstOrFail();

Example

DB::transaction(function () use ($sourceId, $destinationId) {
    $ids = [$sourceId, $destinationId];
    sort($ids);
    $accounts = Account::whereIn("id", $ids)->orderBy("id")
        ->lockForUpdate()->get();
    // Check count, ownership, currency, balance, then update.
});
// SQLite has no SELECT FOR UPDATE row locks; consider conditional writes
// and short transactions / BEGIN IMMEDIATE with busy handling.

Common mistakes

Lock in a consistent order; keep locks short; deadlocks still occur and require safe bounded retries.

Related topics

Browse Financial-system patterns