Design E-Commerce Platform – Frontend System Design

Problem Statement
Build the frontend for an e-commerce website like Amazon or Shopify stores.
Requirements:
- A product listing page with search, filters (brand, price, size, rating), and sorting
- A product detail page with an image gallery, variants (size, color), price, stock status, and reviews
- A cart that persists across visits and works for both guests and logged-in users
- A checkout flow with shipping address, payment, and order confirmation
- The site must be fast, SEO-friendly, and fully responsive
Describe your approach to rendering strategy, component structure, cart and checkout state, the API, and any optimizations you’d consider for performance, conversion, and security.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | How big is the catalog? Hundreds of products or millions? | Assume millions of products across many categories. |
| 2 | Where does the product data come from? Can you describe the API? | Please design the API. |
| 3 | How important is SEO? Do product pages need to rank on Google? | Very important. Most traffic comes from search engines. |
| 4 | Can guests check out, or do they need an account? | Guests can check out. Logged-in users should keep their cart across devices. |
| 5 | Do we handle payments ourselves or use a payment provider? | Use a provider like Stripe or Adyen. |
| 6 | Do prices and stock change often? | Yes. Prices change during sales, and popular items can sell out. |
| 7 | Should the listing page use pagination or infinite scroll? | Your call, but explain the trade-off. |
| 8 | Do we need to support big traffic spikes like Black Friday? | Yes, traffic can be 10x normal on sale days. |
| 9 | Should we support multiple currencies and languages? | Yes, you can talk about localization. |
| 10 | Any requirements for accessibility? | Yes, keep it accessible, especially checkout. |
| 11 | Are seller dashboards, returns, or order tracking in scope? | Out of scope. |
Requirements
Functional Requirements
- Product listing page (PLP) with search, faceted filters, sorting, and pagination
- Search box with autocomplete suggestions
- Product detail page (PDP) with an image gallery, variant picker, live price and stock, and reviews
- Add to cart from the PLP and PDP, with a mini cart that updates instantly
- Persistent cart for guests, merged into the user’s cart when they log in
- Multi-step checkout: shipping, payment, review, and confirmation
- Localized prices, currency, and copy
Non-Functional Requirements
- SEO-friendly: crawlable HTML, structured data, clean URLs
- Fast: good Core Web Vitals (LCP under 2.5s, INP under 200ms, CLS under 0.1), especially on mobile
- Correct: the price the user pays is always the server’s price, and we never sell stock we don’t have
- Reliable checkout: no double charges, even when the user double-clicks or the network retries
- Scales to 10x traffic spikes on sale days
- Accessible (WCAG), with special care for forms
- Secure: card data never touches our servers
Napkin Math (Estimations)
Assume a large online store:
| Metric | Estimate / Calculation |
|---|---|
| Daily Active Users | 5,000,000 users/day |
| Pageviews per User | 8 (search, a few listings, a few products, cart) |
| Total Daily Pageviews | 5,000,000 × 8 = 40,000,000 pageviews/day |
| Average Page QPS | 40,000,000 ÷ 86,400 ≈ 460 pages/sec |
| Sale Day Peak | 460 × 10 ≈ 4,600 pages/sec |
| Products per Listing Page | 24 product cards, each with one image |
| Orders per Day | ~2% conversion × 5,000,000 = 100,000 orders/day |
What this tells us: Most traffic is read-only browsing, so the pages that matter most (listings and product pages) should be served from a CDN cache as much as possible. Only a small slice of traffic reaches the cart and checkout, but that slice is where the money is, so it needs to be correct above everything else. Put simply, the task is to design an e-commerce platform that is fast to browse and correct at checkout.
Architecture / Component Design

User, Router, and Routing
Everything starts when the user enters the app, usually from a Google search landing straight on a product page. We use Next.js because it gives us server rendering, static generation, and routing in one framework. The main routes are:
/search?q=shoesand/c/:category: product listing pages/p/:slug: product detail page/cart: full cart/checkout: checkout steps (shipping, payment, review)/order/:id/confirmation: confirmation page
Human-readable slugs (like /p/nike-air-max-90) help both SEO and trust when users share links.
SSR vs CSR (Server-Side Rendering vs Client-Side Rendering)
E-commerce is the classic case where the rendering strategy changes per page:
| Page | Rendering | Why |
|---|---|---|
| Home, category pages | Static generation with revalidation (ISR) | Same for everyone, cached at the CDN, refreshed every few minutes |
| Search results | SSR | Endless combinations of queries and filters, but still needs to be crawlable |
| Product detail | ISR for content, client fetch for price and stock | Content rarely changes, but price and stock must be fresh |
| Cart, checkout | CSR | Personal, not indexed, very interactive |
The product page is the interesting one. If we cache the entire page, a cached page can show yesterday’s price or “In stock” for an item that just sold out. So we split it: the description, images, and reviews come from the cached HTML, and a small client-side request fetches live price and availability after the page loads. The HTML can include the last known price so the page never looks empty, and the live request corrects it if needed.
State Management and Data Flow
The app has three kinds of state, and each has a natural home:
- URL state: search query, filters, sort, and page live in the URL (
/search?q=shoes&brand=nike&size=10&sort=price_asc&page=2). That makes every listing shareable, bookmarkable, crawlable, and makes the back button work for free. - Server state: products, prices, and stock. These come from the API and are cached by the View Model.
- Cart state: shared by the header badge, the mini cart, the cart page, and checkout, so it lives in a global Store (useContext). For guests, it’s also mirrored to
localStorageso it survives reloads.
| Option | Pros | Cons | Best Use Case |
|---|---|---|---|
| URL query params | Shareable, SEO, back button works | Only for serializable, non-sensitive state | Filters, sort, page |
| useState | Simple, local | Not shared | Selected image, open accordions |
| useContext | Global, minimal boilerplate | Re-renders all consumers on change | Cart, user session |
| React Query / SWR | Caching, deduping, background refetch | Another dependency | Products, live price and stock |
| Redux / Zustand | Fine-grained updates, devtools | Boilerplate or another dependency | If cart and checkout logic grows complex |
Overall, put filters in the URL, the cart in useContext, and treat the server as the source of truth for anything involving money.
Product Listing Component Structure
The ProductListContainer is the listing page’s main “container” component. It reads the filters from the URL, calls useViewModel() to get the products and facet counts, and renders the search bar, filters, and grid.
The component structure looks like:
<ProductListContainer>
<SearchBar />
<FacetFilters />
<SortDropdown />
<ProductGrid>
<ProductCard>
<AddToCartButton />
</ProductCard>
</ProductGrid>
<Pagination />
</ProductListContainer>
ProductListContainer
The “smart” container. It turns the URL into a query, asks the View Model for results, and writes filter changes back to the URL. It doesn’t know how anything looks.
SearchBar
Shows autocomplete suggestions as the user types. It debounces input (around 200 to 300ms), cancels stale requests with AbortController, and caches recent queries so typing and backspacing doesn’t refetch.
FacetFilters
Renders filter groups (brand, price range, size, rating) with result counts next to each option, like “Nike (124)”. Each change updates the URL, which triggers a new search. On mobile, the filters collapse into a bottom sheet.
ProductGrid
A responsive CSS Grid of cards. It knows nothing about filters or fetching, it just lays out the products it receives.
ProductCard
One product: image, title, price, rating, and a quick add-to-cart button. Every card reserves space for its image with a fixed aspect ratio, so the grid doesn’t jump while images load.
Pagination
Numbered pages with real links (<a href="?page=3">) so crawlers can reach every product.
Pagination vs Infinite Scroll
| Approach | Pros | Cons |
|---|---|---|
| Numbered pagination | Crawlable, shareable, easy to return to a position, footer reachable | Extra click to see more |
| Infinite scroll | Great for casual browsing on mobile | Hard to crawl, loses position on back, footer unreachable |
| “Load more” button | Middle ground, user stays in control | Still needs URL updates to keep position |
For a store where SEO drives traffic, go with numbered pagination (or a “Load more” button that also updates ?page= in the URL). Shoppers often compare products and come back, so restoring their position matters.
Product Detail Component Structure
<ProductDetailContainer>
<ImageGallery />
<ProductInfo />
<VariantPicker />
<PriceAndStock />
<AddToCartButton />
<Reviews />
<RecommendedProducts />
</ProductDetailContainer>
- ImageGallery: the main image is the Largest Contentful Paint element, so it’s preloaded with
fetchpriority="high". Thumbnails and zoom images load lazily. - VariantPicker: size and color options. Picking a variant updates the URL (
?color=red&size=10), the gallery images, and the price and stock for that exact SKU. Unavailable combinations are shown as disabled, not hidden. - PriceAndStock: fetched client-side from the live endpoint so it’s never stale.
- Reviews and RecommendedProducts: below the fold, so they load lazily when they scroll near the viewport.
Cart Design
The cart is where a lot of interviews get interesting, because it has to work for guests, survive reloads, and sync across devices:
- Guest cart: the server creates a cart and returns a
cartIdin a cookie. The client also mirrors the cart inlocalStorageso the badge renders instantly on load. - Logged-in cart: stored on the server against the user, so it follows them across devices.
- Merging on login: when a guest logs in, the server merges the guest cart into the user’s cart (summing quantities for the same SKU, capped by stock), and the client replaces its local copy with the merged result.
- Cross-tab sync: listen to the
storageevent (or aBroadcastChannel) so adding an item in one tab updates the badge in another.
Optimistic Add to Cart
Adding to cart should feel instant. The View Model updates the Store immediately, shows the mini cart, and sends the request in the background. If the server rejects it (for example, the item just sold out), we roll back and show a clear message.
async function addToCart(item: CartItemInput): Promise<void> {
const previous = store.cart;
store.setCart(addItemLocally(previous, item)); // optimistic
try {
const cart = await api.addCartItem(previous.id, item);
store.setCart(cart); // server is the source of truth
} catch (error) {
store.setCart(previous); // roll back
toast.error(toCartErrorMessage(error)); // e.g., "Only 2 left in stock"
}
}
Notice that we always replace the cart with the server’s response. The server recalculates prices, discounts, and taxes, so the client never computes the final total on its own.
Checkout Flow
Checkout is a short, focused flow. We strip out the site header, recommendations, and anything else that could distract the user from finishing.
<CheckoutContainer>
<CheckoutSteps /> // Shipping -> Payment -> Review
<AddressForm />
<ShippingOptions />
<PaymentFields /> // iframe from the payment provider
<OrderSummary />
<PlaceOrderButton />
</CheckoutContainer>
- AddressForm: uses proper
autocompleteattributes (shipping street-address,postal-code,country) so the browser can autofill it, plus inline validation on blur. - PaymentFields: card inputs are rendered in iframes hosted by the payment provider (like Stripe Elements). Card numbers go straight from the user’s browser to the provider, never through our JavaScript or servers. This keeps us out of most of PCI DSS compliance scope.
- 3-D Secure: some banks require an extra verification step. The provider’s SDK shows the challenge, and our UI waits for the result before showing confirmation.
- Save progress: keep completed steps in session storage so a reload doesn’t wipe the address the user just typed.
Placing the Order Safely
Double charges are the worst possible bug here. Two things prevent them:
- Disable the button while the request is in flight.
- Send an idempotency key. The client generates a unique key when checkout starts and sends it with the order request. If the user double-clicks, or the network retries, the server sees the same key and returns the original order instead of creating a second one.
Component and Data Relationships (Table)
| Component | Responsibility | Interacts With |
|---|---|---|
| Next.js Router | Routing, SSR/ISR per page | Containers |
| View Model | Business logic, data transforms | Store, Network Manager, containers |
| Store (useContext) | Cart and session state | View Model, localStorage |
| Network Manager | API calls, retries, auth | View Model, server |
| ProductListContainer | Search, filters, grid | View Model, URL |
| ProductDetailContainer | Gallery, variants, live price | View Model |
| CheckoutContainer | Address, payment, order | View Model, payment provider |
| Image CDN | Resized, modern-format product images | Product cards, gallery, order summary |
API Design
The API uses RESTful design principles over HTTPS, and all endpoints return JSON. Catalog endpoints are public and cacheable at the CDN. Cart and order endpoints are personal and never cached.
Authentication & Headers
- Cookie: httpOnly, Secure, SameSite session cookie for logged-in users, plus a
cartIdcookie for guests - Accept-Language: e.g.,
en-USfor localized content - X-Currency: e.g.,
USD,EUR - Idempotency-Key: a unique key on order creation
Pagination: Page-Based vs Cursor-Based
- Page-Based:
page=2&pageSize=24. Simple, maps to numbered page links, and easy to cache. - Cursor-Based:
cursor=abc123. Handles fast-changing data without duplicates, but you can’t jump to page 7.
For listings, page-based pagination wins because we want numbered, crawlable page links and CDN-cacheable responses. Cursor-based pagination is a better fit for things like an order history feed.
API Endpoint Design & Client Data Model
// --- Shared Types ---
export type Money = {
amount: number; // in minor units (cents) to avoid floating point errors
currency: string; // ISO code, e.g., "USD"
};
export type ProductSummary = {
id: string;
slug: string;
title: string;
imageUrl: string;
price: Money;
rating: number;
reviewCount: number;
};
export type Facet = {
key: string; // e.g., "brand"
label: string;
options: { value: string; label: string; count: number; selected: boolean }[];
};
// --- API: Search / Listing (public, CDN cacheable) ---
// GET /api/products?q=shoes&brand=nike&sort=price_asc&page=1&pageSize=24
export type SearchProductsResponse = {
products: ProductSummary[];
facets: Facet[];
page: number;
pageSize: number;
total: number;
};
// --- API: Autocomplete ---
// GET /api/suggest?q=sho
export type SuggestResponse = {
suggestions: { text: string; type: "query" | "product" | "category" }[];
};
// --- API: Product Detail (public, CDN cacheable) ---
// GET /api/products/:slug
export type Variant = {
sku: string;
options: Record<string, string>; // e.g., { color: "red", size: "10" }
imageUrls: string[];
};
export type ProductDetailResponse = ProductSummary & {
description: string;
variants: Variant[];
};
// --- API: Live Price and Stock (never cached) ---
// GET /api/availability?skus=sku1,sku2
export type AvailabilityResponse = {
items: { sku: string; price: Money; inStock: boolean; quantityLeft?: number }[];
};
// --- API: Cart ---
// GET /api/cart
// POST /api/cart/items body: { sku, quantity }
// PATCH /api/cart/items/:sku body: { quantity }
// DELETE /api/cart/items/:sku
export type CartResponse = {
id: string;
items: { sku: string; title: string; imageUrl: string; quantity: number; unitPrice: Money }[];
subtotal: Money;
discounts: Money;
tax: Money;
total: Money;
};
// --- API: Create Order ---
// POST /api/orders
// Headers: Idempotency-Key: <uuid>
export type CreateOrderRequest = {
cartId: string;
shippingAddressId: string;
shippingOptionId: string;
paymentMethodToken: string; // token from the payment provider, never raw card data
};
export type CreateOrderResponse = {
orderId: string;
status: "confirmed" | "requires_action"; // requires_action = 3-D Secure challenge
clientSecret?: string; // used by the provider SDK for 3-D Secure
};
// --- Error Response (all endpoints) ---
export type ErrorResponse = {
error: string; // e.g., "OUT_OF_STOCK", "PRICE_CHANGED"
message: string;
status: number;
};
Explanation
- GET /api/products: Returns a page of products plus facet counts for the current filters. Because the response depends only on the query string, the CDN can cache it.
- GET /api/availability: A tiny, uncached endpoint for live price and stock. It’s batched by SKU, so a page with many products makes one request, not one per product.
- Cart endpoints: Every change returns the full recalculated cart, so the client always renders the server’s totals.
- POST /api/orders: Creates the order using a payment token from the provider. The
Idempotency-Keyheader makes retries safe. If the bank requires 3-D Secure, the response says so and the client completes it with the provider’s SDK. - Error responses: Specific codes like
OUT_OF_STOCKandPRICE_CHANGEDlet the UI show helpful messages instead of a generic “Something went wrong.”
Money is always sent in minor units (cents) as integers. Floating point math like 0.1 + 0.2 doesn’t equal 0.3 in JavaScript, and that’s not a bug you want in a checkout. Format prices for display with Intl.NumberFormat.
Optimizations: Speed, Conversion, and Resilience
Performance and Core Web Vitals
- CDN caching: static and ISR pages are served from the edge, which absorbs sale-day spikes
- Image CDN: request images resized for each slot through
srcsetandsizes, in AVIF or WebP - LCP: preload the hero or main product image, and don’t lazy-load anything above the fold
- CLS: reserve space for images, banners, and the live price so nothing shifts when it loads
- INP: keep filter clicks responsive by updating the UI immediately and fetching results in the background (
useTransitionhelps here) - Code splitting: checkout code and the payment SDK only load on the checkout route
- Third-party scripts: analytics, A/B testing, and chat widgets are the usual cause of slow stores. Load them with
deferor after the page is interactive.
Prefetching
- Prefetch a product page when its card enters the viewport or on hover, so clicking feels instant
- Prefetch the checkout bundle when the user opens the cart
Graceful Loading States
- Skeleton cards sized like real ones while results load
- Keep the old results visible (dimmed) while new filter results load, instead of flashing an empty grid
- Show the last known price immediately, then update it from the live endpoint
Error Handling and Smart Retry Logic
- Out of stock at checkout: highlight the affected item and offer to remove it or pick another variant
- Price changed: show the new total and ask the user to confirm before charging
- Payment declined: keep the form filled in and show the provider’s reason in plain language
- Network errors: retry safe requests (GETs, and order creation thanks to the idempotency key) with exponential backoff
SEO
- Structured data: add JSON-LD
Productmarkup (name, image, price, availability, rating) so Google can show rich results - Canonical URLs: filter combinations create endless URLs, so point variations at a canonical page and only allow indexing for useful ones (like
/c/running-shoes) - Clean metadata: unique titles and descriptions per product and category
Accessibility and Security
Accessibility (a11y)
- Forms: every input has a visible
<label>, errors are linked witharia-describedby, and focus moves to the first error on submit - Cart updates: announce “Added to cart” through an
aria-live="polite"region, since the change happens away from the user’s focus - Filters: real checkboxes and radio buttons, announce the result count after filtering
- Images: meaningful
alttext for product images, including the selected color - Keyboard: the gallery, variant picker, mini cart, and checkout all work without a mouse, with visible focus styles
- Don’t rely on color alone: a sold-out size is crossed out and labeled, not just greyed
Security
- Never trust the client for money: the server recalculates prices, discounts, tax, and stock on every cart change and order
- Card data isolation: provider-hosted iframes keep card numbers out of our code and servers
- XSS: reviews and Q&A are user-generated, so escape them and use a Content Security Policy (CSP). On checkout, an XSS bug could let an attacker skim form data, so CSP matters most there.
- CSRF: SameSite cookies plus CSRF tokens on cart and order changes
- Clickjacking:
frame-ancestorsin the CSP stops other sites from framing checkout - Abuse: rate-limit coupon codes, login, and add-to-cart to stop bots and brute-force attempts
Conclusion: How to Design an E-Commerce Platform
An e-commerce frontend is a balance between being fast and crawlable for millions of shoppers and being exactly right for the few who check out. Cache aggressively where pages are the same for everyone, fetch fresh data where money is involved, keep filters in the URL, make add-to-cart optimistic but let the server have the final word, and protect checkout with provider-hosted payment fields and idempotency keys. If you can explain why the product page is cached but the price isn’t, you’re thinking like a senior engineer.
