The campaign has started and the featured product has one unit left. In the same second, two customers press "Buy now". Both screens said "in stock", both orders were confirmed, and the warehouse holds a single item. This bug rarely shows up in a test environment and appears in force on campaign day. Concurrency control and locking are the techniques that stop two operations changing the same record at the same time from overwriting each other's result; double selling is its best-known symptom.
In this guide we explain how a race condition arises, how pessimistic locking, optimistic locking and conditional updates differ, how to estimate the collision probability, and how to deal with deadlocks and hot records, cart reservations, testing, monitoring and the payback calculation. Every number here is representative; none is a measurement of a real system or an industry average.
What Is a Concurrency Problem and How Does Double Selling Happen?
A concurrency problem occurs when two operations read the same data in the same window and write without knowing about each other. It is called a race condition, and the outcome depends on which operation finishes first.
In the stock example, operation A reads the stock (1) and operation B reads it too (1). Both decide "enough", and both write 0. Two orders are confirmed, the stock shows 0, yet only one unit exists. The system cannot notice, because no single step was wrong on its own.
The same mechanism affects every record that is read and then changed: a dealer's credit limit, a campaign quota, the number of appointment slots, a single-use discount code. On a balance it is called a lost update. A representative example: the balance is ₺1,000, operation A will deduct ₺300 and operation B ₺200. Both read 1,000; A writes 700 and B writes 800. The correct result is 1,000 − 300 − 200 = ₺500, but the record ends at ₺800. The ACID guarantee we described in our database selection guide protects a single transaction; making two transactions aware of each other takes a separate concurrency design.
| Problem | What happens | Example |
|---|---|---|
| Double selling | The check passes, both write | Stock 1, two orders confirmed |
| Lost update | The last writer overwrites the first | Balance 1,000, ends at 800 after two debits |
| Deadlock | Two operations wait for each other | One holds item 1, the other holds item 2 |
How Do You Calculate the Collision Probability?
In a simple model the collision risk depends on the request rate on one record multiplied by the time between reading and writing. Average concurrent operations = λ × t, where λ is requests per second on the record and t is the read-to-write window.
If requests arrive randomly (a Poisson assumption), the probability that at least one other request arrives while an operation is open is 1 − e−λt. Let the window be 80 ms (0.08 s).
| Record type | λ (requests/s) | λ × t | Collision probability |
|---|---|---|---|
| Ordinary item | 0.01 | 0.0008 | about 0.08% |
| Campaign item | 12 | 0.96 | 1 − e−0.96 ≈ 61.7% |
The same code collides about 772 times more often on the campaign item (61.7 ÷ 0.08). The bug appears only under load and only on hot records, so "we never saw it in testing" is no assurance. For capacity thinking, see our software scalability guide.
What Is the Difference Between Pessimistic Locking, Optimistic Locking and a Conditional Update?
Pessimistic locking assumes a collision will happen and holds the record in advance; optimistic locking assumes it will not and checks at write time; a conditional update collapses the check and the write into a single command.
| Topic | Pessimistic lock | Optimistic lock | Conditional update |
|---|---|---|---|
| Logic | Lock the row before reading | Write with a version number, reject if changed | Deduct if the condition holds, else 0 rows |
| Waiting | Others queue up | No waiting; the loser retries | No waiting; rejected |
| Best fit | Frequent collisions, long operations | Rare collisions, read-heavy | Single-field counters and balances |
| Risk | Deadlock, long queues | Retry storms on hot records | Does not span several records |
The simplest way to decrement stock is a conditional update: "stock = stock − quantity, but only if stock ≥ quantity". The command returns the number of affected rows: 1 means the sale was taken, 0 means there was not enough stock and the order is rejected. With optimistic locking, a version column is added to the record; the write says "if the version is still 7, write and set it to 8", and if zero rows are affected someone slipped in and the operation re-reads from the start. Whichever you pick, the rule is the same: do the check in the database, as close to the write as possible.
How Should Retries Be Tuned for Optimistic Locking?
If the collision probability per attempt is p and attempts are independent, the expected number of attempts is 1 ÷ (1 − p), and the probability of failing all three attempts is p³.
| Collision probability p | Expected attempts | Fails all 3 | Comment |
|---|---|---|---|
| 0.08% | 1.0008 | negligible | Optimistic locking is ideal |
| 20% | 1.25 | 0.8% | Acceptable |
| 60% | 2.5 | 21.6% | One request in five fails |
| 90% | 10.0 | 72.9% | Not suitable |
For the campaign item p ≈ 61.7%, so 0.617³ ≈ 23.5%: one customer in four sees an error. Optimistic locking alone is not enough on a hot record, and the failed requests return to the same record and add load. For the wait, use exponential backoff with random jitter: 20 ms, 40 ms, 80 ms. Across three attempts the total added wait is at most 20 + 40 = 60 ms. Without jitter, colliding requests come back at the same moment and collide again.
Why Does Lock Duration Matter So Much?
With pessimistic locking the maximum rate per record is 1 ÷ lock time, so a longer lock builds a longer queue.
If the lock is held for 80 ms (imagine an external service call inside it), the record passes at most 1 ÷ 0.08 = 12.5 operations per second. If the campaign item receives 12 requests per second, utilization is 12 ÷ 12.5 = 96%. In a simple single-server queue model (M/M/1) the average total time is 1 ÷ (12.5 − 12) = 2 s, and the wait in the queue is 0.96 ÷ 0.5 = 1.92 s.
If the same update becomes a conditional command taking 4 ms, the rate limit is 250 operations per second, utilization is 12 ÷ 250 = 4.8%, and the average total time is about 4.2 ms. The practical rule: while a lock is open, do not call external services, send e-mails or wait for payments; do only the check and the write.
How Do You Prevent a Deadlock?
A deadlock is two operations waiting for locks the other holds; if one locks item 1 and then item 2 while the other does the reverse, both wait, and the database usually rolls one back.
If lock order is left free, the chance that two operations lock two items in different orders is 50%. With three items there are 3! = 6 orderings, so the chance of different orders rises to 1 − 1/6 ≈ 83.3%. The fix is a single rule: always acquire locks in the same order, for example by item ID from smallest to largest. If everyone follows the same order, a wait chain cannot form a cycle. In addition, put an upper limit on lock waits, roll back when it expires, and retry once more if the operation has no side effects.
How Do You Overcome a Single Hot Record Bottleneck?
If all requests target one row, the queue forms on that row. A "last 3 items" offer or a bulk campaign stock is the typical case. The answer is to split the counter so that lock areas are separate.
Split a 300-unit campaign stock into 10 parts of 30 units, and send each request to a random part. 12 requests/s becomes 1.2 requests/s per part. With an 80 ms lock, utilization is 1.2 ÷ 12.5 = 9.6% and the wait in the queue is about 8.5 ms; compare that with 1.92 s on a single row.
Splitting has two costs. When one part runs out, the others may still hold stock; a request must try the other parts in turn, or the customer wrongly sees "sold out". And splitting is meaningless for the last few units, since 3 units cannot be divided into 10 parts: once stock falls below a threshold, merge the parts into one record and switch back to a conditional update.
How Do You Reserve Stock in the Cart?
A reservation holds the product for a customer for a set time before purchase; when time runs out the unit is released, so abandoned carts do not keep stock locked.
A representative example: a 300-unit campaign, 30 add-to-cart events per minute. Customers who pay (40%) take 6 minutes on average, and those who abandon (60%) hold the reservation until the end of the hold time. By Little's law, units held at the same time = arrival rate × average hold time.
| Hold time | Average hold | Held at once | Share of 300 stock |
|---|---|---|---|
| 15 min | 0.4 × 6 + 0.6 × 15 = 11.4 min | 30 × 11.4 = 342 | 114% |
| 10 min | 0.4 × 6 + 0.6 × 10 = 8.4 min | 252 | 84% |
| 8 min | 0.4 × 6 + 0.6 × 8 = 7.2 min | 216 | 72% |
With a 15-minute hold, reservations exceed stock and the product shows "sold out" before it is sold. A shorter hold frees stock but loses customers who cannot finish paying; choose the time by looking at the payment-duration distribution. The "reserve" and "release" steps should also use conditional updates; add a cleanup job that releases expired reservations and a check against payments that arrive after expiry. The stock-allocation rules in our order management article continue this logic.
What Do You Do in a Distributed Setup and With Repeated Requests?
When several servers change the same data, an in-memory lock does not help, because each server sees only its own lock. The lock or the condition must live where all of them look, which is the database. The alternative is a queue that orders operations on the same resource through a single writer (the ordering idea in our message queue guide).
Duplicate operations also come from repeated requests: a user double-clicks, or a client resends after a network error. The fix is to give each operation a retry-protection key and not treat a second request with the same key as a new operation; details are in our webhook guide. Locking prevents different requests from colliding, while the key prevents the same request from repeating; one does not replace the other.
How Do You Test for a Race Condition?
A race test sends many requests to the same record at once and checks the invariant: units sold cannot exceed starting stock, and stock cannot fall below zero.
A representative scenario: stock 50, 200 simultaneous requests, each asking for 1 unit. The expected result is exactly 50 successful orders, 150 rejections and final stock 0. If successes exceed 50 or stock is negative, the solution is wrong. The bug does not show in every run: if the probability of catching it in one run is q = 5%, the probability of catching it at least once in k runs is 1 − 0.95k.
| Number of runs | Probability of catching the bug |
|---|---|
| 10 | 40.1% |
| 50 | 92.3% |
| 100 | 99.4% |
A single green run is no guarantee; run the test hundreds of times and automatically in the release pipeline. For load-test thinking, see our performance testing guide. Do not use real customer data in test environments; for personal data obligations such as KVKK (Turkey's personal data protection law), consult your legal counsel.
How Do You Monitor Double Selling in Production?
The aim is to see within minutes that the invariant has been broken. The simplest alarm is negative stock: if stock falls below zero there is no tolerance.
- Negative or oversold stock: Every record where stock < 0 or units sold > available stock.
- Reconciliation: Starting stock + receipts − issues is compared with current stock daily; the difference must be zero.
- Collision rate: Retries ÷ total requests. A sustained rise above 5% shows the record is hot and the method should change.
- Lock waits and rolled-back operations: p95 wait and the daily number of deadlocks.
For alerting principles, see our software monitoring guide.
How Do You Calculate the Payback of This Design?
Payback compares the cost of oversells prevented with the engineering effort. A representative example: 40 oversold orders a month, each costing ₺250 to cancel (customer contact ₺75, compensation voucher ₺100, return and operations ₺75).
| Item | Calculation | Amount |
|---|---|---|
| Monthly loss | 40 × ₺250 | ₺10,000 |
| Prevented (90%) | 36 × ₺250 | ₺9,000 |
| Monthly upkeep and monitoring | Assumption | ₺1,000 |
| Monthly net gain | 9,000 − 1,000 | ₺8,000 |
| Investment | 6 person-days × ₺9,000 | ₺54,000 |
| Payback | 54,000 ÷ 8,000 | 6.75 months |
With only 10 oversells a month, the gain is 10 × 250 × 0.90 = ₺2,250, the net is 2,250 − 1,000 = ₺1,250, and payback stretches to 54,000 ÷ 1,250 = 43.2 months. At low volume the investment is not economic; still, wherever money is directly affected, such as balances, quotas and payments, a conditional update is cheap enough that it should be applied anyway.
We recommend reading: How to choose a database: consistency, indexes and cost
We recommend reading: How to Design a Loyalty Points Program: Earn Rules, Ledger, Expiry and Liability Guide
We recommend reading: What Is Event-Driven Architecture? Event Types, Outbox, Replay and Payback Guide
We recommend reading: How to Design an Offline-First App: Local Data, Sync, Conflict Resolution and Payback Guide
We recommend reading: How to Prepare an E-Commerce Store for Peak Campaign Season: Demand, Stock, Capacity and Live Control Guide
We recommend reading: What Is the Saga Pattern and Distributed Transactions? Compensation, Step Order and Failure Math Guide
Reliable Business Applications with İnovabil
At İnovabil our focus is building software from scratch for your company: custom software, ERP, CRM, e-commerce, web, mobile and integration. For records that many users change at once, such as stock, orders, balances and quotas, we suggest writing the concurrency expectation into requirements analysis as an invariant and a peak-load scenario; settling the testing and monitoring expectation at the same stage is cheaper than fixing it later.
We built CRM, purchasing and mobile for Avcılar İnşaat; a purchasing system for İZBAN; logistics and shipment planning plus wholesale order management for Karyak; and warehouse management plus a complaint and support management system for Sleepy. The calculations in this article are representative and are not an İnovabil performance or accuracy commitment. Briefly tell us which records change heavily in your business, and we will write it up together at the requirements stage.
We recommend reading: Our software development process: from analysis to release, step by step
Frequently Asked Questions
Why does double selling happen and how is it prevented?
It happens because two operations read the same stock at the same time and both decide "enough". It is prevented by doing check and write as one conditional update in the database, or by rejecting the loser of a collision through a version check.
Is pessimistic or optimistic locking better?
It depends on collisions. Optimistic locking is light when collisions are rare; with frequent collisions and long operations, use pessimistic locking or a conditional update. In the example, expected attempts are 1.0008 at p = 0.08% and 2.5 at 60%.
How do you prevent a deadlock?
Acquire locks in the same order every time, keep lock time short and set a timeout on waits. With a three-item order and free ordering, the chance of different orders rises to 83.3%.
How long should stock be held in the cart?
It depends on the payment-duration distribution. In the example a 15-minute hold gives 114% load, 10 minutes 84% and 8 minutes 72%. A hold that is too short loses customers who cannot finish paying.
How do you test for a race condition?
Send many parallel requests to the same record and check the invariant: with stock 50 and 200 requests, expect exactly 50 successes and final stock 0. Run it hundreds of times; with a 5% catch probability, 100 runs catch the bug 99.4% of the time.