DevPath
Foundation lesson · 14 min

Make related writes atomic

Use a transaction for a business operation that must succeed or fail together.

Define the invariant

If an order is created and inventory is reduced, a failure between those writes leaves inconsistent state. Put both writes in one transaction, and throw on a failed invariant so the database rolls back. A transaction protects database writes, not external emails or payment calls.

Plan for retries

Two requests can race even inside transactions. Use a uniqueness constraint or row lock to protect the invariant at the database level. Make retried requests idempotent: the same request key should return the first result instead of applying the change twice.

DB::transaction(function () use ($order) {
    $stock = Stock::whereKey($order->stock_id)->lockForUpdate()->firstOrFail();
    if ($stock->quantity < $order->quantity) throw new OutOfStock();
    $stock->decrement('quantity', $order->quantity);
    $order->save();
});

Walk through a failed transfer

For a transfer, the balance decrease, balance increase, and transfer record form one invariant. Begin the database transaction, lock the relevant rows in a consistent order, verify available funds, write both changes, and commit. Throwing on insufficient funds rolls everything back. A test should force a failure after the first write and verify that both balances stay unchanged.

Know the boundary of atomicity

A database transaction cannot roll back an already-sent email or a completed HTTP payment. Persist an outbox event with the database changes, then let a worker deliver it after commit. The worker must tolerate retries. Also avoid long network calls while holding locks: they increase contention and the chance of timeout or deadlock.

Check your understanding

Does a transaction alone prevent two simultaneous requests from overselling the last item?

Show explanation

No. Lock the row or use a conditional update, and enforce relevant uniqueness rules in the database.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Find customers with no orders

Further reading

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