Design an E-commerce Product Page and Checkout

A frontend system design guide for the two pages that make an online store money. You will learn how to make the product page fast and searchable, and how to build a checkout that never charges twice.

Frontend system design · Commerce and forms

Design a product page that loads fast and ranks well. Then design a cart and checkout that stay correct across tabs, devices, retries, and payment failures.

Correctness contract: The user never pays for an order twice because of a retry or a double click. The price and stock shown at the final step match what the server will charge. Raw card numbers never touch our own JavaScript. Every cart change the UI confirmed is saved on the server.

You know HTML, React or a similar framework, and HTTP. You do not need to know payments in depth. Amazon and Shopify stores are used only to frame the problem. This is a teaching design. Numbers are rough estimates for reasoning.

E-commerce is a frontend interview favourite because every decision has a visible business cost. A slow product page loses sales. Retailers have reported that each 100 ms of extra load time costs a measurable share of conversion. A product page that search engines cannot read loses free traffic. A buggy cart loses trust. A checkout that double charges creates support tickets and chargebacks. The design must balance three forces: static speed for the parts that rarely change, live accuracy for price and stock, and strict correctness for money. This guide covers the product page first, then the cart, then the checkout, and ends with performance budgets, experiments, and analytics.

Contents

  1. Concepts to understand first
  2. 1. Clarifying questions and requirements
  3. 2. Scope and budgets
  4. 3. High-level architecture
  5. 4. Data model
  6. 5. Interface and API
  7. 6. Deep dive: rendering for SEO and speed
  8. 7. Deep dive: variants, inventory freshness, and price
  9. 8. Deep dive: cart state across tabs and devices
  10. 9. Deep dive: checkout form, payments, and idempotent submit
  11. 10. Deep dive: performance budgets, experiments, and analytics
  12. 11. Failure modes
  13. 12. Trade-offs
  14. 13. 45-minute interview walkthrough
  15. 14. Summary
  16. 15. Common mistakes
  17. Worked example: a double click on Place order
  18. Code lab: idempotent order submit with retries
  19. Check yourself
  20. Key terms
  21. Further reading

Concepts to understand first

SSR, SSG, and ISR

Server-side rendering (SSR) builds HTML per request. Static site generation (SSG) builds HTML once at deploy time. Incremental static regeneration (ISR) serves cached static HTML and rebuilds it in the background after a set time or on demand.

Example. A product page is built with ISR and a 5 minute revalidate time. The CDN serves it in 30 ms. Price and stock load as a small live request after.

Limit. Static HTML can be stale. Never trust it for the final price or stock. Personal data, like a logged-in user's cart, cannot go into shared cached HTML.

Hydration and islands

Hydration attaches JavaScript event handlers to server HTML. Islands architecture hydrates only the interactive parts, like the variant picker and Add to cart button, and leaves static text as plain HTML.

Example. The description and reviews are static. Only 3 islands hydrate: gallery, variant picker, and cart button. JavaScript drops from 400 KB to 120 KB.

Limit. Islands need a way to share state, such as the selected variant between the picker and the gallery.

Idempotency key

An idempotency key is a unique ID the client sends with a request that must not run twice. The server stores the key with the result. A repeat with the same key returns the stored result instead of running again.

Example. The client sends POST /orders with Idempotency-Key: 7d1e.... The response is lost. The client retries with the same key and gets the same order ID back.

Limit. The key must be created once per checkout attempt, not once per click. The server must also check that the repeat has the same body.

PCI DSS scope

PCI DSS is the security standard for systems that handle card data. If card numbers pass through your page's JavaScript, your whole frontend is in scope. Hosted payment fields in an iframe from the payment provider keep the card data out of your code.

Example. Stripe Elements or Adyen hosted fields render the card input inside an iframe from their domain. Your page only receives a token.

Limit. The page that hosts the iframe still matters. A malicious script on it can fake the form. PCI DSS 4.0 asks you to control and monitor scripts on payment pages.

Core Web Vitals

Core Web Vitals are Google's user-centred speed metrics. Largest Contentful Paint (LCP) measures loading. Interaction to Next Paint (INP) measures responsiveness. Cumulative Layout Shift (CLS) measures visual stability.

Example. Good targets at p75 are LCP under 2.5 s, INP under 200 ms, and CLS under 0.1.

Limit. Lab tests on a fast laptop hide real pain. Use field data from real users, split by device class.

Product, variant, and SKU

A product is the thing you browse, like "Trail Running Shoe". A variant is one buyable combination of options, like size 42 and colour blue. Each variant has a SKU (stock keeping unit), its own price, and its own stock.

Example. 3 colours and 10 sizes make 30 variants. Only 22 exist in the catalogue, and 5 of those are out of stock.

Limit. Not every option combination exists. The picker must show which choices lead to a real, in-stock variant.

1. Clarifying questions and requirements

Functional requirements

Non-functional requirements

2. Scope and budgets

Traffic and caching

Page weight budget

LCP budget on 4G

Frame budget

Selecting a variant must update price, image, and stock within one interaction. Aim to paint the new selection within 100 ms. Keep the variant computation under 5 ms and avoid re-rendering the whole page. Only the price block, the gallery, and the picker should update.

3. High-level architecture

E-commerce architecture: the CDN serves cached product HTML built by an SSR or ISR server, the product page fetches live price and stock, the cart store calls the commerce API, persists the cart ID, and broadcasts changes to other tabs, and analytics events go to a third-party SDK.
Figure 1. Product page and cart. Static HTML comes from the CDN. Live data and cart writes go to the commerce API.

Layers

Intuition

Split the page by how fast each piece of data changes. Description and images change weekly, so cache them hard. Price changes hourly, so cache it briefly. Stock changes by the second, so fetch it live. Your cart is personal, so never put it in shared cache.

4. Data model

type Product = {
  id: string; slug: string; title: string; brand: string
  descriptionHtml: string                 // sanitized on the server
  options: { name: 'color' | 'size' | string; values: string[] }[]
  variantIds: string[]
  mediaByColor: Record<string, string[]>  // image ids per colour
  rating: { avg: number; count: number }
}

type Variant = {
  id: string; sku: string; productId: string
  options: Record<string, string>         // { color: 'blue', size: '42' }
}

type Offer = {                            // live data, short TTL
  variantId: string
  price: { amount: number; currency: string }   // amount in minor units, e.g. cents
  compareAt?: { amount: number; currency: string }
  stock: 'in_stock' | 'low' | 'out_of_stock' | 'preorder'
  fetchedAt: number
}

type CartLine = { lineId: string; variantId: string; qty: number
                  unitPrice: { amount: number; currency: string } }

type Cart = {
  id: string; version: number             // server increments on each change
  lines: CartLine[]
  subtotal: { amount: number; currency: string }
  warnings: { lineId: string; code: 'PRICE_CHANGED' | 'OUT_OF_STOCK' | 'QTY_REDUCED' }[]
}

type CheckoutDraft = {
  id: string; cartVersion: number
  step: 'contact' | 'shipping' | 'method' | 'payment' | 'review'
  email?: string
  address?: Address
  shippingMethodId?: string
  totals?: { subtotal: number; shipping: number; tax: number; total: number; currency: string }
  idempotencyKey: string                  // made once per order attempt
}

type ClientState = {
  products: Record<string, Product>
  variants: Record<string, Variant>
  offers: Record<string, Offer>          // keyed by variantId
  selection: Record<string, string>      // current picker choice
  cart: Cart | null
  checkout: CheckoutDraft | null
}

Store money as integers in minor units. Floating point sums like 0.1 plus 0.2 give 0.30000000000000004. Format money only at render time with Intl.NumberFormat and the right currency. The cart has a version so tabs and devices can tell whether their copy is current.

5. Interface and API

Catalogue and offers

Cart

Checkout and orders

Component props

<VariantPicker
  options={product.options}
  variants={variantList}
  offers={offersByVariant}
  value={selection}
  onChange={(next) => setSelection(next)}
/>

<AddToCartButton variantId={selectedVariant?.id} disabled={!canBuy} />

<PaymentFields provider="stripe" onToken={(t) => setPaymentToken(t)} onError={showError} />

6. Deep dive: rendering for SEO and speed

Choosing the rendering mode

SEO details that matter

Loading the hero image fast

The hero image is almost always the LCP element. Put it in the HTML as a plain <img> with srcset and sizes so the browser picks the right width. Add fetchpriority="high" and never loading="lazy" on it. Set width and height or aspect-ratio so the layout does not shift. Lazy load the other gallery images and everything below the fold. Serve AVIF with a WebP fallback through an image CDN.

Mistake

Rendering the hero image from a JavaScript carousel that mounts after hydration. The browser cannot discover it until the bundle runs, and LCP moves from 1.2 seconds to 3 or 4 seconds.

Hydration cost

Hydrating a full product page can block the main thread for 300 ms or more on a mid-range phone. A tap on Add to cart during that time feels dead, and INP suffers. Use islands or partial hydration. Hydrate the Add to cart button and picker first. Hydrate reviews and recommendations when they scroll into view with an IntersectionObserver, or when the browser is idle.

7. Deep dive: variants, inventory freshness, and price

Variant picker state

The selection is a map from option name to value. The selected variant is derived, never stored separately. Find the variant whose options match the selection exactly. If none matches, there is no buyable variant yet.

The picker must also show which values are still possible. For each option value, ask: if the user picked this value while keeping the other choices, would a real in-stock variant exist? Values that lead to no variant are disabled. Values that lead only to sold-out variants are shown crossed out but still selectable, so users can see "notify me". With 30 variants this is a few hundred checks, well under 1 ms. Precompute an index from option pairs to variants if the product has thousands of variants.

Inventory freshness

Stock in cached HTML can be minutes old. During a sale, a size can sell out in seconds. The design uses three levels of freshness.

  1. Page load. The HTML shows stock from build time as a hint. The live offers call replaces it within about 200 ms.
  2. While browsing. Refetch offers when the tab becomes visible again after more than 60 seconds. During flash sales, poll every 15 to 30 seconds or subscribe through Server-Sent Events with EventSource for hot items.
  3. At commit. The server checks stock again on add to cart, at checkout start, and when placing the order. Only this check is the truth.

Show "Only 3 left" only when the number is fresh, for example fetched in the last 30 seconds. A stale scarcity message is both wrong and a trust problem.

Price display

8. Deep dive: cart state across tabs and devices

Server cart as the source of truth

Keep the cart on the server, keyed by a cart ID. Guest users get the ID in an HttpOnly cookie. Signed-in users have a cart tied to their account. The client holds a cached copy with its version. This gives devices a shared cart and makes the server's stock and price checks possible.

Optimistic add to cart

  1. The user taps Add to cart. The button shows a pending state and is disabled to stop double adds.
  2. The client adds a temporary line to the local cart and opens the cart drawer at once.
  3. It sends POST /api/cart/lines. The server checks stock and price and returns the full cart with a new version.
  4. The client replaces its local cart with the server cart. If the server reduced the quantity or rejected the item, the drawer shows a clear message.
  5. On network failure, roll back the temporary line and show a retry button.

Syncing tabs

A user may have the product page open in one tab and the cart in another. After each confirmed change, post { type: 'cart-changed', version } on a BroadcastChannel('cart'). Other tabs compare versions and refetch if theirs is older. As a fallback for older browsers, write the version to localStorage and listen for the storage event, which fires in other tabs. Also refetch on visibilitychange when a tab becomes visible, which covers changes made on other devices.

Guest to signed-in merge

A guest adds 2 items, then signs in. Their account already has 1 item from last week on another device. Call POST /api/cart/merge. The server combines lines by variant, caps quantities by stock and per-customer limits, and returns warnings. The UI shows a short note like "We added 1 item from your last visit". Never silently drop items.

Concurrent edits

Two tabs change the quantity of the same line at the same time. Each PATCH sends If-Match with its version. The second one gets 412. The client refetches the cart and reapplies the user's intent if it still makes sense. For a quantity stepper, the latest user action wins.

Tip

Debounce rapid quantity clicks. Five clicks on the plus button should send one request with quantity 6, not five requests that race each other.

9. Deep dive: checkout form, payments, and idempotent submit

Checkout flow: the form saves steps through a checkout state machine to the order API, address autocomplete is queried with debounce, the payment iframe sends card data straight to the payment provider and returns a token, and the order is submitted with an idempotency key.
Figure 2. Checkout. Card data goes from the iframe straight to the payment provider. Our code only sees a token and submits the order with an idempotency key.

A multi-step form as a state machine

Model checkout as explicit states: contact, shipping address, shipping method, payment, review, submitting, done, and failed. Each step has its own validation. Moving forward saves the step to the server, which returns new totals. This keeps tax and shipping correct and lets the user resume on another device.

Validation that helps

Address autocomplete

Call an address API after the user types 3 or more characters, debounced by 200 to 300 ms. Cancel the previous request with AbortController so late answers do not overwrite new ones. Use a session token so the provider bills one session, not every keystroke. Render the suggestions with the combobox pattern: role="combobox" on the input, aria-expanded, aria-controls pointing to a role="listbox", and aria-activedescendant for the highlighted option. When the user picks a suggestion, fill the structured fields and let them edit. Never force the suggestion. Real addresses are sometimes missing from the database.

Payment iframes and PCI scope

Never render your own card number input. Use the payment provider's hosted fields. Each field is an iframe from the provider's origin. The card number goes straight from the iframe to the provider and comes back as a token or payment method ID. Because of the same-origin policy, your JavaScript cannot read the iframe's content. This keeps you in the smallest PCI self-assessment scope.

Idempotent order submit

Placing the order is the one action that must happen exactly once. Many things can go wrong. The user can double click, or click again after a slow response. The network can drop after the server charged the card. The page can reload during submit. The design handles all of them.

  1. When the user reaches the review step, create an idempotency key with crypto.randomUUID(). Store it in the checkout draft and in sessionStorage.
  2. On click, move the state machine to submitting. Disable the button and show progress. A second click does nothing because the state is not review.
  3. Send POST /api/orders with the key, the checkout ID, the payment token, and the expected total.
  4. On timeout or network error, retry with the same key, with backoff like 1, 2, and 4 seconds. The server returns the original result if the first attempt succeeded.
  5. If the page reloads during submit, read the key from sessionStorage. Ask the server for the order status by key before allowing a new attempt.
  6. Create a new key only when the user changes something that changes the order, such as the cart, the address, or the payment method.
Interview

Say clearly that disabling the button is not enough. It stops double clicks but not retries after timeouts, reloads, or two tabs. Only a server-side idempotency key with a stored result gives the exactly-once effect.

Price and stock at the final step

The client sends expectedTotal. If the server computes a different total, because a price changed or a coupon expired, it returns 422 with the new totals. The review page shows the change and asks the user to confirm again. Never charge a different amount than the user saw.

10. Deep dive: performance budgets, experiments, and analytics

Performance budgets for conversion

Set budgets and enforce them in CI. Fail the build when product page JavaScript grows above 150 KB compressed. Also fail it when a lab LCP test on a throttled mobile profile goes above 2.5 seconds. Track field data from real users with the web-vitals library and report LCP, INP, and CLS by page type and device class.

Experimentation

Stores run many A/B tests on price display, button text, and layout. The frontend must avoid two problems: flicker and bias.

Analytics events

Use a standard event list so marketing, product, and data teams speak the same language. Common names are view_item, select_item, add_to_cart, remove_from_cart, begin_checkout, add_shipping_info, add_payment_info, and purchase.

11. Failure modes

12. Trade-offs

Static HTML versus SSR per request

Server cart versus local cart

Single-page checkout versus multi-step

Client-side versus server-side experiments

13. 45-minute interview walkthrough

  1. Minutes 0 to 5. Ask about catalogue size, guest checkout, countries, payment methods, and traffic spikes.
  2. Minutes 5 to 10. Budgets: CDN hit rate, page weight, LCP breakdown on 4G.
  3. Minutes 10 to 15. Draw the architecture: CDN, ISR, islands, live offers, cart store, tab sync, checkout app, payment iframe.
  4. Minutes 15 to 20. Data model with products, variants, offers, cart with version, and checkout draft. Mention minor units.
  5. Minutes 20 to 26. Rendering and SEO: ISR, JSON-LD, hero image, hydration cost.
  6. Minutes 26 to 31. Variant picker logic and inventory freshness levels.
  7. Minutes 31 to 35. Cart: optimistic add, BroadcastChannel, guest merge, If-Match.
  8. Minutes 35 to 41. Checkout: state machine, validation, autocomplete, payment iframe, idempotent submit.
  9. Minutes 41 to 45. Performance budgets, experiments without flicker, analytics, and failure modes.

14. Summary

15. Common mistakes

Worked example: a double click on Place order

A shopper on a slow 3G connection reaches the review step with a total of 129 dollars.

  1. The review step mounts. The client creates key k1 with crypto.randomUUID() and stores it in the draft and sessionStorage.
  2. The shopper clicks Place order. The state machine moves from review to submitting. The button shows a spinner and is disabled.
  3. The client sends POST /api/orders with Idempotency-Key: k1, the payment token, and expectedTotal: 12900.
  4. The shopper clicks again 300 ms later. The state is submitting, so the handler returns without a request.
  5. The server records k1 as in progress, creates the order, charges the card through the provider, and stores the result with the key.
  6. The response is lost when the train enters a tunnel. After 10 seconds the client's request times out.
  7. The client shows "Still placing your order". It retries after 1 second with the same key and the same body.
  8. The server finds k1 with a stored result. It returns 200 with the same order ID. It does not charge again.
  9. The client moves to done, clears sessionStorage, posts cart-changed on the BroadcastChannel, and navigates to the confirmation page.
  10. A second tab with the cart open receives the broadcast, refetches, and shows an empty cart.
  11. The server, not the browser, sends the purchase analytics event once, keyed by order ID.

Code lab: idempotent order submit with retries

This snippet simulates a flaky order API. The server sometimes commits the order and then loses the response. The client retries with the same key. Save it as orders.mjs and run node orders.mjs with Node 19 or newer. It should report one order and one charge for every checkout.

const stored = new Map()                     // idempotencyKey -> { body, result }
let charges = 0

async function serverPlaceOrder(key, body) {
  const prev = stored.get(key)
  if (prev) {
    if (JSON.stringify(prev.body) !== JSON.stringify(body)) return { status: 409 }
    return { status: 200, order: prev.result }
  }
  charges++
  const order = { id: `ord_${stored.size + 1}`, total: body.expectedTotal }
  stored.set(key, { body, result: order })
  if (Math.random() < 0.4) throw new Error('response lost')   // committed, but client never hears
  return { status: 201, order }
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms))

async function submitOrder(draft, { maxAttempts = 5 } = {}) {
  const body = { checkoutId: draft.id, token: draft.token, expectedTotal: draft.total }
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      const res = await serverPlaceOrder(draft.idempotencyKey, body)
      if (res.status === 409) throw new Error('key reused with a different body')
      return res.order
    } catch (err) {
      if (err.message.startsWith('key reused') || attempt === maxAttempts) throw err
      await sleep(10 * 2 ** attempt)             // backoff, same key every time
    }
  }
}

let ok = 0
for (let i = 0; i < 200; i++) {
  const draft = { id: `co_${i}`, token: 'tok_visa', total: 12900, idempotencyKey: crypto.randomUUID() }
  try { await submitOrder(draft); ok++ } catch { /* gave up after max attempts */ }
}
console.log({ checkouts: 200, confirmed: ok, ordersStored: stored.size, charges })
console.log(charges === stored.size ? 'exactly one charge per order' : 'DOUBLE CHARGE')

Now change submitOrder to create a new key inside the loop. Run it again. The number of charges will be higher than the number of checkouts. That is the double charge bug in a few lines.

Check yourself

  1. Why not put live stock levels into the cached product HTML?
    Answer

    Cached HTML can be minutes old, and stock can change in seconds during a sale. Show build-time stock only as a hint, then replace it with a short-lived live call. The server re-checks stock at add to cart and at order time.

  2. What three things must a server do with an idempotency key?
    Answer

    Store the key with the request body and the result. Return the stored result for a repeat with the same key and body. Reject a repeat with the same key but a different body, usually with 409.

  3. How do hosted payment fields reduce PCI scope?
    Answer

    The card inputs live in iframes from the provider's origin. The same-origin policy stops your JavaScript from reading them. Card data goes straight to the provider, and your page only receives a token.

  4. How does a second open tab learn that the cart changed?
    Answer

    The tab that made the change posts a message with the new cart version on a BroadcastChannel. Other tabs compare versions and refetch if theirs is older. The storage event and a refetch on visibilitychange act as fallbacks.

  5. Why should the selected variant be derived rather than stored as separate state?
    Answer

    Storing it separately creates two sources of truth that can disagree, for example after a URL change. Deriving it from the selection map and the variant list keeps the picker, price, and gallery consistent.

  6. Name two reasons client-side A/B tests can hurt a product page.
    Answer

    They cause flicker when the original renders before the change, which also adds CLS. They add JavaScript that delays interactivity. Server or edge assignment avoids both.

  7. Why send the purchase event from the server?
    Answer

    Client events are lost when the user closes the tab early or uses an ad blocker. The server knows for sure that the order was created and can send exactly one event per order ID.

Key terms

ISR
Incremental static regeneration, cached static pages rebuilt in the background.
Hydration
Attaching JavaScript behaviour to HTML rendered on the server.
Islands architecture
Hydrating only interactive parts of a mostly static page.
JSON-LD
Structured data in a script tag that describes the page for search engines.
SKU
Stock keeping unit, the ID of one buyable variant.
Minor units
The smallest unit of a currency, like cents, stored as an integer.
Idempotency key
A client-generated ID that makes a repeated request return the first result.
PCI DSS
The security standard for systems that store, process, or send card data.
Hosted fields
Payment inputs served in iframes from the payment provider.
3-D Secure
An extra bank authentication step for card payments.
LCP
Largest Contentful Paint, the time the main content element renders.
INP
Interaction to Next Paint, how fast the page responds to user input.
stale-while-revalidate
A cache directive that serves a stale copy while fetching a fresh one.

Further reading

Primary references