dine. a kitchen run by sagas Book a table
Log in with Google (coming soon)

Articles

Tiếng Việt · English

Two orders fighting over the last ingredients

October 14, 2026 · about 9 min read

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:

Order A reads 2 in stock; order B reads 2 in stock; order A takes 2, leaving 0; order B takes 2 based on a stale number, and the stock goes to minus 2. order A order B stock read: 2 left read: 2 left enough, take 2 enough (stale)take 2 2 2 0 −2 time
Order B decides based on a number that is already stale: when it read, there really were 2 left, but by the time it subtracts, order A has taken them.

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.

Three ways to run: one thread handles orders one by one, no lock needed; many goroutines in one process share a single sync.Mutex; many nodes each have their own mutex, which cannot block each other, so the lock must live in a shared place, Aerospike. 1 thread 1 process order A order B one order at a time, nobody competes no lock needed, but slow Many goroutines 1 process, shared memory order A order B sync.Mutex one lock in memory, everyone sees it: enough Many nodes node 1 order A own mutex node 2 order B own mutex ✕ Aerospikeshared lock mutexes can't see each other, the lock must live somewhere shared
A lock only stops those who can see it. In one process, an in-memory lock is enough; with many nodes, the lock has to move out, to a place every node can see.

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 MySQLLocking with Aerospike
Where the queue livesRight inside the main database: every waiting order holds a connection and an open transactionIn a separate, very fast store, apart from the main database
What the main database carriesThe main work plus holding locks and managing the queueOnly the main work
When the lock holder diesReleased immediately when the connection or transaction closes. This is a real advantageWaits for the lock to expire (5 seconds at dine)
Extra system to operateNoYes

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

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 availableOut of stock
MeaningAnother order is using this itemThere really is not enough stock
Does retrying helpYes, the lock will be released shortlyNo, however often you retry it is still short
What the kitchen doesRetries, does not answer order yetAnswers "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

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.