A full e-commerce checkout design: requirements and peak estimates, atomic inventory reservation with expiry, the order saga across inventory, payment and orders with compensation, idempotent steps, hot-SKU contention in flash sales (sub-buckets, Redis counters, waiting room), multi-warehouse stock, and failure modes on Azure.
Never overselling comes down to one atomic, conditional reservation: UPDATE Stock SET Available = Available - @qty WHERE Sku = @sku AND Available >= @qty. Zero rows means sold out. I reserve at checkout, not at add-to-cart, with a reservation row and an expiry (say 10 minutes) and a sweeper that releases expired holds. The flow is a saga: reserve stock โ take payment โ confirm the order; if payment fails, compensate by releasing the reservation. Each step is idempotent and events go through an outbox. For a flash sale, one SKU row becomes a lock hotspot, so I split its stock into buckets or use a Redis counter with the database as the record, and add a waiting room. The trade-off: strong consistency only on the reservation, eventual consistency everywhere else.
"I'd clarify when we promise stock. Reserving at add-to-cart locks up inventory for people who never buy; reserving at checkout means someone can lose an item they had in their cart, which is normal retail behaviour. I'd reserve when the customer starts payment, for ten minutes. Then numbers: a big retailer might take a million orders on Black Friday, about 12 a second on average but 500 a second at the 9 pm peak. The really hard case is a flash sale: 500 units of one console and 20,000 people pressing Buy within seconds.
The correctness core is a conditional decrement in the inventory database: subtract the quantity only where enough is available, in one statement, and insert a reservation row with an expiry in the same transaction. If the update affects no rows, it's sold out, and nobody can oversell because the check and the write are a single atomic operation. Then a saga: Orders asks Inventory to reserve, Payment to charge with an idempotency key, and then confirms. If payment declines, the saga releases the reservation. If the payment outcome is unknown, we extend the hold rather than release it, because releasing stock someone may have paid for is how you oversell. Events go through an outbox so a crash can't lose them.
For the flash sale, that single SKU row is the bottleneck: every buyer queues on one row lock. For example, at [company] we [saw lock waits of several seconds on one SKU during a sale]; [splitting stock into 20 buckets] [took p95 reservation time to under 50 ms]. I'd also put a virtual waiting room in front so we admit buyers at a rate the system can serve.
The mistake I see is checking stock in one query and decrementing in another, or trusting a cached stock number. Inventory is the one place in e-commerce where you pay for strong consistency; everything else can be eventual."
| Type | Requirement | Assumption |
|---|---|---|
| Functional | Cart, checkout, payment, order confirmation | Guest checkout allowed |
| Functional | Never sell more than available stock | Per warehouse |
| Functional | Reservations expire | 10 minutes, extendable once |
| Non-functional | Reservation p95 < 100 ms at peak | Including flash sales |
| Non-functional | No lost paid orders | Saga + outbox + reconciliation |
| Non-functional | Product pages fast | Stock shown is approximate (cached) |
| Quantity | Arithmetic | Result |
|---|---|---|
| Orders peak day | given | 1,000,000 |
| Average | 1M รท 86,400 | โ 12/s |
| Peak hour (ร40) | assumption | โ 500/s |
| Flash sale attempts | 20,000 users in ~1 s | 20,000/s on one SKU |
| Reservations stored | 500/s ร 600 s TTL | โ 300,000 active holds at peak |
Browser โโโบ Front Door (+ waiting room for flash sales)
โ
โผ
Cart API (Redis / Cosmos DB, eventual) โโโบ Checkout API โโโบ Order saga (orchestrator)
โ โ โ
reserve/release โ charge โ confirm โ
โผ โผ โผ
Inventory svc Payment svc Orders svc
Azure SQL (PSP) Azure SQL
Stock, Reservations
sweeper releases expired holds
Service Bus (outbox relays) connects the services
| Data | Consistency | Why |
|---|---|---|
| Stock shown on product page | Eventual (cached ~30 s) | Display only |
| Cart contents | Eventual | No promise made |
| Reservation | Strong, atomic | This is the promise |
| Order status, emails | Eventual via events | Seconds of lag is fine |
In a [Black Friday] sale with [800] units of one product and [35,000] buyers in the first minute, a waiting room admitted [1,500] buyers a second, bucketed stock kept reservation p95 at [40 ms], and the sale ended with exactly 800 orders and [62] reservations released after payment declines and resold.
Checks that the candidate identifies the inventory invariant, enforces it atomically, and handles the distributed checkout flow and flash-sale contention.
Green flags
Red flags
The classic oversell bug:
T1: SELECT Available โ 1 T2: SELECT Available โ 1
T1: UPDATE Available = 0 T2: UPDATE Available = 0 โ two orders, one unit
The fix is a single conditional statement. SQL Server takes an update lock on the row, re-evaluates the predicate, and only one transaction can take the last unit. Pair it with a reservation insert in the same transaction:
BEGIN TRAN
UPDATE Stock SET Available -= @q WHERE Sku=@s AND WarehouseId=@w AND Available >= @q -- 0 rows โ sold out
INSERT Reservations(Id, Sku, WarehouseId, Qty, OrderId, ExpiresAt)
COMMIT
Releasing is the reverse, and must be idempotent: only release a reservation whose state is still Held, changing it to Released in the same statement.
A sweeper (BackgroundService or Azure Functions timer) runs every 30 s: select a batch of Held reservations with ExpiresAt < now, mark them Expired and add their quantity back, in small transactions. Index on (State, ExpiresAt). Never release a reservation whose payment is Unknown: extend it and resolve the payment first.
Reserve โโokโโโบ Charge โโokโโโบ Confirm order, commit reservation (Held โ Committed)
โ sold out โ declined
โผ โผ
fail order Release reservation, fail order
โ unknown
โผ
Extend hold, query PSP, then continue
An orchestrated saga (a state machine per order, persisted, e.g. MassTransit saga or Durable Functions) is easier to reason about than choreography here, because there are clear compensation rules. Every step carries the order id as an idempotency key.
One row can only process updates one at a time. If each transaction holds the lock ~2 ms, one row tops out at a few hundred reservations a second, and waits explode beyond that.
DECRBY atomically (or a Lua script that refuses below zero); winners then create the reservation in SQL asynchronously. Redis is the gate, SQL the record; reconcile at the end.Stock per (SKU, warehouse). Allocation picks a warehouse by rule (closest to postcode, then most stock); the reservation names the warehouse. Showing 'in stock' on the page uses a cached sum across warehouses.
Aurora/DynamoDB conditional writes (ConditionExpression: available >= :q), Step Functions for the saga, SQS/EventBridge, ElastiCache for the flash-sale gate.
sys.dm_os_wait_stats (LCK_M_U waits).PaymentUnknown.Atomic reservation with expiry, an idempotent release, and a bucketed variant for hot SKUs.
using Microsoft.Data.SqlClient;
namespace Inventory;
public sealed record ReserveRequest(Guid OrderId, string Sku, int WarehouseId, int Quantity);
public enum ReserveResult { Reserved, SoldOut, AlreadyReserved }
public sealed class ReservationService(string connectionString, TimeProvider clock)
{
private static readonly TimeSpan Hold = TimeSpan.FromMinutes(10);
public async Task<ReserveResult> ReserveAsync(ReserveRequest r, CancellationToken ct)
{
// One statement batch, one transaction: conditional decrement + reservation row.
const string sql = """
SET XACT_ABORT ON;
BEGIN TRAN;
IF EXISTS (SELECT 1 FROM dbo.Reservations WHERE OrderId = @order AND Sku = @sku)
BEGIN COMMIT; SELECT 2; RETURN; END -- idempotent retry
UPDATE dbo.Stock SET Available -= @qty
WHERE Sku = @sku AND WarehouseId = @wh AND Available >= @qty;
IF @@ROWCOUNT = 0 BEGIN ROLLBACK; SELECT 1; RETURN; END
INSERT dbo.Reservations(Id, OrderId, Sku, WarehouseId, Qty, State, ExpiresAt)
VALUES (NEWID(), @order, @sku, @wh, @qty, 'Held', @expires);
COMMIT; SELECT 0;
""";
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@order", r.OrderId);
cmd.Parameters.AddWithValue("@sku", r.Sku);
cmd.Parameters.AddWithValue("@wh", r.WarehouseId);
cmd.Parameters.AddWithValue("@qty", r.Quantity);
cmd.Parameters.AddWithValue("@expires", clock.GetUtcNow().Add(Hold).UtcDateTime);
return (int)(await cmd.ExecuteScalarAsync(ct))! switch
{
0 => ReserveResult.Reserved,
1 => ReserveResult.SoldOut,
_ => ReserveResult.AlreadyReserved
};
}
}
-- Idempotent release: only a Held reservation gives stock back, exactly once.
UPDATE r SET State = 'Released'
OUTPUT deleted.Sku, deleted.WarehouseId, deleted.Qty INTO @released
FROM dbo.Reservations r
WHERE r.OrderId = @order AND r.State = 'Held';
UPDATE s SET Available += x.Qty
FROM dbo.Stock s JOIN @released x ON x.Sku = s.Sku AND x.WarehouseId = s.WarehouseId;
-- Hot SKU: stock split into buckets; try a random bucket first.
UPDATE TOP (1) dbo.StockBuckets SET Available -= @qty
WHERE Sku = @sku AND BucketNo = @randomBucket AND Available >= @qty;
Senior answers find the one invariant (available โฅ 0) and spend strong consistency only there, then design the rest around it with sagas and events. They also treat flash sales as a separate mode with its own controls (waiting room, buckets, pre-warmed caches) rather than hoping the normal path scales 40ร.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Conditional UPDATE on one row | Normal traffic, < a few hundred/s per SKU | Simplest | Flash sales on one SKU |
| Stock buckets | Hot SKUs, still SQL as truth | Allocation logic, 'last few units' edge cases | Low-volume SKUs |
| Redis gate + async SQL record | Extreme bursts | Reconciliation, Redis durability concerns | When SQL can keep up |
| Waiting room | Known high-demand launches | Product/UX work, third-party cost | Everyday traffic |
I measure oversell count (must be zero, checked by reconciliation), reservation latency and lock waits per SKU, reservations expired vs committed, and saga completion time.
Each service changes its own data and writes outgoing messages in one transaction (outbox), and dedups incoming messages (inbox). A saga orchestrator persists the order's progress: on OrderPlaced it sends ReserveStock; on StockReserved it sends CapturePayment; on PaymentCaptured it completes. If payment fails it sends the compensation ReleaseStock.
At every step a crash either committed nothing (the message is redelivered) or committed everything (the outbox resends). Duplicates hit the inbox. Missing replies trigger scheduled timeouts, and late replies after a timeout get their own handling, such as refunding a late capture. Poison messages dead-letter with alerts.
The trade-off: reliability without distributed transactions, paid for with eventual consistency, more states and more operational tooling.
I keep card data out of our systems entirely: the browser uses the PSP's hosted fields, we get a token, and our PCI DSS scope shrinks to the smallest self-assessment. Each payment is a state machine (Created โ RequiresAction for 3-D Secure โ Authorised โ Captured โ Refunded). Every call to the PSP carries an idempotency key tied to the payment attempt, so retries can't double-charge. A timeout is an unknown outcome: I query the PSP by our merchant reference before deciding. Webhooks are verified, deduplicated by event id and applied through the state machine, so out-of-order delivery is harmless. A daily reconciliation compares our records with the settlement report. The trade-off: the PSP owns the money movement and much of the flexibility; we own correctness of our records.
Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.
The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.
How to tell it (STAR)
**S:** At [company] a limited sneaker launch sold [73] more pairs than we had, which turned into refunds and a lot of angry posts. **T:** I was asked to make the next launch, [six weeks] later, impossible to oversell. **A:** I found a read-then-write stock check that raced under load, made worse by timeouts and retries. I replaced it with a single conditional update plus a reservation row with expiry and an order-id idempotency key, split launch stock into buckets, and added a waiting room. A CI test now fires 1,000 concurrent reservations at 100 units. **R:** The next launch sold exactly [800] of [800] units in [3 minutes], with reservation p95 of [45 ms] and zero oversells.
Last updated 23 Nov 2026.