AlgoViz

Design an online shop

hard 90 min

Model 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

0:00 / 4:40

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

  1. 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.

  2. 1979

    Michael Aldrich connects a modified television to a transaction computer by telephone line: online shopping before the web.

  3. 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.

  4. 2004

    Eric Evans describes the Specification pattern in Domain-Driven Design: a question about an object as an object, which can be combined.

  5. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

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.

Honey by rope
4

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

AskUsual answerWhat it changes
When is stock taken?Held at checkout for 15 minutes, taken when it shipsHold with a deadline
Does adding to the cart hold stock?NoThe cart needs no inventory
When is the card charged?Authorised at checkout, captured when it shipsThree calls and not one
What if a price changes while I look?Show the new total and askseenTotal in the call
Which discounts, in which order?Percent, amount, buy one get oneA list of rules
One warehouse? Returns?One, and returns laterAllocator and Return are extensions

Speeds

Four things that people put into one class

ThingChangesWho changes itObject
Name, category, priceSometimesShop staffProduct in Catalog
Number of piecesEvery secondCheckouts, warehouseInventory
What I wantWith every clickOne customerCart
What we agreedNeverNobodyLine and Bill in Order

Life

The life of an order

An order

Once it is SHIPPED it cannot be cancelled. The way back is a return, with its own life.

One piece of stock

Available means on hand minus held minus sold but not yet shipped.

First try

The design most people draw first

The design to avoid: an order that reserves, pays and mails

«abstract»User# id, email, name+ hasPermission(a): boolCustomer- cart: ShoppingCart- orders: List<Order>

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

Python
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")
Three bugs in eight lines. The card is charged before the stock is held. A failed reserve is not seen. And a declined card releases pieces that belong to other people's orders.

Better

The design to reach

The design to reach: a checkout that keeps the order of things

Catalog- products: Map<id, P>+ get(id): Product+ search(spec, page)Product+ id, name+ cents: int+ category: Category

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

Python
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)
The whole purchase as four calls.

Inside place

Roles

What each class owns

ClassOwnsDecidesDoes not know
CatalogProductsWhat is foundStock, orders
CartIds and numbersLimits for a linePrices, stock
InventoryOn hand, holdsWhether it is thereMoney, people
make_billNothingThe arithmeticWhere rules come from
OrderThe agreement, its statusWhich move is legalCards, shelves
CheckoutOrders by keyThe sequence and the way backAny 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. sell after 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

total=(subtotal−discount)⏟goods+shipping(goods)+round(goods×tax)total = \underbrace{(subtotal - discount)}_{goods} + shipping(goods) + \mathrm{round}(goods \times tax)
Whole cents. Tax is rounded once, half a cent up. Here shipping is free from 100.00 of goods, and the tax rate of 8% is an example. Whether shipping is taxed is a question for a lawyer, and a line of code.

Three carts in cents

CartSubtotalDiscountShippingTax 8%Total
Headphones799905996409238
Headphones, backpack1299800104014038
The same, 25% off12998324959978011128
In the third cart the goods are 9749 after the discount, below the limit, so shipping comes back. Some shops look at the sum before the discount: ask.

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