Shopping cart

Carts, inventory and pricing rules: adding items, applying discounts, checking stock and turning a cart into an order safely.

On the roadmap:Software Design · step 5: Low-level design: bookings and payments

Lesson 11 of 16 · 10 min read · quiz · exercise

The problem

Shoppers add and remove products, apply coupons, see a total, and check out. The system must check stock, compute the price correctly and create an order.

Entities

Figure SDA-LLD-11-1 · Shopping cart classes · © forcsguy.com

Cart versus order

A cart is mutable and may be stale. An order is a frozen record of what was bought, at what price, with which discounts. Checkout converts one into the other.

Figure SDA-LLD-11-2 · Checkout flow · © forcsguy.com

Pricing as ordered rules

type Line = { sku: string; qty: number; unit: number };
interface PricingRule { apply(lines: Line[]): { reason: string; cents: number }[] }

const buy2get1: PricingRule = {
  apply: (lines) => lines.filter(l => l.sku === "TSHIRT" && l.qty >= 3)
    .map(l => ({ reason: "Buy 2 get 1", cents: -Math.floor(l.qty / 3) * l.unit })),
};
const coupon10: PricingRule = {
  apply: (lines) => [{ reason: "10% coupon", cents: -Math.round(lines.reduce((s, l) => s + l.qty * l.unit, 0) * 0.1) }],
};

function total(lines: Line[], rules: PricingRule[]) {
  const sub = lines.reduce((s, l) => s + l.qty * l.unit, 0);
  const adj = rules.flatMap(r => r.apply(lines));
  return { subtotal: sub, adjustments: adj, total: sub + adj.reduce((s, a) => s + a.cents, 0) };
}

Decide and document precedence (do percentage discounts apply before or after fixed ones?) and whether discounts stack. Keep a record of which rules applied so the invoice can explain the price.

Inventory safely

// conditional update: succeeds only if enough stock remains
function reserve(sku: string, qty: number): boolean {
  const row = stock.get(sku)!;
  if (row.available < qty) return false;
  row.available -= qty; row.reserved += qty; return true;   // atomic in a real database: UPDATE ... WHERE available >= qty
}

Design notes

  • Guest and signed-in carts: merge a guest cart into the user's cart on login.
  • Abandoned carts: stock is not reserved by a cart, only by checkout; reservations expire.
  • Idempotent checkout: a double click must not create two orders (use a checkout key).
  • Money is integer minor units; taxes and shipping are further rules or services.
  • Extensions: wishlists, saved-for-later, per-region pricing, bundles.

Real-world reading

Check your understanding

Question 1 of 3

0 correct so far

Why compute prices on the server at checkout instead of trusting the cart's stored total?

© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.