📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Design the checkout for an e-commerce site that must never oversell, including during a Black Friday flash sale where thousands of people try to buy the last few hundred units of one product. Walk me through cart, inventory reservation, payment and order confirmation, how reservations expire, and what happens when payment fails or a service crashes mid-checkout.

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.

Senior SystemDesign Advanced concurrency e-commerce flash-sale inventory saga system-design

๐ŸŽฏ Key points

  • Clarify: when stock is reserved (cart vs checkout), reservation TTL, backorders, multi-warehouse
  • Estimate: 1M orders on peak day ≈ 12/s average, 500/s peak; flash sale 20k attempts/s on one SKU
  • Atomic conditional decrement: UPDATE ... SET Available -= @q WHERE Available >= @q; safe under default READ COMMITTED/RCSI because the predicate is re-checked under the row's update lock, so SERIALIZABLE isn't needed
  • Reservation rows with ExpiresAt; sweeper releases expired holds; payment success commits the hold (Held → Committed) so it can no longer expire
  • Saga: reserve → pay → confirm; compensate by releasing stock or refunding; outbox + idempotent consumers
  • PSP down or outcome unknown: extend the hold, retry with the same idempotency key, never release stock that may be paid for
  • Hot SKU: split stock into N buckets or a Redis gate, plus a waiting room; product pages read cached stock or read replicas
  • Inventory service down: fail checkout for affected SKUs fast with a clear message while browsing and carts keep working; never 'sell anyway' without a backorder policy

โฑ 30-second answer

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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"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."


Requirements

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)

Capacity estimate

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

High-level design

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

Where consistency is needed

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

Production example

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.

๐Ÿ” What the interviewer is checking

Checks that the candidate identifies the inventory invariant, enforces it atomically, and handles the distributed checkout flow and flash-sale contention.

Green flags

  • Atomic conditional decrement and reservation with expiry
  • Saga with compensation, and the payment-unknown case
  • Recognises the hot-row problem and proposes buckets, Redis gate or waiting room
  • Applies strong consistency only where needed

Red flags

  • Read-then-write stock checks
  • Two-phase commit across services and the PSP
  • Reservation without expiry
  • Uses cached stock to decide a purchase

๐Ÿ“š Learn in depth

1. The atomic reservation

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.

2. Expiry

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.

3. The saga

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.

4. Flash sales and hot rows

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.

  • Buckets: split 500 units into 20 rows of 25; pick a random bucket, fall back to others when it's empty. Throughput scales with buckets.
  • Redis counter: pre-load stock into Redis and 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.
  • Waiting room: admit users at a fixed rate with a signed token; it protects every downstream system, not just inventory.

5. Multi-warehouse

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.

6. Failure modes

  • Crash after reserve, before charge โ†’ saga resumes from persisted state; if abandoned, expiry releases stock.
  • Duplicate 'reserve' message โ†’ reservation keyed by order id + SKU, unique index.
  • Payment succeeded but confirm event lost โ†’ outbox guarantees publish; reconciliation catches the rest.
  • Inventory database down โ†’ checkout unavailable for affected SKUs; browsing and carts keep working.

7. AWS mapping

Aurora/DynamoDB conditional writes (ConditionExpression: available >= :q), Step Functions for the saga, SQS/EventBridge, ElastiCache for the flash-sale gate.

Try it yourself

  1. Run 200 concurrent reservations for 100 units with a read-then-write implementation and count oversells; repeat with the conditional update.
  2. Measure reservations per second on one hot row vs 20 buckets using a small load test and sys.dm_os_wait_stats (LCK_M_U waits).
  3. Write the sweeper and test that it never releases a reservation in PaymentUnknown.
  4. Model the saga as a state machine in a unit test with payment decline, unknown and success paths.
  5. Implement the Redis Lua gate and reconcile Redis winners against SQL reservations.

๐Ÿ’ป Code

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;

โš  Common mistakes

  • Mistake: Checking stock with a SELECT and decrementing in a separate statement. Why it is wrong: concurrent buyers both see the last unit and both buy it. Instead: one conditional UPDATE with the availability predicate, which is atomic even at READ COMMITTED.
  • Mistake: Raising the isolation level to SERIALIZABLE for the whole checkout. Why it is wrong: range locks and long transactions cause blocking and deadlocks at peak, without adding safety the conditional update doesn't already give. Instead: keep the transaction tiny and let the predicate do the work.
  • Mistake: Reserving stock at add-to-cart with no expiry. Why it is wrong: abandoned carts lock up inventory and the site shows sold out while warehouses are full. Instead: reserve at checkout with a short TTL and a sweeper.
  • Mistake: Releasing a reservation when the payment outcome is unknown. Why it is wrong: the payment may have succeeded, so the unit is sold twice. Instead: extend the hold and resolve the payment first.
  • Mistake: Trusting cached stock for the purchase decision. Why it is wrong: the cache is stale under exactly the load where it matters. Instead: cache for display only; the reservation hits the source of truth.
  • Mistake: Non-idempotent reserve and release. Why it is wrong: duplicate messages double-reserve or double-release, corrupting stock counts. Instead: key reservations by order id and change state conditionally.
  • Mistake: One row per SKU during a flash sale. Why it is wrong: all buyers serialise on one lock and time out. Instead: buckets, a Redis gate, and a waiting room.
  • Mistake: Taking orders without reservation when the inventory service is down. Why it is wrong: during peak demand that is exactly how you oversell hundreds of units. Instead: fail fast for affected SKUs with a clear message, or accept orders only under an explicit backorder policy.
  • Mistake: A distributed transaction across inventory, payment and orders. Why it is wrong: the PSP can't take part, and 2PC couples availability of all services. Instead: a saga with compensations.

๐Ÿ› Senior insight: trade-offs

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.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate describes the order flow across services Why: Checks outbox, inbox and orchestrated saga behaviour when a service crashes or a reply never arrives
    How to answer

    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.

  2. When: Candidate mentions taking payment in the saga Why: Checks idempotent charges, unknown outcomes and webhooks
    How to answer

    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.

  3. When: Candidate talks about locking or isolation Why: Checks which isolation level and locks actually prevent the oversell
    How to answer

    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.

๐Ÿ›  Real-world problems: how you handle them

Oversold limited-edition stock in a flash sale
Situation
An e-commerce platform for [a sneaker retailer], [ASP.NET Core + Azure SQL], launching [600] pairs of a limited release to [40,000] waiting customers.
Signals
[73] more orders than units; customer complaints and social media posts; Application Insights showed reservation calls at p95 [6 s] and many timeouts followed by client retries.
Investigation
Code review of the reservation path showed a SELECT then UPDATE in separate statements under READ COMMITTED. Query Store and wait stats showed heavy LCK_M_U waits on one Stock row. Timeouts led to retries that ran the race again.
Resolution
Immediate: cancelled and refunded the oversold orders with an apology voucher. Long term: conditional UPDATE with reservation rows and expiry, idempotency by order id, stock buckets for launch SKUs, and a waiting room admitting [1,000] buyers a second.
Prevention
A concurrency test in CI that fires 1,000 parallel reservations for 100 units and asserts exactly 100 succeed; a launch checklist (buckets, waiting room, pre-warm); a post-sale reconciliation report.

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.

โ†ฉ Usually asked after

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me