Pessimistic row locking: how an online store with one-of-a-kind items handles a race condition
A second-hand online store sells items that exist only once. Two customers must not buy the same item at the same time - the solution isn't in application logic but in the database.
A classic online store with stock handles concurrent orders simply - it decreases the number of items in stock, and if it hits zero, the next order fails. For a second-hand store with one-of-a-kind items the situation is different: each item exists exactly once. Two customers who put it in their cart in the same second create a race condition that an ordinary "is it in stock?" check won't reliably catch.
Why a check in the application isn't enough
The typical (flawed) approach: the application asks the database "is the item available?", gets the answer "yes", and then reserves it. But between the query and the reservation there is a time window - if a second customer with the same query fits into it, both get the answer "yes" and both think they have the item. That window may be only a few milliseconds, but with enough traffic it will happen.
The solution at the database level
Fotobazoš.cz solves this exactly where it should be solved - in a database transaction with a row lock (`SELECT … FOR UPDATE`). Once one customer locks the item, the second query for the same row waits until the first transaction is closed. It isn't a safeguard in application logic that can be bypassed by a wrong order of operations - it's a guarantee at the level of the database engine.
Why it matters for the business
A sold item that doesn't actually exist means a complaint, lost trust and manually dealing with two angry customers instead of one satisfied one. For a business built on one-of-a-kind items, this certainty isn't an extra technical detail - it's the basic condition for the model to work at all.
Case study
Fotobazoš.cz
View case study →