SELECT ... FOR UPDATE that locks nothing: I raced two connections and scanned 122 booking and payment repos
It's the Black Friday to Cyber Monday weekend, which is when a checkout finally gets two requests for the same order in the same few milliseconds: a double click on a slow Pay button, a retried webhook, a phone that resends after the signal drops. Code that looked fine all year gets tested for real.
I keep seeing the same snippet in payment tutorials. A Telegram Stars pre_checkout_query handler, a booking
endpoint, a webhook that marks an order paid. Somewhere in the middle there is a SELECT ... FOR UPDATE, and the
article says this is what stops two requests from paying for the same order.
Then the code runs it with pool.query().
A Postgres row lock lives until the end of the transaction that took it
(docs). With node-postgres and no
BEGIN, every statement is its own transaction. So the lock is taken, the row comes back, the statement commits,
and the lock is gone before your code even looks at status. The second request reads the same pending and
goes ahead.
I wanted numbers rather than an argument, so I measured it, and then I went looking for it in real code.
Racing two connections
The repro starts a real PostgreSQL 18.6 server (embedded-postgres), opens separate connections and fires two
requests at the same order at the same moment, 20 rounds per strategy. "Both won" means both requests believed
they were the one that moved the order from pending to paid.
Order 'o1' (pending -> paid):
strategy both won
pool.query + FOR UPDATE (no transaction) 20/20
client.query + FOR UPDATE, no BEGIN 20/20
pool.query('BEGIN') + FOR UPDATE via pool 0/20
same, while one other request uses the pool 20/20
one client: BEGIN, FOR UPDATE, UPDATE, COMMIT 0/20
SELECT status, then UPDATE by id (check-then-act) 20/20
UPDATE ... WHERE status = 'pending' RETURNING 0/20
Wallet 'w1' (balance 100, two withdrawals of 80):
pool.query + FOR UPDATE (no transaction) 20/20 final balance 20
one client: BEGIN, FOR UPDATE, UPDATE, COMMIT 0/20
UPDATE ... SET balance = balance - 80 WHERE balance >= 80 0/20
The row I find scary is the third one. pool.query('BEGIN') followed by more pool.query calls passes a quiet
test, 0 out of 20, because an idle pool hands you the same connection back every time. Add one unrelated request
using the pool and it goes to 20 out of 20, because BEGIN, the locking SELECT and COMMIT can each go out
on a different connection. node-postgres says this on its
transactions page: take one client with pool.connect() and
run the whole transaction on it.
The other thing the table shows is that you often don't need the lock at all. A single
UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending' RETURNING id did the check and the write
in one statement and never double-paid. Zero rows back means someone else got there first. The wallet version is
SET balance = balance - $2 WHERE id = $1 AND balance >= $2.
My own bug first
Before pointing at anyone else, I ran the same idea against the products I sell. One of them, a Telegram shop
bot in Python, had the ORM flavour of this bug: read the product, check stock, subtract, commit. Two buyers
racing for the last unit both got it, 10 times out of 10 on SQLite and 6 out of 10 on PostgreSQL 18. A resent
payment update could also mark the same order paid twice. Stock is now taken with one
UPDATE ... WHERE stock >= qty, a status change only applies if the order is still in the status that was read,
and both races have a test now. That shipped as v1.0.1.
Scanning real repos
I added two checks to vibe-preflight, my open source pre-launch scanner. for-update-autocommit (error) looks
for FOR UPDATE / FOR SHARE that no transaction holds: node-postgres pool calls, a client with no BEGIN,
Prisma $queryRaw outside $transaction, Drizzle .for('update') and Knex .forUpdate() outside a
transaction, Sequelize lock without transaction, asyncpg outside conn.transaction(), postgres.js and Neon
tagged queries outside sql.begin. check-then-act (warning) looks for a status or balance read followed by an
UPDATE whose WHERE never re-checks it.
Then I picked a sample. GitHub repository search for booking, wallet, payment, reservation, ticketing and Telegram shop projects pushed between mid-August and mid-November, with a licence, not forks: 122 repos, shallow-cloned. 48 matched a lock pattern in JS, TS or Python, and 34 of those had real lock calls (the rest matched comments and strings like "check for updates"). That gave 128 lock lines, and I read every one of them in its function.
Most of them were fine, which surprised me a little. People used Prisma $transaction, Drizzle tx, Knex trx,
SQLAlchemy sessions, Django atomic, and a lot of job claims written the right way, as one
UPDATE ... WHERE id IN (SELECT ... FOR UPDATE SKIP LOCKED) RETURNING *. Only 2 of the 128 were locks that lock
nothing, both postgres.js cron claims of the form
const due = await sql`SELECT ... WHERE send_at <= now() LIMIT 50 FOR UPDATE OF s SKIP LOCKED`;
for (const row of due) await send(row);
with a comment above saying the rows are claimed. Each tagged query is its own transaction, so they aren't. In that project the cron runs one job at a time in one process, so it only bites with a second instance or an overlapping deploy. Still a duplicate WhatsApp message waiting to happen.
The plain status race was much more common. The scanner reported 22 findings in total, and I sorted them by hand: 20 real races (9 I'd call high or medium impact for money or bookings, the rest small admin-screen races) and 2 false positives, where a worker updated rows its caller had already claimed with a guarded update.
My first version did worse, and I'd rather say so. On the same sample it reported 30 findings, 12 of them false,
and missed both postgres.js claims. The worst case was Python: one AUTOCOMMIT engine used to CREATE DATABASE
in a test helper made the whole project look autocommit. On one more repo I checked later, that produced 44
false errors. Each miss became a test fixture, and 1.7.1 counts autocommit only for code that imports the module
turning it on.
The one I could prove
The best find was in a small open source cinema app that exists to teach database concurrency, with live
locks and deadlocks in the browser. Its real Pay button checks status = 'PENDING' through the pool before
BEGIN. I wrote a test against the project's own harness that taps Pay twice at once:
DOUBLE PAY {
"http 200/200 -> booking FAILED, seats BOOKED,BOOKED, payments PAID,FAILED": 10
}
CANCEL VS PAY {
"pay 200, cancel 200 -> booking FAILED, seats , payments FAILED": 4,
"pay 200, cancel 200 -> booking CANCELLED, seats BOOKED,BOOKED, payments PAID": 6
}
Ten double taps out of ten left a booking marked FAILED while both seats were booked and one payment was PAID. Cancel racing Pay left a cancelled booking with paid, booked seats 6 times out of 10. The second Pay found no held seats, rolled back, and then wrote FAILED over the booking the first request had just confirmed.
The fix is eight lines: after BEGIN, read the booking again with FOR UPDATE on the same client and answer 409
if it is no longer pending; in Cancel, claim the booking with UPDATE ... WHERE status = 'PENDING' first. Then
both probes came out consistent 10 out of 10, and the project's own 57 tests still passed. I still owe the
maintainer a pull request with it.
What I'd check in your code
Search for for update and look at what runs the query. If it's pool.query, a bare sql tag, or a client
nobody sent BEGIN on, the lock does nothing. Better still, look for every place you read a status and then
write it, and try moving the condition into the UPDATE itself. And write one test that sends the same request
twice with Promise.all. That kind of test is what turned my shop bot bug from a hunch into 10 out of 10.
The scanner is free and MIT: github.com/atokim4/vibe-preflight
(npx github:atokim4/vibe-preflight path/to/app --only concurrency). If you're building a paid Telegram bot, my
AI Telegram bot in Python handles Stars
payments with a unique charge id per payment, so a resent update can't credit a plan twice.
I reran the race table on PostgreSQL 18.6 on November 29 before publishing; the numbers above are from that run. I use AI tools while writing and coding, and I check every number myself.
About the author
- Full-stack developer working with React, Next.js, Node.js and Supabase. My open-source projects are at github.com/atokim4.
Comments
Join the discussionNo comments yet. Be the first to comment.