Design an online shop
hard 90 minModel a catalog, a cart, stock and orders as objects, and write a checkout that holds the goods, gets the money and sells, with a way back from every step.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
An online shop in a low-level design round is the program from the first look at a product to the parcel at the door: catalog, cart, checkout, payment, order.
Underneath it is the problem of two resources that must be taken together: pieces on a shelf, and money in somebody else's system. Travel booking, ticket sales and food orders have the same shape.
The answer is four objects that change at four speeds, one owner of stock, and one method that runs three steps, each with an undo.
Why it exists
Everybody has bought something, so the domain needs no explanation. The discussion begins at once with classes and goes quickly to what happens when something fails.
It shows the difference between code that works and code that can be interrupted. A tab is closed, a bank is slow, two people click: the design must have an answer before the code has.
It is a place where patterns are easy to name and easy to overuse. Strategy and Facade carry weight, a Singleton does not.
A short history
1937
Sylvan Goldman introduces one of the first shopping carts in the Humpty Dumpty supermarkets in Oklahoma, on 4 June. The word came to the web.
1979
Michael Aldrich connects a modified television to a transaction computer by telephone line: online shopping before the web.
1994
An album by Sting is sold over the web with a secure payment, often named as the first such sale. In the same year Design Patterns appears, with Strategy and Facade.
2004
Eric Evans describes the Specification pattern in Domain-Driven Design: a question about an object as an object, which can be combined.
2004
Java 5 brings atomic variables and concurrent collections into its standard library, the tools of many stock counters.
Words to know
- SKU
- Stock keeping unit: what is counted on its own, such as the red shirt in M.
- Available
- On hand minus held minus sold but not shipped.
- Hold or reservation
- Pieces promised to one order until a deadline.
- Authorise
- The bank promises an amount. Nothing has moved yet.
- Capture
- The promised money is taken.
- Void
- The promise is given back.
- Price snapshot
- The price copied into the order line.
- Idempotency key
- A name for an attempt, so that repeating it has the same result.
- Saga
- Steps in several systems, each with an undo.
- Specification
- A yes or no question about an object that can be combined with others.
- Outbox
- Messages stored with the change and sent later.
- Invariant
- A sentence that is true after every operation.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Wish. Ids and numbers in a cart
Understand it
Start here
A basket between two balconies
Two balconies face each other over a narrow street. A rope on two pulleys carries a basket. Everything an online shop must get right happens on that rope.
Wish, hold, money, goods, receipt. And a timer for people who walk away.
What an interviewer looks for here
Do they separate?
Price, stock, wish and agreement change at different speeds. Four objects.
Do they hold?
Between "in stock" and "paid" there are minutes. Who has the jar meanwhile?
Do they walk back?
Money fails after the hold, the hold ends during the payment. Each step needs its undo.
Do they survive a double click?
The same key, the same order, one charge.
How to spend the round
Questions
Six questions, and what each answer changes
| Ask | Usual answer | What it changes |
|---|---|---|
| When is stock taken? | Held at checkout for 15 minutes, taken when it ships | Hold with a deadline |
| Does adding to the cart hold stock? | No | The cart needs no inventory |
| When is the card charged? | Authorised at checkout, captured when it ships | Three calls and not one |
| What if a price changes while I look? | Show the new total and ask | seenTotal in the call |
| Which discounts, in which order? | Percent, amount, buy one get one | A list of rules |
| One warehouse? Returns? | One, and returns later | Allocator and Return are extensions |
Speeds
Four things that people put into one class
| Thing | Changes | Who changes it | Object |
|---|---|---|---|
| Name, category, price | Sometimes | Shop staff | Product in Catalog |
| Number of pieces | Every second | Checkouts, warehouse | Inventory |
| What I want | With every click | One customer | Cart |
| What we agreed | Never | Nobody | Line and Bill in Order |
Life
The life of an order
An order
One piece of stock
First try
The design most people draw first
The design to avoid: an order that reserves, pays and mails
1/5A family of users
Customer and admin share a parent because of one question, may they. Roles are data. The customer holds all orders, and the orders hold the customer.
extends (is a)owns (dies together)has (lives on)usesdepends on
def checkout(self, customer_id, address, payment, details): order = Order.create_from_cart(cart, address) result = payment.process(order.total, details) # money first if result.success: order.process() # reserve, answer ignored cart.clear() return order order.cancel() # releases what was never reserved raise ValueError("payment failed")Better
The design to reach
The design to reach: a checkout that keeps the order of things
1/7What can be bought
A product is a record: name, price, category. Stock is not here. It changes every second, and a name changes once a year.
owns (dies together)usesdepends onimplements
lines, bill = shop.price(cart, discounts) # shown to the customerorder = shop.place("asha", "click-1", cart, "Rope Street 3", "card", bill.total, discounts)shop.ship(order) # capture, then stock leavesshop.deliver(order)Inside place
Roles
What each class owns
| Class | Owns | Decides | Does not know |
|---|---|---|---|
Catalog | Products | What is found | Stock, orders |
Cart | Ids and numbers | Limits for a line | Prices, stock |
Inventory | On hand, holds | Whether it is there | Money, people |
make_bill | Nothing | The arithmetic | Where rules come from |
Order | The agreement, its status | Which move is legal | Cards, shelves |
Checkout | Orders by key | The sequence and the way back | Any rule |
The hard part
The last jar
Look, then take
How do you make sure that the last piece is sold once?
BreaksCheck at add to cart
- How
if product.isInStock()when it is added.- Limit
- Minutes pass between the cart and the card. Everybody sees 1.
- Choose when
- As a hint on the page, never as a promise.
WorksHold when it is added to the cart
- How
- A hold for each cart line.
- Limit
- Carts are dreams. A few hundred tabs empty the shelf and nobody pays.
- Choose when
- Seats and tickets, with a short clock.
StrongHold at checkout, all lines or none, with a deadline
- How
reserve(key, lines)under one lock.sellafter the money.- Limit
- Somebody may see "sold out" at the last step.
- Choose when
- The normal shop.
Money
From lines to a total
The order matters
Three carts in cents
| Cart | Subtotal | Discount | Shipping | Tax 8% | Total |
|---|---|---|---|---|---|
| Headphones | 7999 | 0 | 599 | 640 | 9238 |
| Headphones, backpack | 12998 | 0 | 0 | 1040 | 14038 |
| The same, 25% off | 12998 | 3249 | 599 | 780 | 11128 |
Where does a rule belong?
Do
- Hold first, then money, then sell
- Copy price and name into the order
- Give every outside call a key
- Compare the total with the one the customer saw
Do not
- Keep stock in the product
- Trust a total from the browser
- Hold stock for a cart that dreams
- Cancel what was never reserved
Summary
The whole topic in one minute.
Catalog, cart, inventory and order are four objects, because they change at four speeds. The cart holds no prices and no stock. The order copies what was agreed.
Place: price again and compare, store PENDING under the key, hold all lines, authorise, sell, and look at the answer. Every step has the order's key and an undo, and a job finishes or voids what was interrupted.
- Catalog, cart, inventory and order change at four speeds, so they are four objects.
- Reserve all lines or none, under one lock, with a key and a deadline.
- Hold, authorise, sell. Each step has an undo.
- An order copies what was agreed. Nothing later changes it.
- The same key gives the same order, whatever the browser does.
Sources
- Wikipedia: Shopping cart
- Wikipedia: Michael Aldrich
- Wikipedia: Online shopping
- Wikipedia: Specification pattern
- Evans and Fowler: Specifications
- Adobe Commerce: inventory
- Shopify: inventory level
- Shopify: inventory management apps
- WooCommerce: product settings, hold stock
- WooCommerce: order statuses
- Saleor: stock
- Medusa: inventory concepts
- Stripe: PaymentIntent lifecycle
- Stripe: idempotent requests
- Adyen: capture
- Spring Data JPA: specifications
- commercetools: carts
- PostgreSQL: UPDATE