The Last Ticket Sold Twice: Database Race Conditions, Proven and Fixed

On this page
Below is the checkout function of a small ticket shop. It sells one concert ticket if there is one left. Read it the way you would read a pull request, and decide whether you would approve it.
async function buyTicket(buyer) { const db = await pool.connect(); try { await db.query('BEGIN'); const { rows: [t] } = await db.query('SELECT stock FROM tickets WHERE id = 1'); if (t.stock < 1) { await db.query('ROLLBACK'); return { ok: false, reason: 'sold out' }; } await db.query('UPDATE tickets SET stock = $1 WHERE id = 1', [t.stock - 1]); await db.query('INSERT INTO orders (ticket_id, buyer) VALUES (1, $1)', [buyer]); await db.query('COMMIT'); return { ok: true }; } finally { db.release(); }}Nothing in it looks wrong. It reads the stock, refuses when nothing is left, writes the new number, records the order, and wraps all of it in a transaction. The SQL is valid, the sold-out path rolls back, and the connection is always released.
I gave this function ten tickets and sent it one hundred buyers at the same moment, against a real PostgreSQL database. It sold one hundred tickets. When the dust settled, the stock column still said nine were left. No exception was thrown and no error was logged. Every buyer got a confirmation.
That bug has a name, the race condition, and it lives in almost every system that sells, books, reserves or spends something. In the rest of this article we will build the shop, break it on purpose, slow the failure down until each step is visible, and then fix it four ways, measuring every fix against the same crowd. The code, the load tests and every number below come from a lab you can run yourself: last-ticket-race-lab (opens in a new tab), measured on PostgreSQL 18.7 and MySQL 8.4.13 in Docker on an Apple M1.
A Shop With Ten Tickets
Let us start with the smallest shop that can sell something. Two tables: one row that holds the stock, and one table that records orders.
CREATE TABLE tickets ( id int PRIMARY KEY, name text NOT NULL, stock int NOT NULL, version int NOT NULL DEFAULT 0);
CREATE TABLE orders ( id bigserial PRIMARY KEY, ticket_id int NOT NULL REFERENCES tickets (id), buyer int NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
INSERT INTO tickets (id, name, stock) VALUES (1, 'Concert, front row', 10);Ignore the version column for now. It will matter much later.
The checkout is the function you just reviewed, and its transaction feels like it should make it safe.
Test it the way most of us test: click "Buy" eleven times, one after another. Ten clicks succeed, the eleventh says "sold out", and the stock ends at zero. Ship it.
The problem is that nobody buys concert tickets one after another.
Now Let Everyone In at Once
To release a crowd, the lab starts one hundred calls to that function at the same moment, each on its own database connection, and waits for all of them:
const results = await Promise.all( Array.from({ length: 100 }, (_, i) => buyTicket(i + 1)),);Here is the lab's page right after that run:

Ten tickets, one hundred orders, and nine tickets supposedly still on the shelf. The page also adds orders and remaining stock together: they should make 10, and they make 109.
The lab also sends one real HTTP request per buyer, to make sure this is not an artifact of calling functions directly. Here is that load test against all six strategies we will meet in this article. For now, look only at the first row:
$ npm run bench100 concurrent HTTP requests per strategy, 10 tickets for sale, against http://localhost:3000
strategy 200 sold 409 refused other orders stock left oversold time------------- -------- ----------- ----- ------ ---------- -------- -----naive 100 0 0 100 6 90 432 msdecrement 100 0 0 100 -90 90 178 msatomic 10 90 0 10 0 0 85 msforUpdate 10 90 0 10 0 0 76 msoptimistic 10 90 0 10 0 0 116 msserializable 10 90 0 10 0 0 148 msSame result over real HTTP: 100 sold, 90 of them tickets that never existed, and six tickets still "in stock". The exact stock number changes from run to run. The oversell does not.
Two things are wrong here, and they are different problems:
- We sold more than we had. Ninety buyers paid for nothing.
- The stock count is wrong. Even counting only what was recorded, 100 orders plus 9 remaining makes 109 tickets out of 10.
To understand both, we need to slow the crowd down to two people.
Slow Motion: Two Buyers, One Ticket
A hundred buyers at once is too fast to watch. So the lab has a script that runs two buyers, A and B, against a single ticket, and forces their steps into one fixed order so the race happens the same way every time. Here is the code from the previous section, played in slow motion:
$ npm run step1. Read, check, write (READ COMMITTED, the PostgreSQL default) (stock starts at 1) 3 ms A SELECT stock -> 1 5 ms B SELECT stock -> 1 8 ms A UPDATE stock = 0, INSERT order, COMMIT 10 ms B UPDATE stock = 0, INSERT order, COMMIT Result: 2 order(s) for 1 ticket, stock column shows 0Read it line by line, because the whole bug is in those four lines:
- A reads the stock: 1. One ticket left, so A's check passes.
- Before A writes anything, B reads the stock: still 1. B's check passes too.
- A writes 0 and records an order.
- B writes 0 and records an order.
Both buyers were sold the last ticket. And look at the final state: stock 0, which looks perfectly normal. Without the orders table, nobody would ever know.
Before train tickets were sold online, the counters at Kamalapur railway station ran into this every holiday rush. Two clerks sat at two windows with one paper seat chart hanging between them. A passenger at window one asked for seat 23, and the clerk glanced at the chart: free. At that same moment a passenger at window two asked for seat 23, and that clerk glanced at the chart too: still free, because the first clerk had not written anything yet. Both clerks wrote a ticket, and two passengers would later arrive at one seat.
Nobody in that story was careless. Each clerk did exactly the right thing based on what they saw. The problem is the gap between looking at the chart and writing on it. During that gap, the chart is telling a truth that is about to expire.
That gap has a name in security circles: time of check to time of use, or TOCTOU. It is catalogued as CWE-367 (opens in a new tab), a special case of the general race condition, CWE-362 (opens in a new tab).
The transaction did not help
Our code ran inside BEGIN and COMMIT. A transaction makes a group of writes all-or-nothing. It does not, by default, stop another transaction from reading the same row before you write it. PostgreSQL's default isolation level, READ COMMITTED, lets B see the last committed value, and when B read, that value was still 1.
Why the Count Was Wrong Too: Lost Updates
The two-buyer replay explains the overselling. It does not yet explain why the stock column said nine after a hundred sales. Run the same two buyers with ten tickets in stock and follow the stock column:
| Step | Buyer A | Buyer B | stock in the database |
|---|---|---|---|
| 1 | reads 10 | 10 | |
| 2 | reads 10 | 10 | |
| 3 | writes 10 - 1 = 9 | 9 | |
| 4 | writes 10 - 1 = 9 | 9 |
Two tickets left the building, but the stock only went down by one. B's write did not add to A's work; it silently replaced it. This is called a lost update, and it is exactly why the screenshot showed 100 orders and a stock of 9: most of the hundred writes overwrote each other.
The "baki khata", the credit notebook kept at a neighbourhood shop, breaks in exactly this way when a family shares it. Two members of the family both remember that the family owes 1,200 taka. One buys something for 150 and writes 1,350. The other buys something for 300 and, from memory, writes 1,500. One purchase has vanished from the notebook. The fix the shopkeeper uses is obvious once you see it: never write a total from memory; always add to whatever number is in the notebook right now.
We can try exactly that fix in code. Keep the check, but instead of writing an absolute number, decrement relative to the current value:
UPDATE tickets SET stock = stock - 1 WHERE id = 1;Run the same two-buyer replay:
2. Read, check, decrement (stock starts at 1) 2 ms A SELECT stock -> 1 14 ms B SELECT stock -> 1 16 ms A UPDATE stock = stock - 1, INSERT order, COMMIT 18 ms B UPDATE stock = stock - 1, INSERT order, COMMIT Result: 2 order(s) for 1 ticket, stock column shows -1The count is now honest, and that honesty is the worst news yet: the stock is -1. With a hundred buyers, the second row of the load test above shows the stock at -90. The lost updates are gone, but the overselling is not, because the check still happens before the write, in a separate step. This "half fix" is very common in real code, and it is useful to understand because it makes the overselling visible: negative stock is a confession.
But Node.js Is Single-Threaded
A common objection at this point: "My server runs on Node.js, which is single-threaded. Two requests cannot run at the same time, so how can they race?"
They do not need to run at the same time. They only need to take turns at the wrong moments.
Every await in the checkout function is a door. When request A awaits the database, Node.js does not sit idle; it walks through the door and runs request B until B also awaits something. Then it comes back to whichever is ready. With one thread and zero parallelism, A's SELECT and B's SELECT can still both happen before either UPDATE. That is concurrency: several tasks in progress at once. A race needs concurrency; it does not need parallelism.
The database adds its own concurrency on top. Each request in our lab uses its own connection, and PostgreSQL runs each connection in its own server process. So even if your application ran requests strictly one at a time, two instances of your app behind a load balancer, or a cron job running next to a web request, would bring the race right back.
This Has Cost Real Money
It is tempting to file this under "theoretical". These are documented cases where exactly this pattern was exploited:
| When | What happened | Source |
|---|---|---|
| March 2014 | Flexcoin, a bitcoin bank, lost 896 BTC, then worth about 600,000 US dollars, and shut down. An attacker sent thousands of simultaneous transfer requests, so balance checks passed before debits landed. | PCWorld (opens in a new tab) |
| March 2014 | At the Poloniex exchange, withdrawals sent at nearly the same moment were each checked against the same balance. The owner gave the example of an account with 2 BTC withdrawing 10 and ending at -8. About 12.3% of the exchange's bitcoin was taken. | Owner's post (opens in a new tab) |
| May 2015 | Researcher Egor Homakov sent two Starbucks gift card transfers at the same moment, so one 5 dollar transfer ran twice, turning 15 dollars of balance into 20. | Sakurity (opens in a new tab) |
| December 2019 | A reported bug at Reverb let a 25 dollar gift card be redeemed 7 times in parallel, adding 175 dollars of credit. | HackerOne report (opens in a new tab) |
| January 2023 | GitLab fixed CVE-2022-4037, where two simultaneous email change requests could send a confirmation token to the wrong address. It was found with the "single-packet attack" research described later. | PortSwigger research (opens in a new tab) |
| April 2025 | CVE-2024-58248: nopCommerce placed orders without locking, so one gift card could be redeemed more than once. | CVE record (opens in a new tab) |
Notice the shape they all share. Check a balance, a gift card or a limit; then, in a separate step, use it. Whenever money, credit, stock, coupons or seats are involved, the read-check-write gap is a door someone will eventually walk through, either by accident in a flash sale or on purpose.
The Poloniex owner's explanation also contains a lesson for the "half fix": balances went negative, and their audit only checked that deposits minus withdrawals matched the records, so it never noticed. Negative numbers are the confession, but only if somebody is looking.
Two Problems That Look the Same
Before fixing anything, it is worth separating two problems that are often mixed up, because they need different fixes.
| Same buyer, same request, twice | Different buyers, one ticket | |
|---|---|---|
| Looks like | A double click, a retry after a timeout, an app resending on a weak network | Two people, two phones, one seat left |
| What it really is | One intent, several attempts | Several intents, one resource |
| Fix | Idempotency key behind a UNIQUE constraint | Concurrency control: the four fixes below |
The same buyer, twice. A double click, a browser retrying after a timeout, a mobile app resending on a weak network. This is one intent arriving as several attempts. The fix is idempotency: the client generates one key per checkout attempt, the server stores it in a column with a UNIQUE constraint, and a second attempt with the same key finds the first order instead of creating a new one. Stripe's API works this way with its Idempotency-Key header. I wrote about the deeper version of this problem in Why AI Agents Double Charge and in the exactly-once delivery myth.
Different buyers, one resource. Two people, two phones, two perfectly valid requests, and one seat. No key can merge these, because they really are different intents. This is the problem the rest of this article solves.
A real checkout usually needs both.
Fix 1: Put the Check Inside the Write
Go back to the Kamalapur counters. The cleanest fix is not to hire a supervisor. It is to change the rule: a clerk may only write a passenger's name into a box if the box is still empty at the moment of writing. The check and the write become one action.
In SQL, that is a conditional update:
UPDATE tickets SET stock = stock - 1 WHERE id = 1 AND stock > 0;There is no separate SELECT any more. The database decrements the stock only if it is still above zero, and tells you how many rows it changed. One row means you sold a ticket. Zero rows means it is sold out.
async function buyTicket(buyer) { const db = await pool.connect(); try { await db.query('BEGIN'); const res = await db.query('UPDATE tickets SET stock = stock - 1 WHERE id = 1 AND stock > 0'); if (res.rowCount === 0) { await db.query('ROLLBACK'); return { ok: false, reason: 'sold out' }; } await db.query('INSERT INTO orders (ticket_id, buyer) VALUES (1, $1)', [buyer]); await db.query('COMMIT'); return { ok: true }; } finally { db.release(); }}But wait. What if A and B both run this UPDATE at the same moment, while the stock is 1? Here is the replay, with A deliberately pausing for half a second before committing:
3. Fix 1: atomic conditional UPDATE (stock starts at 1) 2 ms A UPDATE ... WHERE stock > 0 -> 1 row updated (not committed yet) 2 ms B UPDATE ... WHERE stock > 0 (blocks: A holds the row) 507 ms A INSERT order, COMMIT 507 ms B ...re-checks stock > 0 on the new row -> 0 rows updated, sold out Result: 1 order(s) for 1 ticket, stock column shows 0Two things happen that make this safe:
- Updates on the same row queue up. When A updates the row, A holds a lock on it until A commits. B's UPDATE has to wait.
- The waiting UPDATE checks again. This is the subtle part. The PostgreSQL documentation on transaction isolation (opens in a new tab) explains that in READ COMMITTED mode, when a waiting UPDATE finally gets the row, the WHERE clause "is re-evaluated to see if the updated version of the row still matches". B does not trust the stale 1 it might have seen earlier. It looks at the row A left behind, sees 0, and updates nothing.
In the load test, this fix sold exactly 10 tickets, refused 90 buyers, and was the fastest strategy of all. MySQL behaves the same way here, because its UPDATE statements also work on the latest committed version of the row.
Reach for this first
If your rule fits in one row's WHERE clause, such as "stock above zero", "balance at least the amount", or "seats booked below capacity", the conditional UPDATE is the simplest and cheapest fix. Always check the affected row count; ignoring it brings the bug right back.
Fix 2: Lock the Row While You Read It
Sometimes the decision cannot be squeezed into a WHERE clause. You need to read the row, run some application logic (apply a discount, check the buyer's limit, call a fraud service), and only then write. For that, you can tell the database to lock the row at the moment you read it:
SELECT stock FROM tickets WHERE id = 1 FOR UPDATE;FOR UPDATE means "I am reading this row because I intend to change it. Nobody else may lock or change it until I finish." The rest of the checkout stays the same:
await db.query('BEGIN');const { rows: [t] } = await db.query('SELECT stock FROM tickets WHERE id = 1 FOR UPDATE');if (t.stock < 1) { await db.query('ROLLBACK'); return { ok: false, reason: 'sold out' }; }await db.query('UPDATE tickets SET stock = stock - 1 WHERE id = 1');await db.query('INSERT INTO orders (ticket_id, buyer) VALUES (1, $1)', [buyer]);await db.query('COMMIT');The replay shows the effect immediately: B is not allowed to read until A is done.
4. Fix 2: SELECT ... FOR UPDATE (stock starts at 1) 2 ms A SELECT ... FOR UPDATE -> 1 (row locked) 2 ms B SELECT ... FOR UPDATE (blocks: waits for A) 506 ms A UPDATE stock = stock - 1, INSERT order, COMMIT (lock released) 506 ms B ...gets the lock -> 0, sold out Result: 1 order(s) for 1 ticket, stock column shows 0Back at Kamalapur, this is giving the two clerks one register and a rule: you may only look at the chart while you are holding the register, and you hand it over only after you have written. The race becomes a queue.
You can watch that queue form. The lab samples PostgreSQL's pg_stat_activity view and the pg_blocking_pids() function every few milliseconds while the crowd runs. Here is a run with 20 ms of simulated work between the read and the write:

Exactly ten orders, zero oversold, and at the peak 99 sessions were waiting in line behind one row lock. The same query works on your own production database when you want to know who is blocking whom:
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 60) AS queryFROM pg_stat_activityWHERE cardinality(pg_blocking_pids(pid)) > 0;Pessimistic locking has real costs, and it is worth knowing them before you reach for it:
- Every path must take the lock. If an admin panel or a background job updates stock without
FOR UPDATE, it walks straight past the queue. Pessimistic locking only works if every writer cooperates. - Keep the transaction short. While you hold the lock, everyone else waits. Never call a slow external API while holding a row lock if you can avoid it.
- Lock in a consistent order. If one transaction locks row 1 then row 2, and another locks row 2 then row 1, they can wait for each other forever. PostgreSQL detects this deadlock and aborts one of them with SQLSTATE
40P01, which your code should retry. - You can choose not to wait.
FOR UPDATE NOWAITfails immediately instead of queueing, andFOR UPDATE SKIP LOCKEDskips rows that are locked. The PostgreSQL docs (opens in a new tab) warn that SKIP LOCKED gives an inconsistent view and suits queue-like tables, not general checkout logic.
In MySQL, the same SELECT ... FOR UPDATE exists, with one extra trap: according to the MySQL manual (opens in a new tab), locking reads only work when autocommit is disabled, so it must be inside an explicit transaction.
Fix 3: Optimistic Version Check
The first two fixes make buyers wait. The third takes the opposite bet: assume conflicts are rare, let everyone read freely, and only check at the moment of writing whether anyone else changed the row in the meantime.
This is where the version column comes in. Every successful write increments it. Every write only succeeds if the version is still the one you read:
SELECT stock, version FROM tickets WHERE id = 1; -- say: 1, version 0UPDATE ticketsSET stock = stock - 1, version = version + 1WHERE id = 1 AND version = 0; -- 0 rows means someone got there firstIf the UPDATE changes zero rows, someone else wrote first. You read again and try again, or tell the user the data changed.
5. Fix 3: optimistic version check (stock starts at 1) 1 ms A SELECT stock, version -> 1, v0 2 ms B SELECT stock, version -> 1, v0 4 ms A UPDATE ... WHERE version = 0 -> 1 row, INSERT order, COMMIT 4 ms B UPDATE ... WHERE version = 0 -> 0 rows, someone got there first, retry 5 ms B SELECT stock, version -> 0, v1, sold out Result: 1 order(s) for 1 ticket, stock column shows 0Long-distance buses face the same thing with their last seat, sold by a conductor at the front door and a helper at the back. Optimistic locking is a seat chart with a revision stamp in the corner. Before you write a passenger's name, you compare the stamp with the one you saw when you checked. If it changed, somebody else wrote on the chart since you looked, so you look again.
Most ORMs build this in, and you have probably used it without calling it by name:
- Hibernate and JPA: a field annotated
@Version. A stale write throws anOptimisticLockException. - Ruby on Rails: a
lock_versioncolumn. A stale write raisesActiveRecord::StaleObjectError. - Prisma: the transactions guide (opens in a new tab) shows the pattern with
updateManyfiltered on id and version, where acountof 0 means a conflict.
Optimistic locking shines when conflicts are rare and the "transaction" is long, such as a user editing a document for five minutes. You would never hold a database lock for five minutes. It is a poor fit for a flash sale, where conflicts are the whole point: in the lab's comparison run, settling 100 buyers on 10 tickets took 252 retries.
Fix 4: SERIALIZABLE and Retry
The last fix changes nothing in the checkout logic at all. It keeps the original buggy read-check-write code and asks the database to guarantee something stronger: that the result is the same as if the transactions had run one at a time, in some order.
BEGIN ISOLATION LEVEL SERIALIZABLE;SELECT stock FROM tickets WHERE id = 1;UPDATE tickets SET stock = <stock - 1> WHERE id = 1;INSERT INTO orders (ticket_id, buyer) VALUES (1, <buyer>);COMMIT;PostgreSQL cannot actually run them one at a time without destroying throughput, so it watches for conflicts instead. When it sees two transactions that could not have produced this result in any serial order, it aborts one of them:
6. Fix 4: SERIALIZABLE with retry (stock starts at 1) 2 ms A SELECT stock -> 1 4 ms B SELECT stock -> 1 6 ms A UPDATE stock = 0, INSERT order, COMMIT 7 ms B UPDATE -> ERROR 40001: could not serialize access due to concurrent update 9 ms B retry: SELECT stock -> 0, sold out Result: 1 order(s) for 1 ticket, stock column shows 0That error is not a bug in your code; it is the database doing its job. The PostgreSQL documentation is explicit that applications using this level must be prepared to retry, and that serialization failures always come with SQLSTATE 40001. The retry must repeat the whole transaction from the beginning, including the read, because the old read is exactly what was wrong:
async function buyTicketSerializable(buyer, maxAttempts = 10) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { const db = await pool.connect(); try { await db.query('BEGIN ISOLATION LEVEL SERIALIZABLE'); const { rows: [t] } = await db.query('SELECT stock FROM tickets WHERE id = 1'); if (t.stock < 1) { await db.query('ROLLBACK'); return { ok: false, reason: 'sold out' }; } await db.query('UPDATE tickets SET stock = $1 WHERE id = 1', [t.stock - 1]); await db.query('INSERT INTO orders (ticket_id, buyer) VALUES (1, $1)', [buyer]); await db.query('COMMIT'); return { ok: true }; } catch (error) { await db.query('ROLLBACK').catch(() => {}); if (error.code !== '40001') throw error; // only retry serialization failures await new Promise((r) => setTimeout(r, Math.random() * 2 ** attempt)); // jittered backoff } finally { db.release(); } } return { ok: false, reason: 'too busy, try again' };}Why would anyone choose this over the simpler fixes? Because some rules do not live in one row. Take a hospital rule that at least one doctor must always be on call, or an app rule that a team must always keep at least one admin. Two people each check that "someone else is still on call" and both sign off. Neither changed the other's row, so no row lock or version check notices. Martin Kleppmann's Designing Data-Intensive Applications calls this write skew. It is like two flatmates in a shared mess flat, each seeing that the other is still home with the key, and both leaving. SERIALIZABLE catches it; the other fixes do not.
The price is retries. In the comparison run, SERIALIZABLE needed 461 retries to settle 100 buyers on one hot row. For a single counter under heavy contention, the conditional UPDATE is far cheaper. SERIALIZABLE earns its cost when the rule spans many rows and contention is moderate.
The Safety Net: Constraints
All four fixes live in application code, and application code has bugs, forgotten paths and future developers. The database can enforce a last line of defence that no code path can skip:
ALTER TABLE tickets ADD CONSTRAINT stock_not_negative CHECK (stock >= 0);Here is the "half fix" from earlier, the one that drove stock to -90, run again with that constraint in place:

Ten sold, ninety rejected by the database, stock stays at zero. The constraint turned an oversell into errors, which is exactly what a safety net is for.
But notice what it cannot do. The original buggy code writes absolute numbers like 9 and 0, which never break stock >= 0, so the same constraint does nothing against lost updates. And the PostgreSQL docs on constraints (opens in a new tab) note that a CHECK constraint can only look at the row being written, not at other rows. Constraints are a net under the trapeze, not a replacement for the trapeze. Use CHECK for single-row rules, UNIQUE for "only one of these may exist" (one seat per show, one order per idempotency key), and real concurrency control for everything else.
Isolation Levels Do Not Mean the Same Thing Everywhere
You may have read that raising the isolation level to REPEATABLE READ prevents lost updates. In PostgreSQL, it does. The lab runs the original buggy code at the levels each database calls READ COMMITTED and REPEATABLE READ, step by step:
$ npm run mysqlPostgreSQL 18.7 (Debian 18.7-1.pgdg13+5), READ COMMITTED A SELECT stock -> 1 B SELECT stock -> 1 A UPDATE stock = 0, COMMIT B UPDATE stock = 0, COMMIT -> accepted => LOST UPDATE: both buyers were sold the last ticket
PostgreSQL 18.7 (Debian 18.7-1.pgdg13+5), REPEATABLE READ A SELECT stock -> 1 B SELECT stock -> 1 A UPDATE stock = 0, COMMIT B UPDATE -> ERROR 40001: could not serialize access due to concurrent update => prevented: the database refused the second write (retry it)
MySQL 8.4.13, READ COMMITTED A SELECT stock -> 1 B SELECT stock -> 1 A UPDATE stock = 0, COMMIT B UPDATE stock = 0, COMMIT -> accepted => LOST UPDATE: both buyers were sold the last ticket
MySQL 8.4.13, REPEATABLE READ A SELECT stock -> 1 B SELECT stock -> 1 A UPDATE stock = 0, COMMIT B UPDATE stock = 0, COMMIT -> accepted => LOST UPDATE: both buyers were sold the last ticketSame SQL, same isolation level name, opposite outcomes. PostgreSQL's REPEATABLE READ notices that the row changed after B's snapshot and refuses B's write. MySQL's REPEATABLE READ, which is MySQL's default, accepts it, because in InnoDB an UPDATE works on the latest committed row even though the earlier SELECT read from an older snapshot. This matches what Martin Kleppmann's Hermitage (opens in a new tab) project found when it tested these databases.
| Isolation level | PostgreSQL | MySQL (InnoDB) |
|---|---|---|
| READ COMMITTED | Lost update possible (PostgreSQL's default) | Lost update possible |
| REPEATABLE READ | Prevented, with error 40001 to retry | Lost update possible (MySQL's default) |
| SERIALIZABLE | Prevented, with error 40001 to retry | Prevented |
The practical lesson: never rely on an isolation level's name. Know which database you are on, or better, use one of the four fixes, which behave the same way on both.
The Scoreboard
Here is every strategy against the same crowd of 100 buyers and 10 tickets, run from the lab's browser page:

| Strategy | Orders | Stock left | Oversold | Retries | Time |
|---|---|---|---|---|---|
| Read, check, write (the bug) | 100 | 9 | 90 | 0 | 418 ms |
| Read, check, decrement (half a fix) | 100 | -90 | 90 | 0 | 111 ms |
| Fix 1: atomic conditional UPDATE | 10 | 0 | 0 | 0 | 42 ms |
| Fix 2: SELECT ... FOR UPDATE | 10 | 0 | 0 | 0 | 57 ms |
| Fix 3: optimistic version check | 10 | 0 | 0 | 252 | 99 ms |
| Fix 4: SERIALIZABLE + retry | 10 | 0 | 0 | 461 | 149 ms |
These timings come from one machine and one run, so do not treat them as a benchmark. The pattern is what matters: under heavy contention on a single row, the fixes that queue (atomic update, row lock) are cheap, and the fixes that retry (optimistic, serializable) pay for every conflict.
The pool can hide the bug
node-postgres opens at most 10 connections by default. With that pool, "100 simultaneous buyers" would really run 10 at a time, and the race would mostly disappear in testing, only to return in production with more instances. The lab uses a pool of 120. When you test for races, make sure your test can actually create the concurrency you are worried about.
ORMs Hide the Gap
Most applications do not write SQL by hand, and ORMs make the read-check-write gap even easier to miss, because the read and the write look like ordinary object manipulation. This Prisma code has exactly the same bug as our first version:
const ticket = await prisma.ticket.findUnique({ where: { id: 1 } });if (ticket.stock > 0) { await prisma.ticket.update({ where: { id: 1 }, data: { stock: ticket.stock - 1 } }); // writes a number computed from a stale read}The fix is the same idea as Fix 1, expressed through the ORM: let the database do the check and the arithmetic in one statement, and look at how many rows changed.
const { count } = await prisma.ticket.updateMany({ where: { id: 1, stock: { gt: 0 } }, data: { stock: { decrement: 1 } },});if (count === 0) throw new SoldOutError();Other ORMs have the same tools under different names. In Django, Ticket.objects.filter(id=1, stock__gt=0).update(stock=F('stock') - 1) returns the number of rows changed, and the Django docs on F() expressions (opens in a new tab) describe exactly this race. For Fix 2, Django has select_for_update() inside transaction.atomic(), Laravel has lockForUpdate(), and Rails has lock! and with_lock. Whatever the ORM, the question to ask of any update is: was this value computed from something I read earlier?
How to Find Races in Your Own App
You cannot fix a race you never see, and clicking a button eleven times will never show you one. You need real concurrency in your tests.
Fire many requests at once. The simplest version needs no tools at all:
const responses = await Promise.all( Array.from({ length: 100 }, () => fetch('http://localhost:3000/api/buy', { method: 'POST' })),);console.log(responses.filter((r) => r.status === 200).length, 'sold');Then compare the number of successes with the stock you started with. Command-line load tools such as hey -n 100 -c 100 -m POST <url> or oha print a status-code summary that makes the same comparison easy.
Hammer the database directly. PostgreSQL ships with pgbench (opens in a new tab), which can run your own SQL script from many clients at once (pgbench -n -f buy.sql -c 50 -j 4 -t 20). Since PostgreSQL 15, --max-tries retries serialization failures for you, which makes it a quick way to test the SERIALIZABLE approach.
Replay the interleaving. Open two psql sessions side by side and type the steps of A and B in the order you fear. This is how Hermitage documents every anomaly, and it is what the lab's npm run step automates.
Think like an attacker. In 2023, James Kettle of PortSwigger published Smashing the state machine (opens in a new tab), which introduced the "single-packet attack": 20 to 30 HTTP/2 requests delivered in one TCP packet, so they reach the server within about a millisecond of each other, even across the world. Network jitter used to hide many races from attackers. It no longer does. PortSwigger's free Web Security Academy (opens in a new tab) has hands-on labs for practising this.
Play with a simulator. If you want to step through isolation levels in the browser without installing anything, the Solita team's interactive PostgreSQL isolation level simulators (opens in a new tab) let you move transactions forward one step at a time and watch the row versions.
Run the Lab Yourself
Everything in this article, including the crowd, the timeline, the lock chart, the step-by-step replays and the MySQL comparison, is in one repository:

git clone https://github.com/rafeuddaraj/last-ticket-race-lab.gitcd last-ticket-race-labdocker compose up -d --buildOpen http://localhost:3000, pick a strategy and press Release the buyers. A few things worth trying:
- Run the bug with the think-time slider at 0 ms, then at 50 ms, and watch the timeline.
- Run Fix 2 with think time and watch the lock chart climb.
- Turn on the CHECK constraint and run the decrement strategy.
- Press Compare every strategy and read the retry column.
- Run
npm run stepto see each fix in slow motion, andnpm run mysql(afterdocker compose --profile mysql up -d) to compare the two databases yourself.
The page also reads its settings from the URL, so a link like http://localhost:3000/?strategy=naive&stock=10&buyers=100&run=1 starts a race as soon as it opens.
Choosing a Fix
Most real cases, stock, balances, quotas and counters, end at the first box. Whichever fix you choose, keep the constraints and idempotency keys from earlier as a second layer.
Before You Ship a Checkout
When a pull request touches anything that sells, books, reserves or spends, these are the questions worth asking in review:
- Is there a
SELECTfollowed later by anUPDATEof the same row? What happens if another request runs between them? - Is any written value computed from an earlier read, like
stock = <number from my SELECT>? - Could the check and the write be one statement, with the affected row count checked?
- If the code locks rows, does every other path that changes those rows take the same lock, in the same order?
- If the code retries, does it retry the whole transaction, only on
40001or40P01, with a limit? - Does the code rely on an isolation level by name? Which database will it run on?
- Is there a
CHECKorUNIQUEconstraint that would reject the impossible state if all of the above fails? - Is a repeated request from the same buyer handled separately, with an idempotency key?
- Was it tested with real concurrency, with a connection pool big enough to let the requests through?
Go back to the function at the top of this article. The bug was never in any single line. It was in the space between two lines, the SELECT and the UPDATE, where another buyer could step in. Once you start looking for that space, you will find it in places you reviewed and approved long ago, and you now have four measured ways to close it.
References
- last-ticket-race-lab (opens in a new tab), the lab used for every measurement in this article
- Transaction Isolation (opens in a new tab), PostgreSQL documentation
- Explicit Locking (opens in a new tab), PostgreSQL documentation
- SELECT: the locking clause (opens in a new tab), PostgreSQL documentation
- Constraints (opens in a new tab), PostgreSQL documentation
- pgbench (opens in a new tab), PostgreSQL documentation
- Transaction Isolation Levels (opens in a new tab), MySQL 8.4 Reference Manual
- Locking Reads (opens in a new tab), MySQL 8.4 Reference Manual
- Hermitage: testing transaction isolation levels (opens in a new tab), Martin Kleppmann
- Designing Data-Intensive Applications (opens in a new tab), Martin Kleppmann, chapter 7: Transactions
- A Critique of ANSI SQL Isolation Levels (opens in a new tab), Berenson, Bernstein, Gray, Melton, O'Neil and O'Neil
- CWE-362: Race Condition (opens in a new tab), MITRE
- CWE-367: Time-of-check Time-of-use (opens in a new tab), MITRE
- Smashing the state machine (opens in a new tab), James Kettle, PortSwigger
- Race conditions (opens in a new tab), PortSwigger Web Security Academy
- Withdrawal vulnerabilities enabled bitcoin theft from Flexcoin and Poloniex (opens in a new tab), PCWorld
- Poloniex owner's statement (opens in a new tab), Bitcointalk
- Hacking Starbucks for unlimited coffee (opens in a new tab), Egor Homakov, Sakurity
- Reverb gift card race condition (opens in a new tab), HackerOne
- CVE-2024-58248 (opens in a new tab), nopCommerce
- Transactions and batch queries (opens in a new tab), Prisma documentation
- Query expressions: F() (opens in a new tab), Django documentation
- Optimistic locking (opens in a new tab), Ruby on Rails API
- Pessimistic locking (opens in a new tab), Laravel documentation
- Transactions (opens in a new tab), node-postgres documentation
- Idempotent requests (opens in a new tab), Stripe API reference
- PostgreSQL isolation levels, interactive simulators (opens in a new tab), Solita