TL;DR
- The usual "read the stock, check it, write it back" code oversold a single item on both Postgres and MySQL. With 50 buyers arriving at the same moment, one item got an average of 47.5 orders on Postgres and 48.1 on MySQL.
- Switching to
REPEATABLE READstopped it on Postgres (49 buyers got an error instead). On MySQL it changed nothing, becauseREPEATABLE READis already MySQL's default and it was the level that just sold one item 48 times. - The fix that was correct and also the fastest on both databases: one conditional
UPDATE ... WHERE stock > 0, then check how many rows it changed.
Here's a bug report every shop eventually gets: "We had one left. Two people bought it."
The first time I thought about this properly, my instinct was that it had to be rare. Two customers would need to click Buy within a few milliseconds of each other, on the same item, when there's exactly one left. Surely the database handles that?
So I tested it. I wrote the checkout code most of us write, pointed 50 buyers at a product with a stock of 1, and released them all at once. On Postgres the item sold an average of 47.5 times. On MySQL, 48.1 times. In the worst rounds, all 50 buyers got an order for a single item.
This post walks through why that happens, why the isolation level you'd reach for first doesn't behave the same on Postgres and MySQL, and which of the four common fixes actually held up when I measured them.
The code most of us write
Here's a checkout written the way I've seen it in a lot of codebases (error handling trimmed so it fits):
tx, _ := db.BeginTx(ctx, nil) defer tx.Rollback() var stock int tx.QueryRowContext(ctx, "SELECT stock FROM products WHERE id = $1", id).Scan(&stock) if stock <= 0 { return ErrSoldOut } tx.ExecContext(ctx, "UPDATE products SET stock = $1 WHERE id = $2", stock-1, id) tx.ExecContext(ctx, "INSERT INTO orders (product_id) VALUES ($1)", id) return tx.Commit() It's in a transaction. It checks the stock before selling. If you use an ORM, it's probably the same thing in a friendlier shape: load the product, product.Stock--, save it.
It reads like it can't oversell. It will pass every test you write for it, because tests usually run one request at a time. The problem only shows up when requests overlap, and on a busy product launch they overlap a lot.
The experiment
I wanted real numbers instead of a theory, so I set up:
- Postgres 18 and MySQL 8.4 , both in Docker with default settings
- A
productstable with one row and anorderstable - 50 goroutines, each acting as one buyer, all waiting on a channel that I close as a starting gun so they hit the database together
- 20 rounds per approach, with the stock reset to 1 before each round
Releasing everyone at once is deliberate. It's what a ticket release, a limited drop or a flash sale looks like: lots of people pressing Buy in the same second.
Here's what the code above did:
| Database (default isolation) | Rounds oversold | Avg orders for 1 item | Worst round |
|---|---|---|---|
Postgres (READ COMMITTED) | 19 of 20 | 47.5 | 50 |
MySQL (REPEATABLE READ) | 20 of 20 | 48.1 | 50 |
Then I tried a bigger sale: 1,000 items in stock and 3,000 purchase attempts from 50 buyers. Both databases accepted all 3,000 orders. And the part that made me laugh: when it finished, the stock column on Postgres still said 933 items left. The shop had sold three times its stock and believed it had barely started.
Why it happens
The transaction protects less than it looks like it does. Here are two buyers on Postgres's default level, READ COMMITTED:
- Buyer A reads the stock: 1.
- Buyer B reads the stock: also 1, because A hasn't committed anything yet.
- Both pass the
stock <= 0check. - A writes
stock = 0and creates an order. - B's
UPDATEwaits for A's row lock. When A commits, B carries on and writesstock = 0too, then creates a second order.
Nothing failed. Every statement did exactly what it was told. The problem is that B made its decision using a value that was already out of date, and the database had no way of knowing the 0 it was writing came from that stale read.
This is called a lost update : two transactions read the same value, both write a new one based on it, and one write silently replaces the other. It also explains the 933. With 50 buyers overlapping, a whole group would read the same stock, each write "that number minus one", and the counter would only go down by one for the entire group.
One more thing worth noticing: a CHECK (stock >= 0) constraint wouldn't have caught any of this. The code never wrote a negative number. It wrote 0, 49 times.
"Just use a stricter isolation level"
This was my first idea, and it's where Postgres and MySQL split.
REPEATABLE READ sounds like exactly what we need: the transaction works from a consistent snapshot, so surely it notices when someone else changes the row? I ran the same code with that isolation level set explicitly:
Database at REPEATABLE READ | Rounds oversold | Avg orders for 1 item | Errors |
|---|---|---|---|
| Postgres | 0 of 20 | 1.0 | 980 (49 per round) |
| MySQL | 20 of 20 | 50.0 | 0 |
Same code, same isolation level name, opposite results.
Postgres refuses to let a REPEATABLE READ transaction update a row that another transaction changed after its snapshot was taken. When buyer B's UPDATE gets the lock and finds that A already changed the row, it fails with:
ERROR: could not serialize access due to concurrent update So one buyer wins and the other 49 get an error. No overselling.
MySQL (InnoDB) handles it differently. Under REPEATABLE READ, a plain SELECT reads from your snapshot and takes no locks. But an UPDATE always works on the latest committed version of the row, and InnoDB doesn't check whether that row changed since your snapshot. So B's UPDATE waits for A, then happily writes the 0 it calculated from the old value. MySQL's documentation does say the snapshot applies to SELECT statements and not necessarily to writes, but it's easy to go years without reading that line.
That's why I said in the TL;DR that MySQL's default didn't help. MySQL already runs at REPEATABLE READ by default, so the first table above was this exact behaviour.
There's also a catch on the Postgres side. Look at those 980 errors. In the 1,000-item sale, REPEATABLE READ with no retry logic sold fewer than 100 of the 1,000 items , because almost every buyer who overlapped with someone got an error and gave up. You've swapped overselling for customers staring at an error page while the stock sits there. A stricter isolation level is only a fix if you also retry.
Four fixes, and what they cost
These are the four approaches I see recommended most. All four stopped the overselling completely on both databases. Where they differ is speed and how they behave under pressure.
1. Let the database do the check: a conditional UPDATE
res, err := tx.ExecContext(ctx, "UPDATE products SET stock = stock - 1 WHERE id = $1 AND stock > 0", id) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrSoldOut } // then insert the order and commit There's no separate read any more. The check (stock > 0) and the write happen in one statement, and both databases evaluate that WHERE against the current row after waiting for any lock on it. When buyer B finally gets the row, the stock is already 0, the condition is false, and zero rows are updated. B gets "sold out" and nothing is written.
I like this one because there's nothing to remember. No isolation level to set, no retry loop, no version column. stock - 1 also means the database does the maths, so a stale value in your Go code can't leak into the table.
2. Lock the row while you decide: SELECT ... FOR UPDATE
tx.QueryRowContext(ctx, "SELECT stock FROM products WHERE id = $1 FOR UPDATE", id).Scan(&stock) This keeps the original code shape and adds two words. FOR UPDATE takes the row lock at read time, so buyer B's SELECT waits until A commits and then reads the real value.
This is the right choice when the decision needs more than a single comparison, for example "only if this customer hasn't bought one already" or "only if the coupon is still valid". The cost is that every buyer queues on that row for the whole transaction. Whatever you do between the SELECT and the commit, every other buyer waits for it. Please don't call a payment API while holding that lock.
3. Optimistic locking: a version column
UPDATE products SET stock = $1, version = version + 1 WHERE id = $2 AND version = $3 Read the row with its version, and only write if the version hasn't changed. If zero rows were updated, someone got there first, so you start again.
Most ORMs support this out of the box, and it's great when conflicts are rare, like two admins editing the same product description. It is not great for one hot row. In the 1,000-item sale, Postgres needed about 4,600 retries. MySQL needed about 48,800, and its throughput dropped to roughly 24 attempts per second, the slowest result in the whole test.
4. SERIALIZABLE plus retries
Keep the original read-then-write code, run it at SERIALIZABLE, and retry when the database rejects a transaction:
for attempt := 0; attempt < maxRetries; attempt++ { err := buyOnce(ctx, sql.LevelSerializable) if !isRetryable(err) { // SQLSTATE 40001/40P01 on Postgres, error 1213 on MySQL return err } } Both databases then refuse to oversell, but in different ways. Postgres detects the conflict and fails the transaction with a serialization error. MySQL quietly turns every plain SELECT into a shared lock, so two buyers both hold a read lock, both try to upgrade it to write, and InnoDB kills one of them as a deadlock. I checked InnoDB's own deadlock counter after a run, and it matched my retry count exactly.
It's correct, and it's the most general option because it protects every query in the transaction, not just the one you remembered. On a single hot row, though, it's expensive: about 30,000 retries on Postgres and 48,000 deadlocks on MySQL for 3,000 purchase attempts.
How fast is each one?
Same setup as the 1,000-item sale: 3,000 attempts, 50 buyers, one product. I ran it twice and show the range of both runs.
| Approach | Oversold | Postgres attempts/s | MySQL attempts/s | Retries (PG / MySQL) |
|---|---|---|---|---|
| Read, check, write (default isolation) | 2,000 | 128 to 160 | 84 to 85 | 0 / 0 |
Conditional UPDATE | 0 | 353 to 443 | 169 to 198 | 0 / 0 |
SELECT ... FOR UPDATE | 0 | 214 to 223 | 136 to 191 | 0 / 0 |
| Version column + retry | 0 | 202 to 221 | 23 to 25 | ~4,600 / ~48,800 |
SERIALIZABLE + retry | 0 | 89 to 90 | 33 to 36 | ~30,000 / ~48,000 |
A few honest caveats:
- This ran on my laptop, with Docker Desktop on Windows and default database settings. Every commit waits for a disk flush, which is why the absolute numbers are low. Compare the rows with each other , not with your production database.
- It's one very hot row on purpose. With thousands of different products and buyers spread across them, conflicts are rare and the differences shrink a lot.
- The broken version isn't even fast. It was slower than the conditional
UPDATEon both databases, because it does an extra round trip and still has to queue for the row lock on itsUPDATE.
So which one should you use?
Here's how I'd pick now:
- Decrementing a counter (stock, seats, credits, coupon uses)? Conditional
UPDATE. It was the fastest and the simplest in every run. - Need to check several things before deciding?
SELECT ... FOR UPDATE, and keep that transaction short. - Users editing records that rarely collide? Version column. That's what it's built for.
- Complex transactions where you can't list every risky read?
SERIALIZABLEwith a retry loop, and make sure the retried work is safe to repeat.
And whatever you pick, add CHECK (stock >= 0) anyway. It wouldn't have caught the original bug, but it will catch the next person who writes stock = stock - 1 without the WHERE stock > 0.
If a single product is getting tens of thousands of purchases per second, no amount of row locking will keep up, and that's when people move the counter into something like Redis with an atomic decrement in front of the database. I wrote about building exactly that kind of atomic counter in Go in my previous article on distributed rate limiting. It's the same bug in a different place.
What I learned
- A transaction is not a lock. Wrapping read-check-write in
BEGINandCOMMITmade it feel safe, and on the default settings of both databases it protected nothing. - The same isolation level name means different things.
REPEATABLE READstopped the oversell on Postgres and did nothing on MySQL. If your code relies on isolation behaviour, test it on the database you actually run. - Stricter isolation moves the problem. Without retries, Postgres went from overselling to selling fewer than 100 of 1,000 items.
- Push the decision into the write. The safest version was also the shortest: let the
WHEREclause do the check at the moment the row is locked. - Concurrency bugs need concurrent tests. None of this shows up with one request at a time. Fifty goroutines and a closed channel found it in under a second.
The full experiment is about 300 lines of Go with Postgres and MySQL in Docker, so you can run it yourself and try other isolation levels: github.com/Rimaz17/last-item-race
If you've hit this in production, I'd love to hear how you found it. Mine was found by a test I wrote on purpose, which is the cheap way to find it.



