Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 40 ยท Practice and Review

E-commerce Interview Questions

Prepare for e-commerce developer interviews: money, carts, overselling, idempotent payments, tax rounding and system design prompts, with answers and runnable code.

E-commerce interviews are different from generic backend interviews. The questions sound simple ("design a shopping cart"), but the interviewer is listening for whether you know where the money, the stock and the trust boundaries are. A strong answer names the failure modes first, then the design that avoids them.

This lesson collects the questions that come up most, grouped by topic, with answers you can say out loud in about a minute each. Three of the answers include a small runnable demo so you can see the idea instead of just reading it. At the end are four open-ended system design prompts with a structure for answering them.

Use this pattern for any question: state the invariant (what must never happen), name the failure (how it happens in practice), give the mechanism (the design that prevents it), and mention the trade-off (what it costs). Interviewers reward the trade-off more than the buzzword.

Money and pricing

Why should you never store prices as floats? Binary floating point cannot represent most decimal fractions exactly, so 0.1 + 0.2 is not 0.3 and errors accumulate across lines, discounts and tax. Store money as integers in minor units (cents) together with a currency code, or use a decimal type. Different currencies have different exponents (JPY has none, KWD has three), so the currency decides how many minor units make a major unit. See Representing Money Correctly.

You must split a 10.00 discount across three order lines. How? Compute each exact share, floor it, and give the leftover cents one at a time to the lines with the largest fractional remainders. The parts then always sum to the discount, so line-level refunds add up. Rounding each share independently loses or invents cents.

Where do you round, and why does it matter? Round only at defined points (a percentage discount, a tax line), always with the same rule, and never inside intermediate steps you display. The rule must be identical on the cart, the invoice, the email and the accounting export; a one-cent difference between two screens is a support ticket.

Percent-off and fixed-off both apply. Which first? Either is valid, but the shop must choose, document and store it as data (a priority on each promotion). Percent first then fixed is common, because a fixed voucher keeps its full value. What is wrong is a result that depends on loop order. See Building a Promotions Engine.

Designing a cart

Design a shopping cart. What do you store? A cart has an id, an owner (a user id or an anonymous token), a status, and line items with a product or variant id and a quantity. Store references and quantities, not trusted prices: calculate totals on the server every time the cart is read. Keep a price snapshot only on the order, because an order is a record of what was agreed.

What happens when a guest logs in and has a cart in both places? Merge them. The simple rule is to add quantities per variant and cap them at the stock and per-customer limits, then delete the guest cart. Decide how to treat a coupon that exists on both carts (keep the better, or the one already applied). The demo below shows the quantity rule.

JS Merging a guest cart into a customer cart

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The merge keeps the mug total at 3, caps the cap at the one unit in stock, and drops the sold-out poster. A good answer also says that the customer should be told what changed.

Why recalculate the cart on every request instead of caching totals in it? Prices, promotions, tax rules and stock change while a cart sits there for days. Cached totals go stale and can be exploited ("I added it when it was cheaper"). Recalculation is cheap compared with the cost of selling at the wrong price, and the only moment a price is frozen is when an order is created.

Inventory and overselling

How do you prevent selling the last item twice? Make "check the stock and take it" one atomic operation. In SQL that is a conditional update, UPDATE stock SET qty = qty - 1 WHERE sku = ? AND qty >= 1, followed by checking that one row was affected. A separate SELECT then UPDATE has a gap in which two buyers both see "1 left". Alternatives are row locks (SELECT ... FOR UPDATE), optimistic locking with a version column, or a single-threaded queue per product for flash sales. Add a CHECK (qty >= 0) constraint as a last line of defence.

The next demo reproduces the problem and the fix with an in-memory SQLite database.

Python Read-then-write versus a conditional update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the wrong version both buyers believe they got two caps, and the stock is 1 when four were sold out of three. In the right version buyer B is refused and buyer C gets the last one. See Reservations and Overselling and, for the database side, Isolation and Locking.

When should stock be reserved: at add-to-cart, at checkout, or at payment? It is a business trade-off. Reserving at add-to-cart abandons stock to people who are only browsing. Reserving at payment risks charging a customer for something that sold out a second ago. The common middle path is a short hold when checkout starts (for example 10 to 15 minutes), released by a time limit or when the order is paid or cancelled. For flash sales, hold earlier and shorter.

Payments and reliability

A customer double-clicks "Pay". How do you avoid charging twice? Use an idempotency key: the client generates one key per payment intent and sends it with the request. The server stores the result of the first request under that key and returns the stored result for repeats, without charging again. Concurrent duplicates must wait for the first request, so record the in-flight work before doing it. Also keep the order state machine strict, so a paid order cannot be paid again with a different key. See Idempotency and Reliable Payments.

Python An idempotency store in 25 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The retry returns the same charge id and sets replayed, the changed amount is refused, and only two real charges exist. In a real system the seen map is a table with a unique index on the key and an expiry.

Why do you need webhooks if the payment call returns a result? The browser can close, the network can drop, and many methods (bank transfers, 3-D Secure, wallets) finish asynchronously. The provider calls your server with a signed event, and that event, not the browser redirect, is the source of truth for "paid". Verify the signature on the raw body, check the timestamp, de-duplicate by event id, and expect events to arrive late, twice, or out of order. See Webhooks and Signature Verification.

What is the difference between authorization and capture? Authorization asks the issuer to reserve the amount on the card; capture actually collects it. Shops that ship later authorize at checkout and capture at shipment, so they never charge for something they cannot deliver. An authorization expires, usually within days, and a void releases it without a refund. See Authorization, Capture, Refunds and Chargebacks.

Do you store card numbers? No. Card data goes straight from the browser to the payment provider (hosted fields or a redirect) and your system keeps only a token and the last four digits. This keeps most of the PCI DSS burden off your servers. See PCI DSS Scope and 3-D Secure.

Tax, orders and trust

Tax-inclusive versus tax-exclusive prices? Exclusive prices add tax at checkout (common in the United States). Inclusive prices already contain it (common for consumers in the EU and many other regions), so the tax is extracted: round the net, then tax is gross minus net, so the parts add up to what the customer paid. Show prices the way the market expects and store both net and tax on each line. This is an overview, not legal advice; a tax service is usually worth its fee. See Sales Tax, VAT and GST.

Rounding tax per line or per invoice? Both exist. Per line gives each line an exact tax figure that is easy to refund; per invoice follows a single rate over the total and sometimes differs by a cent. Pick the rule that your jurisdiction or tax service requires, apply it everywhere, and keep it in the order snapshot.

Why model order status as a state machine? Because most bugs are impossible transitions: refunding an unpaid order, shipping a cancelled one, paying twice. A transition table makes the legal moves explicit and rejects the rest in one place. Keep payment status and fulfillment status separate, since an order can be paid but unshipped, or shipped but partly refunded. Record every transition with a timestamp and a reason. See The Order Lifecycle and State Machines.

Which values must never come from the browser? Prices, discounts, shipping cost, tax, totals, stock decisions, and the ids of other customers' resources. The client can request "two of this product" and "apply this code", and the server decides everything else. Also check ownership on every order or address id to avoid IDOR (insecure direct object reference). See Securing an Online Shop.

System design prompts

Each prompt below is open-ended. A good answer takes 10 to 15 minutes: clarify requirements (scale, countries, payment methods), draw the main components, walk through the happy path, then spend most of the time on failure modes.

Prompt 1: Design checkout for a flash sale with 500 units and 200,000 visitors.

flowchart LR
  U["Visitors"] --> CDN["CDN<br/>(static page, cached)"]
  CDN --> Q["Waiting room / queue"]
  Q --> API["Checkout API"]
  API --> R["Stock counter<br/>(atomic decrement)"]
  API --> H["Holds with TTL"]
  H --> P["Payment provider"]
  P -->|webhook| API

Absorb the traffic at the edge, admit buyers at a controlled rate, and keep one authoritative stock counter.

Key points: serve the product page from the CDN and keep it static; admit users through a queue or waiting room at a rate the database can take; decrement stock atomically (a conditional update or a Redis counter that is reconciled with the database); hold units briefly with a time limit and release them if payment fails; make payment idempotent; show an honest "sold out" fast. Mention what you would degrade first (recommendations, reviews) to protect checkout. See Architecture, Scaling and Peak Traffic.

Prompt 2: Design a coupon and promotions system. Model a promotion as conditions (cart total, products, customer group, dates) plus actions (percent off, fixed off, free shipping, buy-one-get-one), with a priority, an exclusivity flag and usage limits (per coupon and per customer). Evaluate promotions in priority order against the cart, allocate discounts across lines so refunds work, and record which promotion produced which discount on the order. Race conditions on usage limits need an atomic counter. Discuss how you would test it: a table of carts and expected totals.

Prompt 3: Design order history and returns. Orders are immutable records with snapshots of prices, addresses and tax. Changes are new events (shipments, refunds, notes), never edits of the past. Returns are their own entity (an RMA) with a status flow and links to the order lines, and a refund is a payment-ledger entry, not an edit to the order total. Discuss partial returns, restocking decisions, and refunding to the original payment method versus store credit.

Prompt 4: Keep the shop in sync with an ERP and a marketplace. Choose a source of truth per field (the ERP owns stock and cost, the shop owns content). Prefer events or webhooks plus a periodic full reconciliation as a safety net. Make every sync job idempotent, map identifiers explicitly, respect rate limits with backoff, and decide the conflict rule in advance (last write wins is rarely right for stock). See Integrations: ERP, PIM, OMS and Marketplaces.

Questions you can ask the interviewer

Good questions show experience: how do you prevent overselling today, what happens to stock when payment is pending, how are prices and taxes calculated and stored on orders, how do you handle duplicate webhooks, and what is your plan for the biggest traffic day of the year.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the most reliable way to stop two buyers from taking the last unit?

    Checking and taking must be one atomic step. A read followed by a write leaves a gap in which two buyers both see the last unit.
  2. 2. What should a server do when it receives the same Idempotency-Key with an identical request a second time?

    Idempotency means repeating the request has no additional effect. Returning the stored result lets clients retry safely after network failures.
  3. 3. Why is the payment webhook, not the browser redirect, treated as the source of truth for a paid order?

    The redirect depends on the customer's browser finishing the trip. The server-to-server event arrives regardless, and after signature verification it can be trusted.
  4. 4. A guest cart and a customer cart both contain a mug. What is a sensible merge rule?

    Adding quantities respects what the customer wanted from both sessions, and caps keep the cart valid. Silent changes confuse customers, so report them.
  5. 5. In a system design answer, which part do interviewers usually weight most?

    Anyone can list tools. Showing that you know how the system fails and what each design choice costs is what separates experienced engineers.

Summary

  • Money is integers (or decimals) with a currency; round at defined points with one rule and allocate leftover cents by largest remainder.
  • Carts hold references and quantities; totals are recalculated server-side, and prices are frozen only on the order.
  • Prevent overselling with an atomic conditional update (or locks), time-limited holds and a non-negative constraint.
  • Make payments idempotent, treat verified webhooks as the source of truth, and separate authorization from capture.
  • Model orders as state machines with separate payment and fulfillment status, and never trust the browser for money or ids.
  • In system design answers, state invariants, failure modes and trade-offs before naming technology.

Next: E-commerce Cheat Sheet