Build logPublished 21 min read
Inventory without a hot row: reserving stock in parallel on MySQL
onDatabase Internals postsSystem Design postsGo posts
Stock control for limited campaigns on MySQL with no row that every checkout queues on: one row per unit, FOR UPDATE SKIP LOCKED, a ledger off the hot path, 20-minute reservations and the test battery behind it.
In this post
- The ledger I was asked for, and why I argued against it
- What a hot row does to InnoDB when N checkouts arrive at once
- One row per unit: a pool, a ledger off the hot path and SKIP LOCKED
- Reserving an order: fast path, slow path, all or nothing
- Paying, paying late, giving back and adjusting from the dashboard
- The crons, the idle pool and the trade-offs
- The test battery: what it measured and the bug it found
On this page
- The ledger, and the shape of the traffic
- What a hot row does to InnoDB
- One row per unit
- Why SKIP LOCKED works here
- Why READ COMMITTED
- Reserving an order
- All or nothing per order
- Paying, paying late and giving back
- Reading the stock
- Adjusting from the dashboard
- The crons and the idle pool
- What it costs
- The test battery
- Where it stands
The platform I work on in Andorra sells experiences, hotel stays and shop products, and a few times a year it runs its own campaigns: roses and bouquets for Sant Jordi, gifts for Mother’s Day. Those products have a fixed stock, and the platform had no way to promise that the unit a customer is paying for is still there when the payment lands. I designed and built the inventory module that does that, from the first plan to the last hook into the order flow.
I was asked to build it as a ledger. I argued against it, and this post is the argument and what I built instead: why one row per product becomes a queue under a burst of simultaneous checkouts, how a pool of one row per unit lets checkouts of the same product run in parallel, how a reservation lives and dies, and the test battery that found a bug in my first version.
The core idea is not mine. It is what Shopify described this year in We replaced Redis with MySQL for inventory reservations—and it scaled, and the first line of my plan says so. What follows is how I adapted it to a much smaller platform, a legacy order flow and MySQL as the only moving part.
The ledger, and the shape of the traffic
The request was the textbook design: a stock balance per product, decremented by every purchase, with an entry written for every change.
It is simple, and for most of the platform’s products it would be fine. The objection was about the shape of the traffic, not its volume. The volume is small, and I want to be clear about it: a Sant Jordi campaign loads around 250 to 290 roses and about 50 bouquets, last year’s had 280 orders, and the first scope of the module is about twenty products. My concern was that a campaign’s orders do not arrive evenly. They bunch up when the sale opens, and all of them are for the same two or three products. A ledger turns that bunch into one row that every one of those checkouts has to lock, one after the other.
What a hot row does to InnoDB
Here is the ledger at the moment the sale opens, written the way it usually is:
-- inside the checkout's transactionUPDATE ledger SET stock = stock - ?WHERE product_id = ? AND stock >= ?;
INSERT INTO ledger_entries (product_id, order_id, quantity) VALUES (?, ?, ?);-- ... the rest of the checkout ...COMMIT;product_id is the primary key, so the UPDATE is a unique search on a unique index. In that case InnoDB locks only the index record it finds, not the gap before it, under REPEATABLE READ and READ COMMITTED alike. That sounds cheap, and for one checkout it is. With N checkouts it is the whole problem:
- The first checkout takes an exclusive record lock and keeps it until
COMMIT. Not until theUPDATEfinishes: until the transaction ends. Whatever the checkout does after the decrement, every query and every remote call, is time the row stays locked. - Every other checkout for that product waits on that one record. Under
READ COMMITTEDanUPDATEthat meets a locked row first does a semi-consistent read to check whether the row matches itsWHERE. Here the row always matches, so it waits all the same. The isolation level does not help. The checkouts are served strictly one at a time, and the best the product can do is one checkout per lock hold time, however big the server is. - Each waiter holds a connection and a server thread while it waits. The application’s connection pool is shared by every request, not just this product’s. When the burst is larger than the pool, requests that have nothing to do with roses queue behind the roses.
- Waiting has a limit, and it fails. After
innodb_lock_wait_timeout, 50 seconds by default, the waiter gets error 1205. By default InnoDB rolls back only the statement that timed out, not the transaction, so the caller has to notice and roll back the rest itself. - Deadlock detection gets slower. The MySQL manual notes that on high-concurrency systems deadlock detection can itself slow things down when many threads wait for the same lock, which is exactly this situation.
In this codebase there was a sharper version of point 1. The repository’s transaction helper is a unit of work that travels in the context: if a transaction is already open, a new one joins it, in REPEATABLE READ, the server’s default. A decrement written in the usual way would have joined the checkout’s transaction and kept the ledger row locked until the checkout committed, and that commit can come after the call to the payment gateway. The hot row would have been locked for as long as the slowest step of the checkout, once per customer, in sequence.
An append-only ledger, where stock is the sum of the entries, does not escape this. Two checkouts that read the sum at the same time both see enough stock, so something has to serialise them before they write, and that something is again one lock per product.
None of this is exotic. Shopify’s 2017 post on flash sales describes a single store’s sale taking down every store on its database shard, because of how many writes checkout made. I did not expect our traffic to look like theirs. I expected the same shape at a smaller size: a burst on one product, at one instant, on the database the whole platform shares.
One row per unit
The design I proposed instead keeps the ledger but takes it off the hot path. Stock lives in four tables:
- The ledger,
inventory_stock, has one row per managed product with the stock that has not been loaded into the pool yet. The row’s existence is the switch: a product with a row goes through the module, a product without one keeps the platform’s old stock handling.stockisINT UNSIGNED, so a bug that subtracts too much makes MySQL refuse the update instead of storing a negative stock. - The pool,
available_units, has one row per unit that can be reserved right now. The rows are interchangeable and their ids mean nothing. The pool is filled in batches of 50, only when it runs short, so it stays small. - Reservations,
reserved_quantities, have one row per order and product with the quantity held while the customer pays, and an expiry. A reservation is a quantity, not a list of units. Since the units are interchangeable, nothing needs to remember which rows were taken, and giving them back means inserting new ones. - Movements,
inventory_movements, record every change to the total stock: restocks, adjustments, sales and returns. Insert-only.
The invariant ties them together: ledger, plus pool rows, plus reserved quantities, equals the sum of the movements, for every product, at every moment. Moving units between the first three is not a movement, because the total does not change, so the hot path writes nothing to the history. Only a sale does, one row per product of the order, when the payment is confirmed.
Three details of the schema are about locks rather than data:
- The pool’s primary key is
(product_id, id). The reservation query filters by product and walks the clustered index directly, one lock per unit. With an auto-increment primary key and a secondary index on the product, each unit would cost a lock on the secondary entry and another on the clustered record. - There are no foreign keys. When a foreign key has to be checked, InnoDB sets shared record locks on the parent rows it looks at. Every insert into the pool or the reservations would take a shared lock on the ledger row, which is exactly the row the slow path locks for update.
- The ledger is its own table, not a column on
products. Legacy code updates whole product rows from values read earlier. A stock column there would be overwritten with stale values, and its row lock would compete with every one of those updates.
Why SKIP LOCKED works here
A checkout reserves with one statement:
SELECT id FROM available_unitsWHERE product_id = ? LIMIT ?FOR UPDATE SKIP LOCKED;FOR UPDATE locks the rows it returns. SKIP LOCKED makes it never wait for a row another transaction holds: those rows are left out of the result. Three checkouts for the same product each lock different units and none of them waits for another. Then each one deletes its units and inserts its own reservation row, keyed by its own order, so no two checkouts write the same row anywhere on this path.
The MySQL manual is clear about the price: a query that skips locked rows returns an inconsistent view of the data, so SKIP LOCKED is not suitable for general transactional work, but it fits queue-like tables where contention is the problem. The pool is a queue-like table: any free unit is as good as any other. The inconsistency has one consequence that shapes the code. Fewer rows than asked does not mean the product is sold out, only that this checkout could not see enough free units at that instant. So the code counts the rows, and a short read goes to the slow path instead of answering “out of stock”.
Why READ COMMITTED
Every transaction in the module runs in READ COMMITTED, and this is the decision that took longest to get right on paper.
Under REPEATABLE READ, a locking read with a condition that is not a unique match locks the range it scans, with next-key and gap locks, to stop other sessions inserting into it. The pool query is that kind of read: product_id = ? is a prefix of the primary key, not the whole key. When the pool is empty, the query finds nothing and locks the gap where the rows would go, up to the supremum, the pseudo-record past the last one. The insert that loads the next batch needs that gap, so it waits or ends in a deadlock. The pool would lock itself out exactly when it most needs refilling. Shopify hit the same thing and fixed it the same way.
Under READ COMMITTED, locking reads and deletes lock only the index records, not the gaps, so inserts next to locked rows go through. Gap locking remains only for foreign-key and duplicate-key checks. There are no foreign keys, and the only duplicate-key check that matters is the reservation’s primary key, which rejects an order reserving the same product twice. The price of READ COMMITTED is phantoms: a query run twice in one transaction can see new rows. The module relies on that. It is how the slow path sees a batch that another checkout loaded while it was waiting.
For the same reason the module never joins the caller’s transaction. Its adapter opens a new READ COMMITTED transaction straight from the connection pool every time, retries the whole transaction up to three times on a deadlock (1213) or a lock wait timeout (1205), and rolls it back explicitly before retrying, since a timeout alone would only undo the last statement. The consequence is that a reservation is not atomic with the creation of the order. When one succeeds and the other fails, the code compensates: it cancels the order, or releases the reservation.
Reserving an order
The checkout creates the order first, then reserves the units of its managed products, before the customer is sent to pay. The use case is short enough to show in full, simplified:
func (u *UseCase) reserveOne(ctx context.Context, orderID, productID string, quantity int) error { // Fast path: enough free units in the pool. The ledger row is not locked. reserved, err := u.repo.TryReserve(ctx, orderID, productID, quantity, u.config.ReservationTTL) if err != nil || reserved { return err } // Slow path: lock the ledger row, load a batch and reserve in one transaction. return u.repo.ReserveLoadingBatch(ctx, orderID, productID, quantity, u.config.BatchSize, u.config.ReservationTTL)}The slow path is where the ledger row is locked, and it is written so that the lock is short and useful:
SELECT stock FROM inventory_stock WHERE product_id = ? FOR UPDATE; -- the queue is here
SELECT id FROM available_units -- look againWHERE product_id = ? LIMIT ? FOR UPDATE SKIP LOCKED;
UPDATE inventory_stock SET stock = stock - ? WHERE product_id = ?; -- only if still shortINSERT INTO available_units (product_id) VALUES (?), (?), ...; -- the rest of the batch
DELETE FROM available_units WHERE product_id = ? AND id IN (...);INSERT INTO reserved_quantities (order_id, product_id, quantity, expires_at) VALUES (...);COMMIT;When ten checkouts find the pool empty at once, they all queue on the ledger row. The first loads a batch of 50 and takes its own units out of it before they ever reach the pool. The second gets the lock, looks at the pool again, finds the units the first one left and reserves them without touching the ledger. The ledger is decremented once per batch, not once per checkout, and a batch is never loaded twice for the same shortage.
That was not the first version. In the first one, loading the batch and reserving were separate transactions, serialised by a Redis lock. The battery showed that it lost: between the load and the reserve, other checkouts on the fast path took the freshly loaded units, and the checkout that had loaded them gave up after three tries with a false “busy” error, with stock available. The Redis lock had a second problem the tests could not show, because they used an in-memory lock: it retried for about five seconds and then failed the checkout. Loading and reserving in one transaction, with the ledger row as the lock, fixed both. Nobody can take a batch before the checkout that loaded it, and every wait now happens inside MySQL, where a cross wait is detected as a deadlock instead of hanging on a lock InnoDB cannot see.
All or nothing per order
An order can carry several managed products, roses and a bouquet in the same cart. Last Sant Jordi it happened in 8 of 280 orders, so it is rare, but an order that keeps half a cart is a bug either way.
Reserve takes the whole order. It adds up repeated products first, because a t-shirt in two sizes is two lines of one product and an order holds one reservation per product. Then it sorts the products by product_id, so two orders never lock the same products in opposite order, and reserves them one by one, each in its own short transaction. When one does not fit, it releases everything the order already holds and returns an error that names the product, so the checkout can tell the customer which one ran out.
It is all or nothing by compensation, not by one transaction around the whole cart. That is a choice with a cost. Each transaction only ever locks one product’s rows, but between reserving the roses and finding the bouquets gone, the roses are held by an order that is about to fail. The mixed-cart test saw it happen up to 50 times in one run: roses reserved and then given back because the bouquets had run out. Nothing was sold twice or lost, but for that moment another customer could have been told the roses were gone.
One exception: if the error is “this order already reserved this product”, which means a retried checkout, nothing is released, because that would drop the reservations the first attempt made.
Paying, paying late and giving back
Paid in time. The first thing the platform does when an order is marked as paid, before coupons, cashback or notifications, is to confirm the sale. That locks the order’s reservation rows, deletes them and inserts one SALE movement per product. The ledger is not touched, because those units left it when their batch was loaded. If there are no reservation rows, it checks whether a SALE already exists for the order: if so, it is a repeated webhook and nothing happens.
Payment fails, or the customer cancels in the app. The reservation is released: its rows are deleted and the quantity goes back to the pool as new rows, so the next customer can buy them at once. This is the only flow that goes from reservations back to the pool, against the module’s usual table order. It is safe because each order only ever touches its own reservation rows, and the pool rows it inserts are new.
Never paid. Reservations last 20 minutes, and the number is chosen against a cron that already existed: it cancels any order still unpaid after 15 minutes. With the reservation outliving the order, an unpaid order is always canceled first and gives its reservation back as it dies. Expiry is only a safety net, for a reservation left with no order to cancel.
Paid after the reservation expired. It can still happen, with a slow webhook. In that case the module tries to reserve the order’s items again and sell them. If the units are gone, bought by someone else in the meantime, it returns “out of stock”, and the order is canceled and refunded in full. A payment that lands on an order that was already canceled is refunded by the payment code that existed before, and the module never hears about it.
A paid order is canceled. Its units go back to the ledger, not the pool, with a RETURN movement. How much can be returned is computed from the movements: what the order sold minus what it already returned, under the ledger row lock so two returns of the same product cannot race. Calling it twice returns nothing the second time. The old stock code could return an order’s units twice; this cannot.
In the existing order flow, all of that hangs from a handful of places: the checkout reserves, the “paid” hook claims, and failed payments, app cancellations, manual cancellations and both cancellation crons give back. Editing the lines of an order that contains a managed product is refused. The customer cancels and orders again, which keeps the stock arithmetic in one place.
Reading the stock
The stock a customer or an operator sees is what can be sold right now: ledger plus free units in the pool. Units held by orders still paying are not counted, since they only come back if the payment fails. It is one plain query, with no locks, so it never waits for a checkout, and a unit that a checkout is taking at that very moment may still be counted for an instant.
There is one visible consequence, which I decided to accept rather than code around. If every remaining unit is held by someone who has not paid yet, the next customer is told the product is out of stock, even if some of those payments will fail and give units back a minute later. Adding a waiting list or a special error to the backend would have added more problems than it solves for a case this rare. The decision instead was for the front to show it as “temporarily out of stock”, so the customer knows it is worth trying again.
Adjusting from the dashboard
Operators manage stock with two mutations and a query, behind the same roles that can import products:
- Enable a product with its initial stock. That creates its ledger row and a
RESTOCKmovement with the user who did it, even for zero units, so the history always says who put the product under the module. - Adjust by a delta, with a mandatory reason. A positive delta is a
RESTOCKinto the ledger. A negative one is anADJUSTthat takes units from the ledger first and then from the free pool, withSKIP LOCKED. Units held by orders still paying are never taken: if the free stock is not enough, the adjustment fails and nothing changes. - Read the history, newest first, straight from the
(product_id, id)index.
The adjustment locks the ledger row first, like everything else that touches it, so it never runs at the same time as a batch load.
The crons and the idle pool
I added no new schedules. The module’s two jobs ride on crons the platform already ran.
The cron that cancels orders unpaid after 15 minutes now gives back each order it cancels, and when it finishes it runs ExpireReservations. That reads expired reservations without locks, only to know which orders to look at, and releases each one in its own transaction, so one failure does not stop the rest. A test with a short expiry and the cron running every second measured the real bound: units come back at most one expiry plus one cron interval after the reservation, because expires_at has second precision.
The daily cron that already restored product availability now also drains idle pools. A pool is idle when its newest row is more than 24 hours old: pool rows are only created when a batch is loaded or a reservation released, so the newest one says when the pool last moved. A campaign lasts a few days, three to five for Sant Jordi, so the units left in the pool go back to the ledger the day after it ends. The drain locks the ledger row first, the same order as a batch load, takes only free units with SKIP LOCKED, deletes them and adds their count back to the ledger. A checkout that is reserving at that moment keeps its units and sells normally; a test checks exactly that. The pool is meant to be a small, short-lived buffer. The ledger is where stock lives.
What it costs
The design is not free, and these are the costs I would list in a review:
- More moving parts. Four tables instead of one, two reserve paths, an invariant to maintain and two cron hooks. A ledger is one
UPDATE. - The ledger row is still locked, just rarely. Every checkout that finds the pool short queues on it while a batch is loaded, and each of them holds a connection while it waits. In the stress tests below, the mean lock wait in MySQL was 88 ms and the worst was 3 seconds. That is the cost the plan accepted: it only matters with thousands of simultaneous customers on one product.
- A short read is not proof of “sold out”. Near the end of the stock, a checkout can miss units that another checkout has locked and is about to give up. The window is narrow, and the targeted test to provoke it is still on the to-do list.
- The reservation is not atomic with the order. The module’s transactions are its own, so failures are compensated rather than rolled back together.
- At our volume a ledger would have survived an ordinary day. The argument for this design rests on the opening minute of a campaign and on how long the lock would have been held, not on traffic we do not have.
The test battery
Everything the module promises was tested against a real MySQL, and the tests refuse to run against anything but a local server over TCP. There are two suites. The live tests drop and recreate the tables from the migration and check one behaviour each. The integration tests run on a local database seeded with campaign products, create real orders and order lines, reserve before payment and confirm after a random webhook delay of 3 to 20 seconds, like customers typing their card at different speeds. Every scenario starts its goroutines behind a barrier, so the customers really hit the checkout at the same instant. And every scenario checks the same four things per product: no unit sold twice, no unit lost, no order rejected while its quantity was still available, and ledger plus pool plus reservations equal to the sum of the movements.
| Scenario | What it showed |
|---|---|
| 3 units and 5 orders, 281 units and 300 orders, 40 units and 60 orders with batches of 7 | Exactly the stock was accepted, the rest rejected as out of stock |
| Sale opening: 500 customers at once for 280 roses, over 40 runs | Always exactly the stock sold |
| 1,000, 10,000 and 100,000 customers at once over 5 products with 20 million units each | No overselling, no losses; at 100,000 the bottleneck was the test’s pool of 100 connections, not MySQL |
| Slow webhooks of 3 to 20 s and of 60 to 90 s | Each reservation kept its units until its payment arrived |
| Two waves of customers, half the payments failing | Released units were resold at once, nothing oversold or lost |
| Short expiry with the cron running every second, 40% of customers abandoning | Abandoned units were bought by a second wave, nothing left reserved |
| Mixed carts: 3% and 30% of orders with roses and a bouquet, 20% of payments declined, 13 runs | No order kept half a cart; canceled orders sold nothing, paid ones sold every line |
| Payment after the reservation expired | Units still there: sold, and a repeated webhook does not sell twice. Units gone: out of stock, nothing sold or held |
The battery earned its keep with the first version. With plenty of stock it rejected 2 of 10,000 customers with batches of 50, and 3 of 100,000 with batches of 1,000, with the “busy” error described above. That is what led to loading and reserving in one transaction. After that change and the all-or-nothing cart, I ran the whole battery again: the 500-customer opening ten times with the race detector, always exactly the 483 units in stock sold; 10,000 customers three times and 100,000 three times, every order paid, no failures. The 100,000 runs took between 65 and 195 seconds.
Two caveats about those numbers. They come from a laptop, a local MySQL and synthetic customers, and the large runs are hundreds of times the real campaign, chosen to look for races and lock pile-ups, not to predict production. And the race detector cannot go above about a thousand customers, because it supports at most 8,128 goroutines at once, so the larger runs are checked by their invariants only.
Two paths are not tested end to end yet: a payment declined by the real gateway, and one of the cancellation crons. Both call the same give-back function that the other paths exercise.
Where it stands
The module is merged into the development branch and wired into checkout, payment, cancellations, the crons and the dashboard, but no real product has been moved into it yet. Until a product gets a ledger row, the order flow behaves exactly as before.
What I would keep from this project: decide where the lock lives before deciding the schema. The ledger and the pool store the same number of units. What differs is which row every checkout has to touch, and for how long.
Materials used to write this article
- We replaced Redis with MySQL for inventory reservations—and it scaled — One row per unit in a bounded pool, SKIP LOCKED, READ COMMITTED against gap locks, inline replenishment under a lock
- Surviving Flashes of High-Write Traffic Using Scriptable Load Balancers (Part I) — A single flash sale's checkout writes took down every store on its database shard
- MySQL 8.0 Reference Manual: Locking Reads — FOR UPDATE, NOWAIT and SKIP LOCKED, and why SKIP LOCKED is meant for queue-like tables
- MySQL 8.0 Reference Manual: Transaction Isolation Levels — Which locks InnoDB takes under REPEATABLE READ and READ COMMITTED, gaps included
More of what I read in my software-engineering-guide.
Related posts
Build log
Building a distributed job scheduler without a queue
at and cron as a service, in Go: six services, MySQL as the queue, Cassandra for history. The decisions behind it, their trade-offs, and what load-testing it on an AWS-shaped bench found, including a bug of mine.
onSystem Design postsDatabase Internals postsGo posts
11 min read · Part 1 of Building a distributed job scheduler
Build log
Load-testing a distributed job scheduler on an AWS-shaped bench
An EKS and RDS lookalike on one PC, a cron platform with 30,000 jobs due at 09:00:00, and ten tests. Nothing was lost; the 300 jobs/s ceiling turned out to be an N+1 of mine.
onSystem Design postsDatabase Internals postsGo posts
11 min read · Part 3 of Building a distributed job scheduler
Build log
Distributed job scheduler: the design decisions in depth
Why the jobs table is the queue, why MySQL and not Postgres, why Cassandra only for history, and how leases, fencing tokens and idempotency keys keep at-least-once honest. With the alternatives I rejected and the SQL behind each decision.
onSystem Design postsDatabase Internals postsGo posts
12 min read · Part 2 of Building a distributed job scheduler