Tiếng Việt · English
Two orders fighting over the last ingredients
The kitchen has exactly 2 portions of pizza dough left. Two guests order at the same time, 2 pizzas each, and both orders reach the kitchen
at almost the same moment. Only one order can be accepted; the other must report out of stock. It sounds obvious, but if you write the code
the most natural way, both orders get accepted and the stock goes negative. This article is about why, and how dine's kitchen
went from a single UPDATE to a lock on Aerospike.
The most natural approach, and where it goes wrong
The approach everyone thinks of first: read the stock, and if there is enough, subtract.
read stock → 2 left, need 2, enough → write stock = 2 − 2
With one order it is always right. But when two orders run at once, their steps can interleave:
The gap between "check" and "act" is the root of this bug, and it only shows up when several orders run at once. Test it on its own and you will never see it. (The idempotency article runs into exactly the same kind of bug, with two jobs both asking "has this been charged yet?".)
Layer 1: let the database check and subtract together
The fix is to stop splitting "check" and "subtract" into two steps, and merge them into a single statement:
take 2 portions of dough, only if stock ≥ 2
In MySQL, that is an UPDATE with the condition quantity >= 2 in its WHERE clause.
The database guarantees that two statements modifying the same row do not interleave: the later one waits for the earlier one to finish,
then checks the condition against the latest number. Order A subtracts, leaving 0. When order B's turn comes, the condition "at least 2 left"
no longer holds, the statement changes no rows, and the kitchen knows right away it is out of stock.
This layer is correct on its own. Whatever else goes wrong, the stock never goes negative. The rest of the article is about running smoothly when it is busy, not about right or wrong.
An order with several items: all or nothing
An order can have up to 8 different items. The kitchen takes them one by one, and it may manage items 1 and 2, then find item 3 short. At that point items 1 and 2 must be given back; the order cannot be left half-taken.
The kitchen uses a feature the database already has, SAVEPOINT: mark a point before starting to subtract,
and on a short item, go back to exactly that point. Every subtraction after the mark is undone, as if it never happened.
No hand-written loop adding things back. The order is recorded as rejected, the kitchen reports "failed: out of stock"
to order, and the order follows the normal cancellation path.
Layer 2: why a lock is still needed
Layer 1 is already correct, but when many orders compete for one item, every late order still has to open a transaction, go into the database, queue on the same row, and only then find out it lost. The database is the busiest part of the system; making it carry the queue as well is not great. A lock placed before the database lets orders learn early that they must wait, without touching the database.
Where the lock should live depends on how the kitchen's code runs. One step at a time:
Code running on one thread: no lock needed
If the kitchen has only one process, and that process handles messages one at a time, finishing one order before starting the next, then two orders never run at the same time. There is nothing to fight over, and no lock is needed. Simple, but slow: one order at a time, and each order waits for the previous one to finish completely.
Running many goroutines: sync.Mutex is enough
To go faster, let several goroutines process several messages at once. Now two goroutines can hold two orders that both need
pizza dough, and the story from the top of the article comes back. In Go, the simplest way to stop it is an in-memory lock,
sync.Mutex, one per item: whichever goroutine holds the lock for that item, the others must wait.
This works because all the goroutines live in the same process, see the same memory, and therefore see the same lock. Fastest, cheapest, no extra system needed.
Running many nodes: each mutex only locks its own house
Then comes the day you run the kitchen on two nodes (two machines, or two containers), to handle more orders, and so that if one node dies
the other is still there. Each node is a separate process with its own memory, so it has its own sync.Mutex.
Order A lands on node 1, order B lands on node 2: each locks its own mutex, finds it free, and both carry on as if there were no lock at all.
The lock now has to live in a shared place that every node can see. That is called a distributed lock.
That shared place: MySQL or Aerospike?
Every node is already connected to MySQL, so using it as the shared lock is the first thought, and it works: lock the row with
SELECT ... FOR UPDATE before subtracting, or use a named lock with GET_LOCK(). The difference is
where the queue lives:
| Locking with MySQL | Locking with Aerospike | |
|---|---|---|
| Where the queue lives | Right inside the main database: every waiting order holds a connection and an open transaction | In a separate, very fast store, apart from the main database |
| What the main database carries | The main work plus holding locks and managing the queue | Only the main work |
| When the lock holder dies | Released immediately when the connection or transaction closes. This is a real advantage | Waits for the lock to expire (5 seconds at dine) |
| Extra system to operate | No | Yes |
With few orders, locking with MySQL is a reasonable choice, even the simpler one. When it is busy, the database itself becomes the bottleneck: connections are taken up by orders that are just sitting and waiting. dine's kitchen chose to move the queue out of the database.
Keep the distinction clear: the UPDATE ... WHERE quantity >= ? statement in layer 1 also locks the row in MySQL, but only for
the few milliseconds of one statement, so it stays cheap. What is expensive is using MySQL to hold a lock while waiting,
across many statements.
Aerospike or Redis?
Honestly: either works. Redis is the most popular choice for distributed locks, with plenty of docs and examples:
a single SET key value NX PX 5000 does it, meaning "create only if it does not exist, delete automatically after 5 seconds".
Aerospike does exactly the same thing in its own way. I chose Aerospike simply because I am familiar with it, not because it beats Redis
at this job.
What matters is not the tool's name but the idea behind it: a shared place, a "create only if nobody has yet" operation, and an automatic expiry. Swap Aerospike for Redis or the other way round, and the rest of this article stays exactly the same.
How the Aerospike lock works
Very simply. "Taking the lock" means: create a record named after the item, only if nobody has created it yet. If the create succeeds, you have the lock. If someone already created it, the item is busy. When done, delete the record to release the lock.
Three small but important details
- The lock expires by itself after 5 seconds. If the kitchen dies while holding a lock, nobody deletes that record. Without an expiry, the item would stay locked forever and no order could ever get it again. With a 5-second expiry, Aerospike cleans up by itself, far more than the few tens of milliseconds an order actually needs. In return, if an order for some reason takes longer than 5 seconds, the lock expires while it is still working and another order gets the lock: both think they hold it. That is the shared weakness of every lock with an expiry, and the reason layer 1 still has to be there.
- Always lock in the same order. Order A needs dough then cheese, order B needs cheese then dough. If A locks the dough and B locks the cheese, each waits for the item the other holds, and waits forever. This is called a deadlock. The simple cure: every order sorts its item list by ID before locking, so nobody holds a "later" item while waiting for an "earlier" one.
- Remove duplicate items before locking. An order may list the same item on two lines. If you lock line by line, the second lock attempt finds that item "busy", and the holder is the order itself. The order blocks itself. Merging duplicates first makes the problem go away.
What if the lock cannot be taken
The kitchen retries on the spot, up to 5 times, 100 milliseconds apart. In most cases, the order holding the lock finishes within a few tens of milliseconds, so the second or third attempt succeeds. If it still fails after half a second, the kitchen returns an error so the message-receiving part retries later, more slowly and less often (the article Where broken messages go describes that path).
Two situations sound alike but must be handled in opposite ways:
| Lock not available | Out of stock | |
|---|---|---|
| Meaning | Another order is using this item | There really is not enough stock |
| Does retrying help | Yes, the lock will be released shortly | No, however often you retry it is still short |
| What the kitchen does | Retries, does not answer order yet | Answers "failed" right away, the order is cancelled |
Mixing these two up is a very common bug: cancelling orders just because it is busy, or endlessly retrying an order that will never have enough stock.
And restocking?
When an item runs low, the kitchen restocks it automatically, like ordering supplies in real life. Adding to stock uses the same approach as layer 1: a single statement that adds to the latest number, with a ceiling so the stock does not grow forever. Since a single statement is already safe, restocking needs no lock of its own.
In short: what actually keeps the stock from going negative is layer 1, one statement that checks and subtracts together.
The lock in layer 2 helps orders learn early that they must wait, reducing crowding in the database when it is busy. One thread needs no lock yet,
many goroutines need sync.Mutex, many nodes need a lock in a shared place, and Aerospike or Redis both do the job.
If your system can only have one layer, choose layer 1: it is correct without any extra system.
See it for yourself
- Kitchen Stock for each item, warning thresholds, and the stock log per order, including automatic restocks.
- Failure after others finished When the order is cancelled, the kitchen returns the ingredients to stock, using the same lock-and-subtract approach as above.
Spotted a mistake, or have a question? Write to [email protected].
dine is a personal project about distributed systems, written in Go: orchestrated sagas, transactional outbox, Kafka. More articles.