I ran 200 purchase attempts against 100 shirts. All 200 created orders, and the stock column still said 94.
The requests wrote decrements based on stale reads. The fix for one item was a conditional UPDATE.
1. The code that does this
The broken version reads stock, checks it and writes back a value calculated in the app:
def buy(conn):
stock = conn.execute("SELECT stock FROM product WHERE id = 0").fetchone()[0]
if stock > 0:
time.sleep(0.001) # shipping fee, coupon check, fraud score...
conn.execute("UPDATE product SET stock = %s WHERE id = 0", (stock - 1,))
conn.execute("INSERT INTO orders (product_id) VALUES (0)")
conn.commit()I ran 200 attempts with 40 threads:
FLASH SALE — 100 shirts in stock, 200 Buy clicks at once
1. read → check → write (the first version anyone writes)
sold 200 orders | stock shows 94 | OVERSOLD BY 100
0.20 secondsOverlapping requests passed the check and overwrote each other’s updates. That is how stock stayed positive after 200 orders.
2. One conditional UPDATE
Before reaching for a lock, look at why the bug exists: the app read a number, then computed a new value from it. Close that gap by letting the database do both in one statement:
def buy(conn):
n = conn.execute(
"UPDATE product SET stock = stock - 1 WHERE id = 0 AND stock > 0"
).rowcount # <- the check and the decrement, together
if n == 1:
conn.execute("INSERT INTO orders (product_id) VALUES (0)")
conn.commit() 2. one SQL statement: WHERE stock > 0
sold 100 orders | stock 0 | matches
0.22 secondsIt sold exactly 100. rowcount tells the caller whether the decrement happened.
PostgreSQL evaluates the stock predicate and updates the row together, so the stale value from an earlier read never enters the calculation. If your update fits in one statement, you need no lock at all.
3. When one statement is not enough
For a cart, reserve every item or roll the transaction back.
One way is to read and lock the rows with SELECT ... FOR UPDATE before updating them:
def checkout(conn, items):
for pid in items:
conn.execute("SELECT stock FROM product WHERE id = %s FOR UPDATE", (pid,))
time.sleep(0.002) # check stock, price the line, log...
for pid in items:
conn.execute("UPDATE product SET stock = stock - 1 WHERE id = %s", (pid,))
conn.execute("INSERT INTO orders (product_id) VALUES (%s)", (pid,))
conn.commit()I ran eight customers with overlapping carts:
CART OF 3 ITEMS — 8 customers checking out at once, 15 carts each
lock order | deadlocks | seconds | stock consistent
----------------------+------------+----------+-----------------
order in the cart | 220 | 132.30 | ✓4. Why it deadlocks, and the one-line fix
Cart A locks row 3 and waits for 7. Cart B locks row 7 and waits for 3. PostgreSQL aborts one transaction to break the cycle.
Lock the rows in the same order in both transactions:
for pid in sorted(items): # <- lock in a globally consistent order
conn.execute("SELECT stock FROM product WHERE id = %s FOR UPDATE", (pid,))lock order | deadlocks | seconds | stock consistent ----------------------+------------+----------+----------------- order in the cart | 220 | 132.30 | ✓ always sorted by id | 0 | 0.89 | ✓
Sorting eliminated deadlocks and cut checkout from 132.30 s to 0.89 s. Every code path that locks the same rows must use the same order. This only shows up under real concurrency with overlapping carts, which means on sale day.
5. When the transaction would span a gateway call
A payment gateway changes the choice. A row lock lasts only for the transaction, so holding it across the call also occupies a database connection.
I tested eight checkouts, four connections and 200 products to keep conflicts rare:
| Gateway takes | Strategy | orders/s | total s | retries |
|---|---|---|---|---|
| 50 ms | pessimistic | 67.6 | 1.42 | 0 |
| 50 ms | optimistic | 132.9 | 0.72 | 0 |
| 200 ms | pessimistic | 19.1 | 5.01 | 0 |
| 200 ms | optimistic | 37.8 | 2.54 | 0 |
| 500 ms | pessimistic | 7.9 | 12.22 | 0 |
| 500 ms | optimistic | 15.6 | 6.15 | 0 |
In this test, optimistic locking doubled throughput with zero retries. It released the connection before the gateway call, so all eight checkouts could be in flight:
# read the version, then RELEASE the connection
conn = pool.acquire()
stock, v = conn.execute("SELECT stock, version FROM product WHERE id = %s", (pid,)).fetchone()
pool.release(conn)
pay(gateway_ms) # holding nothing: no lock, no connection
# confirm, but only if nobody changed the row while we were away
conn = pool.acquire()
n = conn.execute(
"UPDATE product SET stock = %s, version = version + 1 "
"WHERE id = %s AND version = %s", # <- the entire optimistic mechanism
(stock - 1, pid, v),
).rowcount
pool.release(conn)
# n == 0 -> somebody else bought it first: re-read and try againIf the wait is a customer sitting on a payment page for two minutes, pessimistic locking stops being an option: no transaction can stay open that long per customer. Pick it for a gateway call and the symptom is connection pool exhaustion, which looks nothing like a locking problem during a sale.
6. What optimistic locking costs on a hot item
Then I tested the opposite case: 200 buyers competing for one product.
3. pessimistic: SELECT ... FOR UPDATE
sold 100 orders | stock 0 | matches
0.40 seconds
4. optimistic: version column + retry
sold 100 orders | stock 0 | matches
0.53 seconds | 2136 retriesBoth versions protected stock. The optimistic run placed 100 orders and discarded 2,136 attempts.
Pessimistic locking makes contenders wait and optimistic locking makes losers retry, so on a hot row the retries are the cost to measure.
7. One more option, on PostgreSQL
At Repeatable Read, PostgreSQL can detect a conflicting update without a version column:
conn.isolation_level = psycopg.IsolationLevel.REPEATABLE_READ T1 reads stock 100, T2 reads stock 100 T1 writes 99, COMMIT T2 writes -> SerializationFailure: could not serialize access due to concurrent update T2 retries: reads 99, writes 98, COMMIT
A conflict gives a serialization error instead of a zero row count. Retry the whole transaction, including its reads.
8. The lock only protects one layer
A purchase also crosses HTTP and queue boundaries:
browser -> load balancer -> N app servers -> queue -> M workers -> database
The same request can return as a client retry or a redelivered message, even if the database never sees two concurrent writers.
I kept the row lock and redelivered 25 of 100 messages:
QUEUE REDELIVERY — stock 200, 100 real orders, 8 workers
A. SELECT ... FOR UPDATE only (the row lock is entirely correct)
queue delivered 125 messages (25 redelivered)
-> created 125 order rows (should be 100)
-> stock left 75 (should be 100)
-> 25 shirts gone that nobody bought, 25 customers charged twiceBoth deliveries acquired the lock in turn and decremented stock. There was no race and no lost update; the same order ran twice. A row lock serializes access to a row. It does not make an operation happen once, and no isolation level does.
Carry one business key through every retry. Enforce it with a unique constraint:
CREATE TABLE orders (order_id text PRIMARY KEY, product_id int NOT NULL)
def handle(conn, order_id):
n = conn.execute(
"INSERT INTO orders (order_id, product_id) VALUES (%s, 0) "
"ON CONFLICT (order_id) DO NOTHING", # <- the guard, at the business key
(order_id,),
).rowcount
if n == 0:
conn.commit() # already processed: do NOT decrement again
return
conn.execute("UPDATE product SET stock = stock - 1 WHERE id = 0 AND stock > 0")
conn.commit() B. guard at the business key: INSERT ... ON CONFLICT DO NOTHING
queue delivered 125 messages (25 redelivered)
-> created 100 order rows correct
-> stock left 100 correctClaim the key before decrementing, in the same transaction. If the key already exists, skip the decrement.
The protection belongs where the failure happens:
| Layer | How one operation becomes two | What helps |
|---|---|---|
| Browser / client | double-click, retry after timeout | idempotency key generated by the client |
| LB → N app servers | retry lands on a different instance | the guard must be outside the process |
| Queue → M workers | at-least-once redelivery | dedup on the business key |
| Database | interleaved transactions | atomic statement, or a row lock |
9. The decision, in order
- Can the same request arrive twice? Through a retry, a queue or a double-click, it can. Put a unique business key on the write path first (§8).
- Does the update fit in one SQL statement? Then use
UPDATE ... WHERE stock > 0and no lock (§2). - Does the work wait on a gateway or a customer? Pessimistic would hold a connection the whole time. Use optimistic (§5).
- Several rows in one transaction?
FOR UPDATE, locked in one sorted order everywhere (§3, §4). - Everyone fighting over one row? Pessimistic. Waiting beat 2,136 discarded attempts (§6).
- On PostgreSQL, Repeatable Read can replace a hand-rolled version column (§7).
The usual rule, optimistic when conflicts are rare and pessimistic when they are common, answers only the last of these questions. The first two decide the outcome far more often, and neither is about how likely a collision is.
Tests ran on PostgreSQL 17.11 in Docker with psycopg 3.2.13. Timings are from this setup.