Ir al contenido
#0081
Sqlite

Decrement inventory atomically at checkout

Black Friday. Three hundred customers click "buy" on the last twelve units of the same product within four seconds. The classic race-condition disaster.

Your checkout handler does one thing: POST /api/v1/sqlite/kv/stock:sku-9911/decr?db=shop.db. The endpoint returns the new count. If it's negative, you know the unit was sold out before the request landed, you refund the cart, you say sorry. If it's zero or positive, the order succeeds.

Three hundred parallel POSTs become three hundred ordered decrements. Twelve return non-negative numbers; the rest get refunds. No transaction code, no row locks, no Lua script in Redis, no distributed lock service. The increment endpoint is the lock.

The hardest race condition in e-commerce becomes a one-line HTTP call against a SQLite KV.

Inventory wasn't a database problem. It was a counter problem all along.