Interview frequency: …
Short answer
Transactions make operations atomic and roll them back on failure; DB::transaction accepts an argument that sets how many times to retry automatically after a Deadlock.
Explanation
Transactions prevent partial failures in financial operations and reservations. Concurrent transactions can lock rows in conflicting orders, causing a database Deadlock. DB::transaction(callback, attempts: 5) automatically retries transient Deadlocks without showing the error to the client.
Code example
DB::transaction(function () use ($from, $to, $amount) {
$from->decrement('balance', $amount);
$to->increment('balance', $amount);
}, 5); // 5 Retries when DeadlockCommon mistakes
- Sending emails or making external HTTP requests inside DB::transaction; these actions repeat on each retry and cannot be undone by a Rollback.