Designing an E-commerce Cart System

Difficulty: Intermediate Patterns: Strategy, Observer, Builder Asked at: Amazon, Flipkart, Myntra, Meesho


Functional Requirements

  1. Add/remove items - add products to cart, remove by product ID
  2. Quantity updates - increase or decrease quantity of items in cart
  3. Apply coupons/discounts - percentage off, flat discount, buy-X-get-Y
  4. Price calculation with tax - subtotal, discount, Goods and Services Tax (GST), and final total
  5. Stock validation - verify product availability before adding and at checkout
    💡 Stock validation means confirming the units exist before promising them. It happens twice on purpose: another shopper can buy the last unit in the gap between you adding it to the cart and you paying. Learn more →
  6. Checkout - validate cart, apply pricing, generate order summary

Non-Functional Requirements

  1. Thread-safety - concurrent add/remove operations must not corrupt cart state
    💡 Thread-safety = the code still behaves correctly when several threads run it at the same instant. Two browser tabs adding the same product in the same millisecond must not leave the cart holding one item instead of two.
  2. Extensibility - new discount types or tax rules require minimal code changes
  3. Accurate pricing - rounding handled correctly; no floating-point drift on totals
    💡 That drift is why money handling is its own discipline: binary floating point cannot represent 0.01 exactly, so money is best held as a precise decimal or as whole paise/cents and rounded once, at the end.

Core Entities

Entity Description
Product ID, name, price, category
CartItem Product reference + quantity in cart
Cart Collection of CartItems, holds applied coupons
Coupon Discount rule: percentage, flat, or buy-X-get-Y
DiscountStrategy Interface for computing discount amount
TaxCalculator Computes tax based on product category and region
StockService Validates product availability
Order Final checkout result with itemized breakdown
OrderBuilder Builds an Order step by step

Class Diagram

classDiagram
    class Product {
        -String id
        -String name
        -double price
        -String category
        -int stockQuantity
    }

    class CartItem {
        -Product product
        -int quantity
        +getSubtotal() double
        +updateQuantity(int qty)
    }

    class Coupon {
        -String code
        -DiscountStrategy strategy
        -double minCartValue
        -boolean active
        +apply(Cart) double
        +isApplicable(Cart) boolean
    }

    class DiscountStrategy {
        <<interface>>
        +calculateDiscount(Cart cart) double
        +getDescription() String
    }

    class PercentageDiscount {
        -double percentage
        +calculateDiscount(Cart) double
    }

    class FlatDiscount {
        -double amount
        +calculateDiscount(Cart) double
    }

    class BuyXGetYDiscount {
        -String productId
        -int buyCount
        -int freeCount
        +calculateDiscount(Cart) double
    }

    class StockObserver {
        <<interface>>
        +onStockUpdated(Product product, int newQty)
        +onOutOfStock(Product product)
    }

    class Cart {
        -Map~String, CartItem~ items
        -List~Coupon~ appliedCoupons
        -StockService stockService
        +addItem(Product, int qty)
        +removeItem(String productId)
        +updateQuantity(String productId, int qty)
        +applyCoupon(Coupon coupon)
        +getSubtotal() double
        +getTotal() double
        +checkout() Order
    }

    class TaxCalculator {
        +calculateTax(CartItem item) double
    }

    class Order {
        -String orderId
        -List~CartItem~ items
        -double subtotal
        -double discount
        -double tax
        -double total
    }

    Cart --> CartItem
    CartItem --> Product
    Cart --> Coupon
    Coupon --> DiscountStrategy
    DiscountStrategy <|.. PercentageDiscount
    DiscountStrategy <|.. FlatDiscount
    DiscountStrategy <|.. BuyXGetYDiscount
    Cart --> TaxCalculator

💡 Reading the arrows: <<interface>> marks a contract with no code of its own, a dashed arrow (DiscountStrategy <|.. FlatDiscount) means “implements that contract”, and a solid arrow means “holds a reference to”. Learn more →

Key classes:

  • Cart — the orchestrator. It owns the items map and the list of applied coupons, and it is where every rule gets enforced: stock checks on add, coupon eligibility, and the checkout sequence.
  • CartItem — owns the pairing of one product with a quantity, and the line-item subtotal that follows from it. It exists so the cart never has to store the same product twice.
  • DiscountStrategy — the contract every discount must satisfy: given a cart, return an amount off. PercentageDiscount, FlatDiscount and BuyXGetYDiscount are three implementations, and a fourth would not touch Cart at all.
  • Coupon — owns the eligibility decision (is the cart above minCartValue, is the code still active) and delegates the arithmetic to its strategy. Separating “may I apply this” from “how much is it worth” is why coupon rules stay readable.
  • StockObserver — the callback contract for stock changes. It exists so the cart can learn that an item went out of stock without repeatedly asking.
  • TaxCalculator — owns tax rules per category and region, kept outside Cart because tax changes far more often than cart mechanics do.
  • Order / OrderBuilder — Order is the immutable receipt (items, subtotal, discount, tax, total); OrderBuilder assembles it field by field so a half-built order can never escape into the system.

Design Patterns

Pattern Where Why
Strategy DiscountStrategy with Percentage/Flat/BuyXGetY implementations New discount types = one new class, zero changes to Cart
Observer StockObserver notified when stock changes Cart reacts to out-of-stock events without polling
Builder OrderBuilder constructs Order step by step Complex order object with many optional fields
Composition Cart HAS CartItems, each HAS Product Clean ownership hierarchy

💡 Strategy pattern = define a family of interchangeable algorithms behind one interface and let the caller plug one in. Here the cart asks whichever discount it holds for an amount, so “add a new discount type” never means editing Cart. Learn more →

💡 Observer pattern = the thing being watched keeps a list of listeners and notifies them on change, so the stock service pushes “this went out of stock” to whoever registered instead of carts polling it in a loop. Learn more →

💡 Builder pattern = assemble an object through a chain of small calls and hand back the finished thing at the end, instead of a constructor with ten arguments you have to remember the order of. Learn more →

💡 Composition means one object holds another and delegates to it (“Cart HAS CartItems”), as opposed to inheritance where one class becomes a kind of another. Composition is the safer default because you can change what an object holds at runtime. Learn more →


Data Structures

Component Structure Why
Cart items ConcurrentHashMap<String, CartItem> O(1) add/remove/update by product ID, thread-safe
Applied coupons ArrayList<Coupon> Ordered application matters (stacking rules)
Product catalog HashMap<String, Product> O(1) product lookup
Stock levels ConcurrentHashMap<String, AtomicInteger> Thread-safe stock decrement

💡 ConcurrentHashMap is a hash map built for many threads at once: it guards only the slice of the map being touched rather than the whole map, so two shoppers editing different carts never wait on each other.