Skip to content

    Frontend System Design

    Front-End Case Study: E-Commerce Storefront

    Design the front end of an online store: cart, checkout state, price and stock freshness, caching per page, and an order that is placed once, with a tested lab.

    By Published 19 min read

    • frontend-system-design
    • case-study
    • e-commerce
    • checkout
    • caching
    Share

    What you'll learn: By the end of this case study you will be able to design the front end of an online store from requirements to rollout: choose a rendering and caching strategy for each page type, keep money exact, decide who owns the cart, treat price and stock on screen as claims that expire, model checkout as a state machine, place an order exactly once when a reply is lost, announce changes to assistive technology, and explain each decision as a trade-off. A lab with a pure TypeScript core and a thin React layer backs the key rules.

    Think of a shop assistant filling a basket for you while the shelf labels are being changed. The label you read a minute ago may no longer be right, the last tin may have gone to the person ahead of you, and if you hand over money twice because the till froze, you want one receipt, not two. A storefront front end is that assistant: it must be fast while you browse, honest at the till, and careful about what it promises in between.

    This is an educational reference design, not the verified internal architecture of Amazon or any other company. It uses generic parts and the shared ShopStream grocery marketplace from the back-end project course. All numbers, time limits and prices in it are illustrative. It follows the method of the Front-End Case Study Method lesson: requirements, constraints, architecture, deep dives, failure, then a decision record.

    The core idea

    1. Treat every number on screen as a claim with an age. A price or a stock count was true when the server computed it. The page may show it, but only the server may commit to it.
    2. Browsing is cheap and cached; checkout is exact and uncached. The same product can be served from an edge cache on the listing page and priced fresh at the moment of purchase.
    3. Make state transitions explicit. Cart edits and checkout steps are events handled by pure functions, so the rules can be tested without a browser.
    4. Safe retry is a design requirement. On a network, a lost reply and a lost request look the same, so the order call must be repeatable without a second order.

    Requirements and constraints

    Functional. Browse and search products, view a product, add to a cart, edit the cart, check out (address, delivery, payment), see an order confirmation, and recover when something changes.

    Non-functional (illustrative targets). The listing and product pages should be indexable and fast on a mid-range phone. The cart must survive a reload. A shopper must never be charged for a price they did not see, and never be charged twice. Prices and stock may be slightly old while browsing, but not at the till.

    Constraints that shape the design.

    • Traffic is spiky and mostly reads. Many people browse for each one who buys, so the read path is cached and the write path is small and protected.
    • Ownership. The catalog, inventory, pricing, orders and payments are different back-end services. The front end composes them and must not guess their rules.
    • Money. Totals involve rounding, tax and currencies. A wrong total is a trust problem, and the front end only displays totals the server will honour.
    • Accessibility and SEO. Product pages are search landing pages and checkout must work with a keyboard and a screen reader.

    Illustrative traffic shape for the rest of the lesson: of 1,000 sessions, about 600 see a product page, 80 add to a cart, 30 start checkout and 20 place an order. These are made-up figures to size the effort, not a benchmark.

    Architecture overview

    The front end is the composition layer between the shopper and ShopStream's services (see ShopStream Stage 2 for the read path, Stage 5 for the order pipeline and Stage 6 for payments). A thin server layer shaped for this client, the pattern in The Backend for Frontend (BFF) from the Client's Side, gathers what a screen needs.

    Figure 1. Storefront front end and the services behind it

    Storefront front end: edge cache for browsing, services for cart, stock, price and ordersStorefront UI to Edge cache (browse); Storefront UI to Storefront server (cart, checkout); Edge cache to Catalog (fill); Storefront server to Inventory (quote); Storefront server to Cart (read, write); Storefront server to Orders (place order); Orders to Payments (authorise)EDGEBACK-END SERVICESStorefront UI: cart and checkout stateStorefront UIcart and checkoutstateEdge cache: listing, product pagesEdge cachelisting, productpagesStorefront server: composes callsStorefrontservercomposes callsCatalog: titles, images, priceCatalogtitles, images,priceInventory: stock, holdsInventorystock, holdsCart: per shopperCartper shopperOrders: idempotent placeOrdersidempotent placePayments: gateway, ledgerPaymentsgateway, ledgerbrowsecart, checkoutfillquoteread, writeplace orderauthorise

    How to read this: the top lane is browsing, served from an edge cache that fills from the catalog. The lower lanes are the exact path: the storefront server asks inventory and the cart service, and places the order. Payment is reached from the order service, never directly from the browser.

    Rendering and caching per page type

    Different pages have different freshness needs, so no single strategy fits (Choosing a Rendering Strategy Per Page gives the method).

    Page Audience What may be stale Strategy
    Category listing Everyone, search engines Minutes (price and stock hints) Pre-rendered or cached at the edge, refreshed in the background
    Product page Everyone, search engines Short (price) Cached HTML shell and static facts; price and stock refreshed client-side
    Cart One shopper Nothing, once checkout starts Not cached; read from the cart service
    Checkout One shopper Nothing Not cached; every figure confirmed by the server
    Order confirmation One shopper Nothing Not cached; read after the order is stored

    Two HTTP facts support this table. A response with Cache-Control: private may be stored only in a private cache such as a browser's; MDN advises private for user-personalised content, and warns that forgetting it can let a shared cache store and reuse a personalised response for several users. And no-store tells caches of any kind not to store a response, while no-cache still allows storing but requires validation before each reuse (HTTP Caching for the Front End covers the full model). A cart response is personal: it must never come from a shared cache.

    For the listing and product pages, stale-while-revalidate lets a cache reuse a stale response while it fetches a fresh one. RFC 5861 defines it: a cache may serve the stale response after it becomes stale, should revalidate without blocking, and should not keep serving it stale. The shopper gets a fast page, and the next shopper gets a newer one. The cost is that a price on a cached page can be older than the product database. That is acceptable for browsing and not for buying, which is why the price is refreshed on the client and re-checked on the server. Incremental Static Regeneration and On-Demand Revalidation and CDN and Edge Caching From the Browser's Side describe the mechanisms, and SEO Architecture for Web Apps explains why the product page must still contain its main facts in the HTML a crawler receives.

    Illustration 1: the minimal example, an age becomes an action

    The lab models one rule: the action depends on the figure's age and on the moment it is used. These limits are illustrative:

    Age of the figure Class While browsing In the cart When placing
    10 s fresh show show ask the server
    120 s stale show with a hint refetch ask the server
    400 s expired refetch refetch ask the server

    The last column does not depend on age at all. At the moment of purchase the screen's figure is not an input to the decision; it is only what the shopper agreed to.

    Money: exact numbers on a screen

    JavaScript numbers are double-precision floating point. MDN documents that they represent integers exactly only up to Number.MAX_SAFE_INTEGER, which is 2^53 minus 1 (9,007,199,254,740,991). Decimal fractions are worse: many cannot be stored exactly, so arithmetic on prices drifts. The lab's first demo section shows it from a real run: 0.1 + 0.2 prints 0.30000000000000004 and 4.35 * 100 prints 434.99999999999994.

    The rule is to hold money as an integer count of the smallest unit (cents here, an illustrative single currency with two decimals) and format only at the edge. A real product reads the number of decimals from its currency data, because some currencies have none. MDN's Intl.NumberFormat example shows the Japanese yen formatted with no minor unit. For amounts that could pass the safe integer limit, use BigInt, which the banking case study does. Two more rules follow:

    • Derive totals, never store them. The subtotal is computed from the lines each render. A stored total can disagree with its lines.
    • The displayed total is not authority. Tax, shipping, discounts and rounding rules belong to the server, and the screen shows what the server returned (Derived and Normalized State explains why).

    The cart: who owns it

    There are three places a cart can live, and the design choice is a trade-off.

    Where Gain Cost
    Only in the browser (local storage) Works for guests, no back end Lost on another device; prices and stock go stale silently
    Only on the server One truth across devices and tabs Needs an identity even for guests; a network round trip per edit
    Both: server cart with a local copy Instant UI, survives reload and device change You must merge and resolve conflicts

    The ShopStream back-end course keeps the cart in the database, so the reference design uses the third option: the server cart is the record and the front end holds an optimistic copy. A guest gets an anonymous cart that is merged into the account cart at sign-in. The merge rule is a product decision: for the same product, sum or keep the larger quantity, and tell the shopper what happened. Edits are applied at once and reconciled with the server's answer, as in Optimistic Updates and Rollback. A second tab should see the change: Cross-Tab Sync With BroadcastChannel and State Persistence and Synchronization cover how, and why a saved cart from an older build needs a version and a migration.

    The shape of the cart state

    The lab's CartState is two lists: lines and issues. A line holds the SKU, the quantity, and the unit price the shopper saw, with the time it was seen. issues is the result of the last comparison with the server. The reducer handles add, setQty, remove, revalidated and acceptChanges. Any edit to the lines clears issues, because an old comparison no longer describes the cart. React's useReducer documentation requires a reducer to be pure and not to mutate state, and says Strict Mode calls it twice in development to expose accidental impurity; the lab's tests check that the reducer leaves its input state unchanged.

    Price and stock freshness

    When the shopper reaches the cart or checkout, the front end asks the server for a fresh quote for every SKU in the cart: the current unit price and the units available. It then compares; it does not silently fix. There are three outcomes per line.

    • Price changed. Show the old and new price and block checkout until the shopper accepts.
    • Stock short. Show how many remain. Accepting caps the quantity at the stock.
    • Unavailable. Show the line as no longer available. Accepting removes it.

    Figure 2. Freshness along the path from browse to order

    Freshness: price and stock are claims at browse time and commitments only at the serverCached page to Cart screen (add to cart); Cart screen to Quote call (quote, compare); Cart screen to Place order (agree); Place order to Server check (decides)Cached page: price may be oldCached pageprice may be oldCart screen: compares with quoteCart screencompares withquoteQuote call: price, stock nowQuote callprice, stock nowPlace order: agreed total sentPlace orderagreed total sentServer check: price, stock, keyServer checkprice, stock, keyadd to cartquote, compareagreedecides

    How to read this: a figure on a cached page is only a hint. The cart screen compares it with a fresh quote and shows the differences. Even after the shopper agrees, the server repeats the check when the order is placed.

    The second check exists because time passes between the quote and the click. In the lab's fifth demo section the shopper agreed to a total, the price moved, and the server answered 409 with reason price-changed and placed no order. MDN describes 409 Conflict as a conflict with the current state of the target resource, which is what this is. HTTP Methods, Status Codes and Headers a Front End Relies On covers status code use.

    Illustration 2: the realistic example, a price moves while the item sits in the cart

    The shopper adds two kettles at $19.99. The price is raised to $21.99. At the cart, the quote shows the change:

    issue:      Kettle: price changed from $19.99 to $21.99
    compared:   subtotal still $39.98, can check out: false
    accepted:   subtotal $43.98, can check out: true

    Notice subtotal still $39.98: comparing changes nothing. The shopper sees the difference and decides. Silently updating the price would be convenient and wrong, because the shopper would pay a number they never saw. The lab's full output is in the next section.

    What the screen says: announcing changes

    A price change that appears in the DOM is invisible to a screen reader unless it is announced. WCAG 2.2 success criterion 4.1.3 (Status Messages, level AA) requires that status messages can be programmatically determined through role or properties so they can be presented without receiving focus; the Understanding document uses a shopping cart count as an example. The practical pattern is a region with role="status", which MDN says has an implicit aria-live of polite and aria-atomic of true. The lab puts the issues and the order result in one such region. The same document lists role="alert" on content that is not important or time-sensitive as a failure, so an out-of-stock notice is a status message and a failed payment is the kind of error an alert is for. See Accessibility Fundamentals and WCAG and Cumulative Layout Shift and Layout Stability (a price banner that pushes the buy button down at the wrong moment is a layout-shift bug and a mis-click bug).

    Checkout as a state machine

    Checkout has steps, forbidden moves and a dangerous moment (placing the order). A state machine makes them explicit (Finite State Machines for UI is the background).

    Figure 3. Checkout states

    stateDiagram-v2 accTitle: Checkout state machine accDescr: The shopper moves from cart to details to review. Place order moves review to placing. While placing, a second click changes nothing. A reply of created moves to confirmed. A refusal or a lost reply moves to failed with a reason. From failed after a lost reply, try again returns to placing with the same key. After a refusal the shopper goes back to review. [*] --> cart cart --> details: begin details --> review: details done review --> placing: place order placing --> placing: second click ignored placing --> confirmed: order created placing --> failed: refused or reply lost failed --> placing: try again after lost reply failed --> review: back after refusal confirmed --> [*]

    How to read this: the loop on placing is the double-click guard. failed has two exits because the two kinds of failure are different: a lost reply means "I do not know", a refusal means "no".

    The lab's checkoutReducer returns the same state object for a second place while placing, which a test asserts. The component adds a synchronous in-flight flag, because two clicks in the same tick are handled before React renders the disabled button. Each guard covers a gap the other leaves.

    Entering checkout also requires canCheckout(cart): lines exist and no unresolved issue remains. That rule is one pure function, tested without a DOM.

    Placing the order exactly once

    The dangerous moment is the order call. If the request is sent and the connection drops before the reply, the client cannot tell whether the order was placed. A plain retry might create a second order; no retry might leave the shopper unsure. The fix is an idempotency key: the client generates a unique value for one intended order and sends it with every attempt. The server stores the key with the result, and a repeat returns the stored result.

    Two documents describe the practice. Stripe's API documentation says that for its v1 API the status code and body of the first request made with a key are saved, retries return the saved response (including a 500), keys are generated by the client (it suggests V4 UUIDs), and the layer errors if a retry's parameters differ from the original. An IETF Internet-Draft for an Idempotency-Key header (an active draft, not an RFC, at the time of writing) says the key must be unique and must not be reused with a different payload, and that a server should answer 422 when it is. Idempotency Keys and Safe Retries is the server-side treatment and ShopStream Stage 6 applies it to payment.

    Figure 4. A lost reply, then a safe retry

    sequenceDiagram accTitle: Retry with the same idempotency key after a lost reply accDescr: The shopper presses place order. The browser sends the order with key k-1. The server creates the order, but the reply is lost. The browser shows that it could not confirm and offers try again. On retry it sends the same key k-1 with the same order. The server recognises the key and returns the stored result. One order exists. participant S as Shopper participant B as Browser participant V as Order service S->>B: Place order B->>V: POST order, key k-1 V->>V: create order ord-1, store key V--xB: reply lost B->>S: Could not confirm. Try again is safe. S->>B: Try again B->>V: POST order, key k-1 (same order) V-->>B: 201 ord-1 (stored result) B->>S: Order placed

    How to read this: the cross on the return arrow is the lost reply. The retry carries the same key and the same order, so the server answers with the stored result instead of creating another order.

    Illustration 3: the failure case, the reply is lost

    In the lab's fourth demo section the server carries out the order and the reply is dropped. The client sees only a network error, while the server already holds one order. The retry reuses k-1:

    network:    network: reply lost; server orders so far: 1
    retry:      key k-1, reply {"status":201,"orderId":"ord-1","replayed":true}, server orders: 1

    The word replayed is the server saying "I have seen this key". The shopper is told that trying again will not charge them twice, and that sentence is true only because of the key.

    When may the client reuse the key? Only for the same order after a lost reply. After a definite refusal (price changed, out of stock, declined) the cart or its prices have changed, so the next attempt is a different order and needs a new key. The lab's chooseKey function encodes this, and the server rejects a reused key with a different order using 422.

    Build it: the cart and checkout core

    Goal. Run the storefront's rules as tests and as a printed trace: integer money, cart comparison against the server, the checkout machine, the lost reply, and the freshness table.

    Setup. The lab is storefront-cart-checkout in the course's example workspace (Node 26.13.1, pnpm). The rules are pure TypeScript; one React component (Storefront.tsx) is a thin layer over them and is tested in jsdom, which is a model of the DOM and not a browser.

    cd examples/frontend
    pnpm install
    cd labs/storefront-cart-checkout
    pnpm test           # 36 tests
    node src/demo.ts

    Steps.

    1. Run the tests. Open test/core.test.ts and read the revalidation group: a comparison reports issues and edits nothing.
    2. Run the demo and compare it with the output below.
    3. In section 4, follow the key: the first click makes placing, the second click returns the same state object, the lost reply leaves one order on the server, and the retry uses k-1 again and gets the stored answer.
    4. Optional: in chooseKey always return freshKey, watch the lost-reply test fail, then restore it.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    Storefront cart and checkout: money, freshness, retries
    
    === 1. Money: floats against integer cents
    float:   0.1 + 0.2 = 0.30000000000000004
    float:   4.35 x 100 = 434.99999999999994
    cents:   parseCents("4.35") = 435; 3 x 1999 = 5997 -> $59.97
    format:  $1,234,567.89 | $0.05 | -$1.50
    
    === 2. The price moves after the item was added
    added:      subtotal $39.98, can check out: true
    issue:      Kettle: price changed from $19.99 to $21.99
    compared:   subtotal still $39.98, can check out: false
    accepted:   subtotal $43.98, can check out: true
    
    === 3. Stock runs short, then runs out
    issue:      Mug: only 2 left, you asked for 3
    issue:      Mug: no longer available
    accepted:   0 lines left
    
    === 4. The reply is lost, the shopper clicks again
    click 1:    step=placing
    click 2:    step=placing, same state object: true
    network:    network: reply lost; server orders so far: 1
    retry:      key k-1, reply {"status":201,"orderId":"ord-1","replayed":true}, server orders: 1
    same key, different order: {"status":422,"reason":"key-reused-with-different-order"}
    stock left: 4
    
    === 5. The shopper agreed to an old total
    server:     {"status":409,"reason":"price-changed","currentTotalCents":2199}; orders: 0
    
    === 6. What the screen does with an old figure (illustrative limits: fresh 60 s, stale 300 s)
    age        class     browsing        cart            placing
    10 s       fresh     show            show            ask-server
    120 s      stale     show-with-hint  refetch         ask-server
    400 s      expired   refetch         refetch         ask-server

    What the lab does not show: a real browser, real network timing, a payment provider, tax or currency rules, or any real storefront platform. The fake server stands in for the services in Figure 1.

    Trade-offs

    Decision Gain Cost
    Cache listing and product pages at the edge Fast, cheap, indexable Price and stock may be old; needs refresh and purge
    Refresh price on the client Fresher number on a cached page A visible change after load; layout shift if unplanned
    Compare, do not auto-fix, at the cart The shopper sees and accepts changes One more step on a bad day
    Server cart with a local copy Cross-device, survives reload Merge rules and conflict handling
    Idempotency key on place order Safe retry after a lost reply Server must store keys and compare payloads
    Checkout as a state machine Illegal moves cannot happen More up-front modelling

    In practice: the cart that charged an old price

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront redesigns checkout. Support reports two kinds of complaint: shoppers who saw one price in the cart and a different total on the confirmation, and shoppers who pressed Pay on a slow connection and later found two orders. The team has a mobile-heavy audience and a sale starting in a week.

    Starting architecture

    Figure 5. Before: cart total trusted, order button not guarded

    Before: the cart total comes from the page, and the pay button can be pressed twiceStorefront UI to Server (total, items); Server to Orders (create)Storefront UI: stored totalStorefront UIstored totalServer: no key, no compareServerno key, nocompareOrders: creates each timeOrderscreates each timetotal, itemscreate

    How to read this: the warning boxes are the two gaps. The total is a stored value from when items were added, and the order call can be repeated by a retry or a second tap.

    Options considered

    Option What it fixes What it costs Risk
    Refresh the cart every few seconds Fewer stale prices Load and flicker Still wrong at the moment of purchase
    Disable the button after the first tap Most double taps Little A lost reply leaves the shopper stuck with no safe retry
    Quote at the cart, compare, and send a key with the order Both complaints A quote call, a state machine, a key store More states to test

    The decision

    Field Decision record
    Context Price and stock drift between add and pay; replies can be lost; a sale will raise both.
    Decision Derive totals from lines; quote and compare at cart and review; block checkout until changes are accepted; model checkout as a state machine; send an idempotency key with the order, reused only after a lost reply for the same total; announce changes in a status region.
    Consequences, good The shopper pays only a total they saw; a retry cannot create a second order.
    Consequences, bad One more screen state on bad days; the server must store keys and compare payloads.
    Revisit when A promotion engine makes totals depend on more than the lines, or the order service changes its error codes.

    Rollout and verification

    1. Ship behind a feature flag to a small share of sessions and compare complaint rates and conversion with the old flow (Feature Flags and A/B Testing covers the method).
    2. Test the schedules, not just the happy path: price change after add, stock to zero, reply lost, two taps in one tick, a retry after a refusal.
    3. Throttle the network in a staging browser and press Pay repeatedly; confirm one order.
    4. Watch the signals that the change should move: price-changed refusals, retries that replayed a stored result, orders per key.

    The 2 a.m. failure

    During the sale the order service starts answering 422 for some retries. The cart was edited between the failed attempt and the retry, but the client reused the old key because it only checked "was the last failure a network error" and not "is this the same total". The key-reuse rule in the lab compares the total as well, and the server compares the order.

    First three checks: (1) look at the 422 responses and the keys they carry; (2) check whether the cart changed between the two attempts; (3) check the client's key-reuse condition. Mitigation: start a new key for any attempt after an edit. Follow-up: add a test that edits the cart between a lost reply and the retry, and expects a new key.

    The other side of this topic

    The back end owns the guarantees this front end leans on: inventory holds that expire, an order pipeline that reacts to the new order, and a ledger that records money. See ShopStream Stage 5 and Stage 9. The front end's job is to ask at the right time, show what changed, and retry safely.

    Architect's notes

    • Freshness is a per-moment policy, not a per-page setting. The same price is "show" on a listing and "ask the server" at purchase.
    • Make the server the only judge of a total. The screen can present and compare; it cannot commit.
    • Keep the reducers pure and the components thin. The lab's React file has no rule that a test cannot reach without a DOM.
    • Treat a lost reply and a refusal differently, in state, in text and in the key.
    • Budget for the bad day. The extra states are rare for each shopper and common across a sale.

    Common mistakes

    • Adding prices as floats, or storing a total next to its lines.
    • Silently changing a price in the cart, so the shopper pays a number they never saw.
    • Caching a personalised cart response in a shared cache.
    • Disabling the pay button and calling that safe, with no key and no answer for a lost reply.
    • Reusing an idempotency key after the order has changed.
    • Announcing changes only visually, so a screen reader user never learns the total moved.

    Key takeaways

    • Treat on-screen price and stock as claims with an age; the server commits.
    • Cache browsing pages; do not cache cart or checkout responses.
    • Hold money as integers and derive totals from lines.
    • Compare a fresh quote with the cart and let the shopper accept changes.
    • Model checkout as a state machine with a guard on placing.
    • Send an idempotency key with the order; reuse it only after a lost reply for the same order.
    • Announce changes with a status region.

    Practice exercises

    Exercise 1: Starter (30 min). Add a test where the quantity of one line is edited after a comparison, and state what happens to issues. Then add a case for a negative quantity.

    Exercise 2: Intermediate (2 hours). Design the guest-to-account cart merge: write the rule for the same SKU in both carts, the message the shopper sees and the test that proves the rule.

    Exercise 3: Advanced (half day). Extend the fake server with a stock hold that expires after a time limit and add a checkout state for "hold expired". Decide what the screen says and what the key does.

    In this course:

    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