Menu

1 / 2

Two Users Bought the Last Item. Your Database Allowed It.

DEV Community: mysql·Rimaz Saththar·4 days ago
#n2TGqP3o
#devtomysql#devto#dev#stock#mysql
Long article (2511 words) — no AI summary yet.
Reading 0:00
15s threshold

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 READ stopped it on Postgres (49 buyers got an error instead). On MySQL it changed nothing, because REPEATABLE READ is 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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.