Skip to content

    System Design

    Case Study: E-Commerce Order System (ShopStream)

    Design an e-commerce order system end to end: durable checkout, no oversell, a saga across stock, payment and delivery, an outbox, idempotency and read models.

    By Published 20 min read

    Share

    What you'll learn: By the end of this lesson you will be able to (1) scope an order system and size it with a few shared numbers, (2) design a checkout that accepts an order durably in one local transaction and answers fast, (3) reserve stock without overselling and drive stock, payment and delivery through a saga with compensation, and (4) keep events, retries and read models correct when every step can run twice.

    This is an educational reference design, not the verified internal architecture of any company. ShopStream is the fictional grocery marketplace used across this course, and every number is an illustrative assumption unless a source is named.

    Picture a restaurant on a busy Friday. The waiter writes a ticket and the guest is told "it is coming". The ticket goes to the kitchen, the bar and the cashier, who work at their own pace. Nobody is allowed to lose the ticket, serve it twice or charge the guest for a dish that was never made. The ticket itself is small. The whole difficulty is the promise it represents, spread across several desks that cannot share one lock.

    An e-commerce order is that ticket. This case study pulls together what the ShopStream project lessons teach step by step, and shows how the pieces fit in one interview-sized design. Where a concept has its own lesson we link it and give only the working definition: ShopStream brief, data model, scaling writes, order pipeline, payments and ledger, resilience, the saga, outbox and idempotency key lessons, and idempotent consumers. The general method for case studies lives in the case-studies overview lesson, which is planned and not yet linked here.

    The core idea

    An order system is a durable state machine plus a set of promises to other systems. Checkout does the smallest thing that must be atomic: it records the shopper's intent, the price they saw and an event to publish, in one local transaction, and answers immediately. Everything slower or more fragile (stock, payment, courier) happens afterwards as a saga of local transactions, each safe to repeat, each with a defined undo. Because networks, brokers and workers fail at random moments, the design leans on three habits: write intent first, make every step idempotent, and give every failure a named state.

    Requirements and scope

    Functional:

    • Place an order from a cart: items, quantities, delivery address, payment method.
    • Reserve stock at the chosen store, authorise payment, assign a courier, confirm.
    • Show order status and history; let the shopper cancel until the courier collects.
    • Notify the shopper at each important state change.

    Out of scope here: catalogue and search, cart storage, promotions and tax engines, fraud scoring, returns and refunds, courier routing. The brief and later project lessons cover some of these.

    Non-functional (assumptions):

    • Never charge twice and never lose an accepted order. These two rules outrank speed.
    • No oversell beyond a stated policy. For groceries a rare substitution is acceptable. For a limited promotion it is not.
    • Checkout answers in under about 300 ms at p99 (illustrative), because it only records intent.
    • Order status becomes consistent within a few seconds. The shopper always sees their own latest order.
    • Every state change is auditable: who or what moved the order, and when.

    Back-of-envelope estimate

    The shared ShopStream numbers (500,000 orders per day, peak ten times the average) are illustrative assumptions. Derived values:

    Quantity Assumption Result
    Orders per day 500,000 about 5.8 per second on average
    Peak checkouts 10 times average about 58 per second
    Lines per order 8 (illustrative) 4 million lines per day
    Stock updates at peak 58 x 8 about 464 per second across all stores
    Events per order 6 (see the order pipeline lesson) about 350 events per second at peak
    Event size 1 KB about 3 GB per day
    Order rows 9 rows (1 header, 8 lines) x 200 bytes about 0.9 GB per day, about 330 GB per year before indexes

    Two conclusions follow. First, the load is modest: one well-tuned PostgreSQL primary per shard handles hundreds of writes per second, so the hard part is correctness, not raw throughput. Second, the tail matters more than the average. A single promotional item that 30 percent of peak orders contain receives about 17 updates per second on one stock row (illustrative), and those updates serialise on that row. That hot row is the scaling problem to solve.

    API design

    POST /v1/orders
    Idempotency-Key: 6f1c2f8e-0d2b-4a8e-9a43-5d1b7a6e0c11
    Content-Type: application/json
    
    { "cartId": "c-5521", "storeId": 42, "addressId": "a-9", "paymentMethodId": "pm-3" }
    
    -> 202 Accepted
    Location: /v1/orders/o-7001
    { "orderId": "o-7001", "status": "PENDING" }
    
    GET  /v1/orders/o-7001               -> 200 { "status": "STOCK_RESERVED", "version": 3, ... }
    GET  /v1/orders?cursor=...&limit=20  -> 200 { "items": [...], "nextCursor": "..." }
    POST /v1/orders/o-7001/cancel        -> 202 { "status": "CANCEL_REQUESTED" }

    Three design choices are visible. POST /v1/orders returns 202 Accepted, not 201, because the order exists but is not confirmed. The client-generated Idempotency-Key makes the call safe to retry, as the idempotency key lesson explains. Cancel is also a request, because the saga may be mid-step.

    Data model

    erDiagram accTitle: Order system core tables accDescr: An order has many lines, many state history rows and many outbox rows. An idempotency key row points to one order. Stock holds link an order to a stock row. ORDERS ||--|{ ORDER_LINES : contains ORDERS ||--o{ ORDER_HISTORY : records ORDERS ||--o{ OUTBOX : emits ORDERS ||--o| IDEMPOTENCY_KEYS : created_by ORDERS ||--o{ STOCK_HOLDS : reserves STOCK ||--o{ STOCK_HOLDS : held_in ORDERS { string order_id PK long shopper_id int store_id string status int version long total_minor string currency } ORDER_LINES { string order_id FK string sku int qty long unit_price_minor } ORDER_HISTORY { string order_id FK string from_status string to_status datetime at } OUTBOX { long id PK string order_id string type string payload datetime published_at } IDEMPOTENCY_KEYS { string key PK string request_hash string order_id FK datetime created_at } STOCK { int store_id PK string sku PK int available } STOCK_HOLDS { string order_id PK string sku PK int qty datetime expires_at string state }

    How to read this: ORDERS is the aggregate root. Lines copy the unit price at order time, so a later price change never rewrites history. OUTBOX and IDEMPOTENCY_KEYS live in the same database as ORDERS so one local transaction can write all of them. STOCK and STOCK_HOLDS belong to the inventory service and have their own database.

    Key modelling decisions:

    • Money is stored in minor units (integer cents) with a currency code, never as floating point.
    • status plus version on the order. Every transition is a guarded update: it succeeds only if the row is still in the expected state. That one rule makes concurrent or duplicated messages harmless.
    • Order history is append-only: it is the audit trail and the debugging tool.
    • Orders are sharded by shopper id (the scaling writes lesson explains the choice), so "my orders" reads one shard and all of a shopper's orders live together. Stock is sharded by store, because stock questions are about a store.

    High-level design

    Figure 1. The order system at a glance

    E-commerce order system high-level designShopper app to API gateway; API gateway to Checkout service (POST order); Checkout service to Outbox relay (outbox row); Outbox relay to Kafka; Kafka to Orchestrator (event); Orchestrator to Inventory (reserve); Orchestrator to Payments (authorise); Orchestrator to Delivery (assign); Kafka to Read model; Kafka to NotificationsShopper appShopper appAPI gatewayAPI gatewayCheckout service: orders databaseCheckoutserviceorders databaseOutbox relayOutbox relayKafka: order-eventsKafkaorder-eventsOrchestrator: saga stateOrchestratorsaga stateInventory: stock and holdsInventorystock and holdsPayments: gateway and ledgerPaymentsgateway andledgerDelivery: courier assignmentDeliverycourierassignmentRead model: order historyRead modelorder historyNotificationsNotificationsPOST orderoutbox roweventreserveauthoriseassign

    How to read this: the solid path from the shopper ends at the checkout service, which returns 202. The dashed paths are events: the relay publishes the order to Kafka, and the orchestrator, the read model and notifications each read it. The orchestrator is the only component that commands stock, payment and delivery, so the flow lives in one place.

    Deep dive 1: accepting the order

    Checkout must not call stock, payment or delivery. Each is slower, less available or owned by another team, and calling them in sequence multiplies their failures: five dependencies each available 99.9 percent of the time are all available about 99.5 percent of the time (illustrative arithmetic from the order pipeline lesson). Instead, checkout runs one local transaction with four writes:

    1. Insert the idempotency record for the key, with a hash of the request body.
    2. Insert the order (PENDING, version 1) and its lines, with prices copied from the catalogue at that moment.
    3. Insert an OrderPlaced row into the outbox.
    4. Commit, then return 202.

    Figure 2. One checkout from the shopper's side

    sequenceDiagram accTitle: Checkout accepted in one local transaction accDescr: The shopper sends an order with an idempotency key. The checkout service writes the key, the order and the outbox row in one transaction and returns 202. The relay publishes the event and the orchestrator starts the saga. participant S as Shopper participant C as Checkout service participant D as Orders database participant R as Outbox relay participant K as Kafka participant O as Orchestrator S->>C: POST order with Idempotency-Key C->>D: BEGIN, insert key, order, lines, outbox row, COMMIT D-->>C: committed C-->>S: 202 Accepted, order o-7001 R->>D: read unpublished outbox rows R->>K: publish OrderPlaced, key o-7001 R->>D: mark row published K->>O: OrderPlaced Note over O: saga starts, every step is retryable

    How to read this: the shopper's wait ends at the 202. The relay and the orchestrator work after the response, which is why checkout latency does not depend on stock, payment or delivery.

    The outbox is what makes step 3 safe. Without it the service would write the order and then publish to the broker as two separate actions, and a crash between them either loses the event or publishes an event for an order that was rolled back. The pattern stores the message in the same transaction as the business data and lets a separate relay forward it. The relay may publish a message more than once, for example after crashing between publishing and recording that it did so, so every consumer must be idempotent. The pattern's own description gives the guarantee: the message is sent if and only if the transaction commits. The transactional outbox lesson shows the failure cases in a lab.

    What the idempotency record decides. When the same key arrives again:

    Situation Answer
    Key unseen Run the transaction above
    Key seen, same request hash, order exists Return the original 202 and order id
    Key seen, different request hash Reject with a conflict error: the client reused a key for a different order
    Key seen, transaction still in flight Wait briefly or answer "in progress" and let the client retry
    Key older than the retention window Treated as new (retention is a product decision, illustratively 24 hours)

    This mirrors how a payment provider documents it. Stripe's API reference for version 1 says the first response for a key is saved and returned on retries, including 500 errors, that keys can be pruned after at least 24 hours, that the incoming parameters are compared with the original request, and that a request which fails validation or conflicts with a concurrent one is not saved and can be retried. Keys are up to 255 characters. Use the same shape for your own checkout.

    Deep dive 2: stock without overselling

    The tempting design reads stock, checks it, then writes it:

    available = SELECT available FROM stock WHERE store_id = 42 AND sku = 'milk-1l'
    if available >= 2: UPDATE stock SET available = available - 2 ...

    Two shoppers can both read 2 and both subtract. This is the classic check-then-act race. The fix is to make the check and the decrement one atomic statement whose condition is evaluated by the database against the latest committed row:

    UPDATE stock
       SET available = available - 2
     WHERE store_id = 42 AND sku = 'milk-1l' AND available >= 2;

    If the statement updates one row, the reservation succeeded. If it updates zero rows, there was not enough stock. PostgreSQL's default Read Committed isolation makes this safe under concurrency: an updater that finds a row already being changed by another transaction waits for that transaction to finish, and if the first one commits, re-evaluates the WHERE clause against the updated row. So the second shopper's available >= 2 is tested against the first shopper's result, not a stale read. The same documentation page warns that this re-evaluation behaviour can surprise you in other query shapes, so keep the statement this simple.

    A reservation is more than a decrement, because it must be undoable and expiring. The inventory service therefore writes, in one transaction on its own database:

    1. INSERT INTO stock_holds (order_id, sku, qty, expires_at, state) ... ON CONFLICT (order_id, sku) DO NOTHING. The primary key makes a repeated ReserveStock command harmless: the insert is skipped. PostgreSQL documents that ON CONFLICT DO NOTHING simply avoids inserting the row.
    2. Only if the insert added a row, run the guarded decrement above. If it updated zero rows, delete the hold and reply StockUnavailable.
    3. Reply StockReserved through the outbox.

    Release is the mirror: mark the hold RELEASED (guarded on its current state) and add the quantity back. A scheduled job releases holds past expires_at, so a saga that stalls cannot lock stock forever. The ShopStream hold lasts 10 minutes (illustrative).

    The hot row. One promotional item receiving about 17 updates per second serialises on a single row, and each update holds the row lock for the whole transaction. Options, from simplest:

    • Keep transactions short and keep the decrement as the first statement that touches the stock row, so the lock is held for milliseconds.
    • Split the counter: represent 1,000 units as 10 rows of 100 (buckets), pick a bucket by hashing the order id, and fall back to other buckets when one empties. This spreads the lock contention. The cost is that the last few units are hard to sell, because they sit in different buckets.
    • For a flash sale of a strictly limited item, put reservation behind a queue that admits shoppers at the rate stock can be decremented, so excess demand waits in line instead of in lock waits.

    The policy question matters as much as the mechanism. A grocery shelf is not a database row: stock counts are estimates, so ShopStream treats the hold as a soft reservation and lets the picker substitute. A ticketing system would need a hard reservation. State which one you are building.

    Deep dive 3: the saga

    Stock, payment and delivery have different owners and different databases, and a two-phase commit across an external payment gateway is not an option. A saga is a coordinated sequence of local transactions in which each step has a compensating action that semantically undoes it. Compensation must be designed explicitly, and sagas give up isolation: other readers can see a half-finished order. The saga lesson compares the two coordination styles; ShopStream uses orchestration, because a central owner of the flow can answer "where is order 9001 stuck?" in one query.

    Figure 3. Order states

    stateDiagram-v2 accTitle: Order saga states and cancellation accDescr: An order moves from pending through stock reserved and payment authorised to confirmed. Failures lead to compensating and then cancelled. A cancel request in a cancellable state also leads to compensating. A failing compensation leads to needs review. [*] --> PENDING: checkout accepted PENDING --> STOCK_RESERVED: stock held STOCK_RESERVED --> PAYMENT_AUTHORISED: funds held PAYMENT_AUTHORISED --> CONFIRMED: courier assigned PENDING --> CANCELLED: stock unavailable STOCK_RESERVED --> COMPENSATING: payment declined or cancel PAYMENT_AUTHORISED --> COMPENSATING: no courier or cancel COMPENSATING --> CANCELLED: undo steps done COMPENSATING --> NEEDS_REVIEW: undo keeps failing CONFIRMED --> COLLECTED: courier collects COLLECTED --> [*] CANCELLED --> [*]

    How to read this: every arrow is a guarded update that checks the current state. COMPENSATING runs the undo steps in reverse order. NEEDS_REVIEW is where a person takes over. CONFIRMED can still be cancelled until the courier collects, and cancel then follows the same compensating path.

    The orchestrator's loop for each event is the same every time:

    1. Load the order. If the event does not match a valid transition from the current state, ignore it (it is a duplicate or a stale message).
    2. Apply the transition with UPDATE orders SET status = :next, version = version + 1 WHERE order_id = :id AND status = :expected. Zero rows updated means another copy of the event won.
    3. Write the history row and, through the outbox, the next command, in the same transaction.

    The state and the outgoing command commit together, so a crash between "decided" and "told" cannot happen. Step 2 is the idempotency of the saga itself.

    Compensation is not rollback. A void of a payment authorisation is a new action that can fail. It must be retried until it succeeds, and every attempt must be safe to repeat, so the payment service takes the order id as its idempotency key. After a capture the undo is a refund, with its own ledger entries; the payments and ledger lesson and the double-entry ledger lesson cover that side.

    Deadlines. Every non-final state has a deadline (illustratively 10 minutes for the whole saga). A scheduled job finds orders stuck past it and sends them to COMPENSATING. A stuck order is a defect with an owner, never a normal condition.

    Deep dive 4: events, ordering and the read model

    Figure 4. Event flow after checkout

    Order events fan out from one Kafka topicOrders DB to Outbox relay; Outbox relay to Kafka; Kafka to Orchestrator group; Kafka to Read-model group; Kafka to Notification group; Kafka to Analytics group; Read-model group to Order history storeOrders DB: orders, outboxOrders DBorders, outboxOutbox relayOutbox relayKafka: key = order idKafkakey = order idOrchestrator group: saga stepsOrchestratorgroupsaga stepsRead-model group: order historyRead-modelgrouporder historyNotification groupNotificationgroupAnalytics groupAnalyticsgroupOrder history storeOrder historystore

    How to read this: one topic, several independent consumer groups. Each group keeps its own position, so a slow notification group never delays the orchestrator.

    Kafka partitions a topic and writes events with the same key to the same partition. A consumer of a partition reads it in exactly the order it was written, and events stay available after they are read, until the topic's retention ends. ShopStream keys order-events by order id, so all events of one order are ordered and different orders run in parallel across partitions. There is no ordering guarantee across partitions, and that is fine, because nothing needs to compare two different orders.

    Kafka's delivery guarantee by default is at least once: messages are never lost but may be redelivered. So every consumer needs an idempotent way to apply an event. For the order read model, the natural rule is version-guarded upsert: apply an event only if its order version is higher than the stored one. For consumers that perform side effects (sending an email, creating a courier job) the pattern is a processed_events table written in the same transaction as the effect, as in the idempotent consumers lesson, or a natural idempotency key such as the notification id.

    The order history read model is a denormalised table shaped for "my orders" and the status page. It is a deliberate small piece of CQRS (the CQRS and event sourcing lesson goes deeper) and it is eventually consistent. One rule keeps users from being confused: right after placing an order, read it from the orders shard that holds it (a read-your-writes path), and use the read model for lists and history.

    Deep dive 5: cancellation races

    A shopper taps cancel while the courier step is running. Treat cancel as another event for the same order, in the same partition, handled by the same state machine:

    Current state Cancel request
    PENDING, STOCK_RESERVED, PAYMENT_AUTHORISED Move to COMPENSATING; undo completed steps in reverse order
    CONFIRMED Allowed until collection; compensate (void or refund, release courier)
    COLLECTED Reject: the order is out for delivery; offer a return flow instead
    COMPENSATING, CANCELLED Idempotent no-op; return the current status

    The race between "courier assigned" and "cancel" resolves itself because both are guarded updates on one row: whichever commits first wins, and the loser's event is ignored or compensated. No locks across services are needed.

    Caching, bottlenecks and scaling

    • Reads (order status, history) dominate writes. Serve lists from the read model, cache the status page with a short time-to-live, and invalidate on events.
    • Orders database: shard by shopper id. Throughput at peak is far below what one primary handles, so sharding is for data size and isolation, not speed (see the sharding lesson).
    • Orchestrator: parallelism equals the number of partitions of order-events. The project's 12 partitions (illustrative) allow 12 parallel workers.
    • Payment gateway: the gateway's rate limit is the real ceiling. At 58 checkouts per second against a contract of 40 authorisations per second (illustrative), the payment queue absorbs the surplus and shedding rules decide what happens when it is full. The order pipeline lesson works the backpressure arithmetic.
    • Hot stock rows: buckets or an admission queue, as above.

    Failure modes

    Failure Effect Defence
    Checkout times out after commit Client retries Idempotency key returns the original order
    Crash between order write and publish None: the event is in the outbox Relay publishes on restart
    Relay publishes twice Duplicate OrderPlaced Orchestrator's guarded update ignores the copy
    Payment gateway slow or down Orders stall at STOCK_RESERVED Timeout, retry with backoff, deadline, then compensate; see timeouts and retries
    Payment authorised but reply lost Orchestrator retries Order id as idempotency key makes the retry return the original result
    Compensation keeps failing Funds or stock stay held NEEDS_REVIEW queue, alert, stock-hold expiry as backstop
    Poison event Consumer loops Retry limit, then a dead-letter topic; see dead-letter queues
    Consumer group lags Stale status, late emails Alert on lag per group and partition

    Build it

    This lesson has no lab: it is a design walkthrough. Working code for the individual patterns is in the lessons linked above (outbox, saga, idempotent consumer and idempotency key labs run in-process with MockMvc, an in-process Kafka broker and in-memory or H2 data, each named in its lesson). No output is shown here.

    Trade-offs worth stating

    Decision Choice here Gain Cost Wrong when
    Checkout response 202 after local commit Fast, independent of downstream Order not yet confirmed; UI shows progress The business needs an instant yes or no, for example a last-unit flash sale
    Coordination Orchestrated saga One place to see and test the flow Orchestrator must be reliable and free of business rules Only two simple steps exist
    Event publishing Outbox plus relay No lost or phantom events Extra table, relay to run, duplicates possible You can use a platform that offers transactional publishing for your store
    Stock Guarded decrement plus expiring hold No oversell, self-healing Hot-row contention, soft versus hard policy to decide Stock is only an estimate and substitution is fine, so a lighter check suffices
    Read path Read model plus read-your-writes Fast lists, simple scaling Eventual consistency, one more store Volume is small enough for direct queries
    Delivery guarantee At least once plus idempotent consumers Simple and robust Every consumer must handle duplicates The effect is naturally idempotent already (then there is nothing to add)

    Interview cheat sheet

    1. Clarify scope and the oversell policy first. Ask: hard or soft reservation?
    2. Size it: orders per second at peak, lines per order, events per order. Conclude that correctness, not throughput, is the challenge.
    3. Draw checkout as one local transaction: order, lines, idempotency key, outbox row. Return 202.
    4. Draw the saga: reserve stock, authorise payment, assign courier, confirm, with a compensation for each.
    5. Name the three duplicate defences: idempotency key at the edge, guarded state updates in the orchestrator, idempotent consumers downstream.
    6. Discuss the hot stock row and the cancel race.
    7. Close with failure modes, the dead-letter path and what you would monitor: stuck orders by state, consumer lag, outbox backlog, compensation failures.

    In practice: operating the order system

    This is a realistic scenario, not a case history. It describes an educational reference design, and every number is an illustrative assumption.

    The situation

    ShopStream runs a "free delivery weekend" promotion. Checkouts rise from the usual peak of about 58 per second to roughly twice that for 20 minutes. Support reports that some shoppers see "Placing your order" for several minutes, and a few orders show as paid but never confirmed.

    Starting architecture

    The design above: checkout with an outbox, an orchestrated saga, a payment gateway contract of 40 authorisations per second, 12 partitions on order-events, holds that expire after 10 minutes, and a saga deadline of 10 minutes.

    Options considered

    • Raise the payment concurrency. Fast, but the gateway contract is the ceiling; going above it risks throttling errors.
    • Skip the saga for the weekend and charge synchronously. Removes the stall but reintroduces double charges on retries and couples checkout latency to the gateway.
    • Keep the saga, make the backlog visible and bounded. Alert on queue age, cap the payment queue, and shed excess checkouts with a clear message and a retry hint.

    The decision

    Keep the saga and bound the backlog. The payment command queue gets a maximum size of 2,400 messages, which is the 60 seconds of work a shopper tolerates at 40 per second. Beyond it, checkout answers 503 with a retry hint rather than accepting orders that would wait longer than the shopper will. The deadline job compensates anything stuck past 10 minutes.

    Rollout and verification

    Before the next promotion, replay a synthetic load at twice the peak against a staging copy and watch four numbers: oldest message age in the payment queue, orders per state, consumer lag per group, and compensation success rate. Verify that duplicate delivery of every event type leaves the order in the same state, by injecting duplicates in the test environment. Verify that void and release are idempotent by calling them twice.

    The 2 a.m. failure

    At 02:10 the alert "orders in PAYMENT_AUTHORISED older than 5 minutes" fires. The courier service is down, so AssignCourier retries until its window ends, and 300 orders start compensating at once. The compensation traffic hits the payment service, which is already near its limit, so voids queue up and funds stay held. The runbook says: pause new courier-dependent checkouts (a feature flag), let compensation drain, and confirm that the count of orders in COMPENSATING falls to zero. Then check the NEEDS_REVIEW queue. The lesson: compensation is real load, and it must have its own capacity and its own alert.

    Architect's notes

    • Name the invariants before the components. "Never charge twice, never lose an accepted order, never oversell beyond policy." Every component then has a job: it protects one invariant.
    • The orchestrator holds sequence, not business rules. If it starts deciding prices or eligibility it becomes the monolith you split away from.
    • A guarded update is the cheapest idempotency tool you have. It needs no extra table and works under duplicates and races alike.
    • Design the unhappy ending first. A cancelled order that leaves no charge and no hold is the proof the system works.
    • Make states visible to the shopper. "Placing your order" is honest. A spinner that hides a saga is not.

    Common mistakes

    • Calling stock, payment and delivery from the checkout request, so any slow dependency fails checkout.
    • Check-then-decrement on stock instead of one guarded statement.
    • Publishing to the broker after the database commit, with no outbox.
    • Using the broker's delivery guarantee as the only duplicate protection, with no idempotent consumers.
    • Treating a compensation as a rollback that cannot fail.
    • Having no deadline on the saga, so stuck orders and held stock are discovered by customers.
    • Reading lists from the read model immediately after placing an order and showing the shopper an empty history.

    Key takeaways

    • An order system is a durable state machine; checkout records intent in one local transaction and returns 202.
    • Use an idempotency key at the edge, guarded state updates in the orchestrator and idempotent consumers downstream.
    • Reserve stock with one atomic guarded statement and an expiring hold; decide hard versus soft reservation explicitly.
    • A saga trades isolation for availability; each step needs a retryable compensation and every state needs a deadline.
    • Order events keyed by order id keep one order's steps ordered while orders run in parallel.
    • Scale the real bottlenecks: hot stock rows and the payment gateway, not the order table.

    Practice exercises

    1. (20 minutes) Write the guarded UPDATE statements for three transitions of the order state machine and say what a zero row count means for each.
    2. (30 minutes) Add a RESERVED_PENDING_SUBSTITUTION state for items the picker cannot find. List the new transitions, the compensation and the events.
    3. (30 minutes) Design the bucketed stock counter for a flash-sale item with 1,000 units. How do you choose a bucket, what happens when one empties, and how do you report the remaining total?
    4. (20 minutes) A courier is assigned at the same instant the shopper cancels. Walk through both orderings and show that each ends in a consistent state.
    5. (40 minutes) Decide which three metrics you would put on the order dashboard and what alert threshold each gets, with one sentence of reasoning per threshold.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments