Why lockForUpdate() blocks foreign key inserts, how lockForNoKeyUpdate() avoids it, and how to get an alert when a transaction runs too long.
Two queue workers process payments for the same invoice at the same moment. Each one does what the code review approved: insert a payment row, then lock the invoice and reduce its balance. One of them dies with SQLSTATE[40P01]: Deadlock detected. Neither transaction touches a second invoice, so there’s no lock-ordering mistake to point at. The code takes one lock on one row, and it still deadlocks, but only when two payments for the same invoice land close together. That’s why it survives staging and shows up in production on the busiest day.
There’s a second, quieter version of the same problem. A long job locks a team row with lockForUpdate() while it recalculates something. For the next ten seconds, every request that creates a project for that team hangs, even though those requests never touch the team row’s columns. They just insert a row that references it.
Both symptoms come from one fact about PostgreSQL that lockForUpdate() never mentioned: a foreign key check takes its own lock on the parent row, and FOR UPDATE conflicts with it. Laravel 13.44 adds lockForNoKeyUpdate() (PR #62544 by Ali Morgan) to ask PostgreSQL for the weaker lock you usually meant. The same release adds DB::whenTransactionRunsLongerThan() from Jack Bayliss, a hook for alerting on slow transactions, and Laravel News reports that it also adds PHP 8.6 support.
This post explains the lock mechanics, shows the deadlock in a reproduction you can run in two terminal windows, rewrites the Laravel code, and covers where the fix stops working and what to monitor.
What I could and couldn’t verify. The lock behavior comes from PostgreSQL’s own 9.3 release notes, the commit that introduced these locks, and writing by PostgreSQL committers. The Laravel details come from the Laravel News 13.44 write-up and the pull request listing. I haven’t run the Laravel code below. I couldn’t confirm a 12.x backport of lockForNoKeyUpdate(), since the pull request is labeled 13.x. And I couldn’t confirm whether the slow-transaction callback can fire while a transaction is still open or only when it ends, so I’ve written the monitoring advice to work either way.
The Four Row Locks PostgreSQL Offers
lockForUpdate() compiles to SELECT ... FOR UPDATE, and most Laravel developers think of that as “the” row lock. PostgreSQL actually has four, and the strongest one is rarely what you need.
| Lock | Taken by | Conflicts with |
|---|---|---|
FOR KEY SHARE | Foreign key checks on the referenced row | FOR UPDATE only |
FOR SHARE | sharedLock(), SELECT ... FOR SHARE | FOR NO KEY UPDATE, FOR UPDATE |
FOR NO KEY UPDATE | An UPDATE that doesn’t change key columns; lockForNoKeyUpdate() | FOR SHARE, FOR NO KEY UPDATE, FOR UPDATE |
FOR UPDATE | A DELETE; an UPDATE that changes key columns; lockForUpdate() | All four |
The two weakest locks were added deliberately in PostgreSQL 9.3. The commit message from Álvaro Herrera, who led the work, explains the motivation in one line:
“which is the whole point of this patch” — Álvaro Herrera, in the PostgreSQL commit “Improve concurrency of foreign key locking,” January 2013, about foreign key triggers using
FOR KEY SHAREinstead ofFOR SHARE
PostgreSQL committer Michael Paquier summarized the same feature when it shipped, in terms that match what Laravel users are now hitting:
“to reduce lock contention for foreign key triggers” — Michael Paquier, PostgreSQL 9.3 feature highlight, on the purpose of
FOR KEY SHAREandFOR NO KEY UPDATE
The release notes describe the intended outcome: an UPDATE that doesn’t change a column referenced by a foreign key takes the new NO KEY UPDATE lock on the row, while foreign key checks take KEY SHARE, and those two don’t conflict. So there’s no blocking unless a foreign-key column is changed.
Read the table again with that in mind. FOR KEY SHARE conflicts with exactly one mode: FOR UPDATE. And FOR UPDATE is the one Laravel has been giving you.
The Lock You Never Asked For
When you insert a child row, PostgreSQL has to confirm the parent row it references exists and won’t disappear. It does that by taking FOR KEY SHARE on the parent row for the duration of your transaction. You never wrote that lock, and Eloquent never mentions it, but it’s there:
Payment::create(['invoice_id' => $invoiceId, 'cents' => 1500]);
// PostgreSQL silently takes FOR KEY SHARE on invoices.id = $invoiceId
// and holds it until this transaction ends
FOR KEY SHARE is deliberately weak, and many transactions can hold it on the same row at once. That’s why it doesn’t hurt until something asks for FOR UPDATE on that same row. Laravel News describes the result in the 13.44 write-up: while a parent row is locked with lockForUpdate(), inserting a child row that references it waits, and two transactions can deadlock.
Here’s the deadlock, step by step, using the invoice example. Run it in two psql sessions against any test database with an invoices table and a payments table that has a foreign key to it:
-- Session A
BEGIN;
INSERT INTO payments (invoice_id, cents) VALUES (1, 1500); -- holds FOR KEY SHARE on invoice 1
-- Session B
BEGIN;
INSERT INTO payments (invoice_id, cents) VALUES (1, 2500); -- also FOR KEY SHARE: compatible, no wait
SELECT * FROM invoices WHERE id = 1 FOR UPDATE; -- conflicts with A's KEY SHARE: waits
-- Session A
SELECT * FROM invoices WHERE id = 1 FOR UPDATE; -- conflicts with B's KEY SHARE: deadlock
Session A waits for B, and B is already waiting for A. PostgreSQL notices the cycle after its deadlock timeout, aborts one of the two transactions with error 40P01, and lets the other continue. Now change both FOR UPDATE lines to FOR NO KEY UPDATE and run it again. Session B’s lock succeeds immediately because it doesn’t conflict with A’s KEY SHARE. Then A’s lock waits for B, but B isn’t waiting for anything, so B finishes, commits, and A proceeds. There’s no cycle, so there’s no deadlock.
One developer who hit this in production described what they learned about the stronger lock in terms worth keeping in mind:
“asking for more than a plain UPDATE of the same row would” — a DEV Community author writing as edyiaeonian, in “A PostgreSQL deadlock hiding in a foreign key check”, about their
FOR UPDATElock
That’s the whole bug in a sentence. If you’re just going to UPDATE the row without changing a key column, PostgreSQL itself only takes FOR NO KEY UPDATE. An explicit FOR UPDATE before it asks for strictly more than the update needs.
The Same Bug in Laravel Code
// ❌ Before: insert first, then lock with the strongest mode
DB::transaction(function () use ($invoiceId, $cents) {
Payment::create(['invoice_id' => $invoiceId, 'cents' => $cents]);
// ↑ the foreign key check takes FOR KEY SHARE on the invoice
$invoice = Invoice::whereKey($invoiceId)->lockForUpdate()->firstOrFail();
// ↑ FOR UPDATE conflicts with a concurrent transaction's FOR KEY SHARE
$invoice->decrement('balance_cents', $cents);
});
// ✅ After: ask for the lock the work actually needs
DB::transaction(function () use ($invoiceId, $cents) {
Payment::create(['invoice_id' => $invoiceId, 'cents' => $cents]);
$invoice = Invoice::whereKey($invoiceId)->lockForNoKeyUpdate()->firstOrFail();
$invoice->decrement('balance_cents', $cents);
}, attempts: 3);
lockForNoKeyUpdate() still stops two transactions from updating the same invoice at once, because FOR NO KEY UPDATE conflicts with itself. It just doesn’t conflict with the foreign key checks of the child inserts. You keep the protection against lost updates and drop the part that was blocking your inserts.
The attempts: 3 is a seatbelt, not the fix. Laravel retries a transaction that hits a deadlock, so an occasional one that slips through still succeeds. Retries re-run your closure from the top, so anything inside that has side effects, such as sending an email or dispatching a job, needs to wait until after the commit. Use DB::afterCommit() or ->afterCommit() on the dispatch.
The second fix is an ordering rule that works with either lock: take the parent lock first, before inserting children.
// ✅ Lock the parent first, then insert: no transaction holds a child's KEY SHARE
// while waiting on the parent
DB::transaction(function () use ($invoiceId, $cents) {
$invoice = Invoice::whereKey($invoiceId)->lockForNoKeyUpdate()->firstOrFail();
$invoice->payments()->create(['cents' => $cents]);
$invoice->decrement('balance_cents', $cents);
});
Locking first means a transaction that can’t get the lock waits holding nothing, which can’t form a cycle. Use both rules together: the right lock strength, and a consistent order.
What lockForNoKeyUpdate() Does Not Cover
It’s the wrong lock when you change a referenced key or delete the row. FOR NO KEY UPDATE promises that you won’t change the row’s key. If you’re deleting the parent, or changing the primary key or another column a foreign key points at, you need FOR UPDATE, because child rows’ KEY SHARE locks exist precisely to stop that. PostgreSQL’s documentation defines which columns count; check its explicit-locking page for the exact rule instead of trusting a summary, since my recollection is that it concerns columns covered by a unique index that a foreign key could use, and an UPDATE that changes one of those takes the stronger lock on its own.
It changes nothing on other databases. Per Laravel News, MySQL, SQLite and SQL Server use the same lock as lockForUpdate(), so the method is safe to call on any driver. That also means it fixes nothing there. This is a PostgreSQL-specific improvement.
It isn’t backported, as far as I can tell. The pull request is labeled for 13.x, and I found no 12.x equivalent. On Laravel 12, the query builder’s lock() method accepts a raw lock clause, so this should work as a stopgap. Verify it on your version before relying on it:
$invoice = Invoice::whereKey($invoiceId)->lock('for no key update')->firstOrFail();
You may not need a lock at all. The same author who wrote up the deadlock above pointed out that a single atomic statement avoids the whole question. In Laravel terms, a conditional decrement is one UPDATE with no gap between reading and writing:
// ✅ No explicit lock, no read-modify-write gap
$updated = Invoice::whereKey($invoiceId)
->where('balance_cents', '>=', $cents)
->decrement('balance_cents', $cents);
if ($updated === 0) {
// Not enough balance, or the invoice doesn't exist
}
An UPDATE takes FOR NO KEY UPDATE on its own, so this version can’t deadlock the way the lock-then-update version did. It only works when the business rule fits in a WHERE clause. When you need to read several things and decide, you need the explicit lock, and then you need the right one.
Aborted transactions are a separate trap. PostgreSQL marks a whole transaction as failed after any statement error, so a “try the insert, fall back to an update” pattern inside a transaction breaks. A Laravel contributor hit exactly this with the database cache lock, and put the failure mode this way:
“On Postgres the failed insert aborts the transaction, so the update fails too.” — GitHub user xurshudyan, in framework PR #62114, merged in October 2026
If you’ve ever seen current transaction is aborted, commands ignored until end of transaction block with no obvious culprit, that’s the pattern.
Getting Alerted When a Transaction Runs Too Long
Deadlocks are the loud failure. The common one is quieter: a transaction that stays open for a long time, holding its locks while everything behind it queues up. The new callback in 13.44 gives you a place to notice.
// app/Providers/AppServiceProvider.php
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
public function boot(): void
{
DB::whenTransactionRunsLongerThan(CarbonInterval::seconds(5), function ($connection, $event, $duration) {
Log::warning('Slow database transaction', [
'connection' => $connection->getName(),
'duration_ms' => $duration,
]);
});
}
The shape of the callback, with the connection, an event and a duration in milliseconds, comes from the Laravel News example, which uses a 15-second threshold. That’s a demonstration value. Pick yours from reality: measure your normal transaction duration, set the threshold well above it, and tighten it over time. A threshold that fires constantly gets ignored, and one set too high never fires.
Two limits matter. I couldn’t confirm whether this callback can fire while a transaction is still open, or only when it ends. The example logs the duration, which suggests it’s measured at the end. If that’s right, a transaction that hangs forever never produces an alert, so the callback can’t be your only defense. And the callback tells you that a transaction was slow, not why. Log enough to find it, such as the connection and the route or job name from your own context, and be careful about logging query bindings, which can contain personal data.
The Database Should Have Its Own Limits
Application-level alerts are a second line. PostgreSQL can enforce limits itself, and these settings stop a slow transaction from becoming an outage:
-- New sessions for this role give up waiting for a lock after 5 seconds
ALTER ROLE app_user SET lock_timeout = '5s';
-- A session that opens a transaction and goes idle is terminated after 30 seconds
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s';
And in postgresql.conf, log_lock_waits = on records any lock wait longer than the deadlock timeout, which turns “the site felt slow at 4pm” into a log line naming the blocked query. For a single operation that you know is risky, set the limit inside the transaction instead:
DB::transaction(function () {
DB::statement("SET LOCAL lock_timeout = '3s'");
// ... the risky work
});
Why the idle timeout matters is easy to underrate. One engineer who wrote up five PostgreSQL incidents described a query killer that cancelled four UPDATE statements, which had been “running” for over thirty minutes because they were waiting on a lock. The real culprit was a session sitting idle inside a transaction, and the standard cancel function couldn’t touch it:
“pg_cancel_backend() does nothing to an idle in transaction session” — a DEV Community author writing as johnvithera01, in “Your PostgreSQL isn’t slow, it’s waiting”
In Laravel apps, that idle-in-transaction session is usually a DB::transaction() that makes an HTTP call or waits on something slow before it commits. Keep network calls outside transactions.
When something is already stuck, ask PostgreSQL who is blocking whom:
SELECT pid,
pg_blocking_pids(pid) AS blocked_by,
wait_event_type,
state,
now() - xact_start AS transaction_age,
left(query, 80) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
What the Community Is Already Saying
The change landed to a quick, practical reaction. Md. Khorshed Alam, a developer who works with PostgreSQL, described where it matters:
“a great addition for busy billing tables” — Md. Khorshed Alam, on a social post about
lockForNoKeyUpdate()in Laravel 13.44
That’s the right instinct. Billing, inventory and ledger tables are where a parent row is both updated often and referenced by many child inserts, which is exactly the shape that deadlocks.
An Upgrade and Audit Checklist
Work through these in order. Do the audit before the upgrade, because the audit is where the value is.
- Find every explicit lock.
grep -rn "lockForUpdate\|sharedLock" app/ src/lists them. Each one is a place to ask what the code needs. - Classify each one. If the transaction only updates non-key columns of the locked row, it’s a candidate for
lockForNoKeyUpdate(). If it deletes the row or changes a referenced key, leave it aslockForUpdate(). - Look for the insert-then-lock pattern. Any transaction that creates a child row and then locks the parent is the deadlock shape from this post. Reorder it, or switch the lock, or both.
- Add retries where they’re safe.
DB::transaction($callback, attempts: 3), with side effects moved to after the commit. - Upgrade to 13.44 or later. Confirm with
composer show laravel/framework. On 12.x, use the rawlock()clause for now. - Turn on the database’s own limits.
log_lock_waits,lock_timeoutandidle_in_transaction_session_timeout, set on the application role rather than globally. - Register the slow-transaction callback with a threshold based on your measured baseline.
- Reproduce the deadlock once with the two-session SQL above on a copy of your schema, so you recognize it next time.
Which Lock to Reach For
Do you need to block other writers from changing this row?
├─ No → Don't lock. Prefer one atomic UPDATE with a WHERE clause.
└─ Yes → Will you delete the row or change a column a foreign key points at?
├─ Yes → lockForUpdate()
└─ No → lockForNoKeyUpdate() (PostgreSQL; same as lockForUpdate() elsewhere)
Then, regardless of which lock:
├─ Lock the parent before inserting children
├─ Keep the transaction short: no HTTP calls, no sleeps inside it
├─ Retry with attempts: N, and put side effects after the commit
└─ Alert on slow transactions, and set lock_timeout and idle_in_transaction_session_timeout
The Verdict
The deadlock in this post is hard to find because every line of the code is reasonable. Inserting a child row is normal. Locking a parent before updating it is careful. The failure lives in the interaction between a lock you asked for and a lock PostgreSQL took on your behalf, and the only way to see it is to know the second lock exists. lockForNoKeyUpdate() doesn’t add a capability so much as it removes a mismatch: it lets you request what your update needs instead of the strongest lock available. Use it wherever you’re updating non-key columns on PostgreSQL, keep lockForUpdate() for deletes and key changes, and take parent locks first. Then put limits and an alert around transactions, because the next slow one won’t announce itself either. The fix is one method name. The skill is knowing which of the four locks you actually meant.
