Live demo D1 (atomic) Pages Functions In the Frontier case file →

The Hoarder

On a limited drop, bots pile in and oversell the inventory, leaving real customers with cancelled orders. A single atomic write in Cloudflare D1 guards the count, so it can never go below zero.

The pain

Limited drops invite a buying frenzy, and a read-modify-write race can oversell stock you do not have.

The fix

Guard the count with one atomic D1 UPDATE (qty > 0), so concurrent buyers can never push it below zero.

So what

No oversells, no refunds or angry customers, and a fair drop that holds up under bot-driven load.

Try it

Limited drop: 10 in stock.

Buy one at a time, or send a bot stampede of 15 simultaneous buys. The count never goes below zero, and the extra buys come back sold out. No overselling.

10 in stock

Real Cloudflare D1: UPDATE stock SET qty = qty - 1 WHERE qty > 0 is one atomic statement, so concurrent buyers can never race it below zero.

How it works

A single atomic D1 write guards the stock count, so concurrent buyers can never race it below zero.

🛒
Buyers + bots
all at once
buy
🗄️
D1 atomic UPDATE
qty > 0 guard
one statement
Fair result
no oversell
Stock left → bought
Zero left → sold out

Add it to your site

1 SQL statement · no race
D1: decrement only if stock remains
const { meta } = await env.DB.prepare(
  'UPDATE stock SET qty = qty - 1 WHERE id = ?1 AND qty > 0'
).bind(productId).run();

const bought = meta.changes === 1;   // 0 changes = sold out, no oversell
01
Keep the count in one D1 row
02
Decrement with a single guarded UPDATE (qty > 0)
03
Use rows-changed to tell "bought" from "sold out"
Works with:D1Pages FunctionsAny SQL backend