Bird
Raised Fist0
LLDsystem_design~25 mins

Product, Cart, Order classes in LLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: E-commerce Cart and Order Management
Design focuses on the core classes and their interactions for product catalog, cart management, and order processing. Payment, shipping, and user authentication are out of scope.
Functional Requirements
FR1: Allow users to browse products with details like name, price, and stock quantity
FR2: Users can add products to a shopping cart with specified quantities
FR3: Users can update or remove items in the cart
FR4: Users can place orders from their cart
FR5: Orders should capture product details, quantities, prices, and total amount
FR6: Support multiple users with separate carts and orders
Non-Functional Requirements
NFR1: Handle up to 10,000 concurrent users
NFR2: Ensure cart updates and order placements have p99 latency under 200ms
NFR3: Maintain data consistency between cart and order
NFR4: Availability target of 99.9% uptime
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
Product catalog management
Cart service to manage user carts
Order service to process and store orders
Database or in-memory storage for persistence
APIs for user interactions
Design Patterns
Domain-Driven Design for modeling Product, Cart, and Order entities
Event-driven updates for stock changes
Repository pattern for data access abstraction
Transactional consistency for order placement
Reference Architecture
  +-------------+       +------------+       +------------+
  |   Product   |<----->|    Cart    |<----->|   Order    |
  +-------------+       +------------+       +------------+
        ^                     ^                    ^
        |                     |                    |
  Product Catalog       User Session          Order History
  (Database)            (In-Memory/DB)        (Database)
Components
Product
Class with attributes
Represents items available for purchase with details like id, name, price, and stock quantity
Cart
Class with collection of CartItems
Holds products selected by a user with quantities before order placement
Order
Class capturing finalized purchase details
Records purchased products, quantities, prices, total amount, and order status
Request Flow
1. User browses products from Product catalog
2. User adds product with quantity to Cart
3. Cart updates item quantities or removes items as requested
4. User places order from Cart
5. Order is created with snapshot of Cart items and prices
6. Stock quantity in Product catalog is updated accordingly
7. Order status is tracked until completion
Database Schema
Entities: - Product(id PK, name, price, stock_quantity) - Cart(id PK, user_id FK) - CartItem(id PK, cart_id FK, product_id FK, quantity) - Order(id PK, user_id FK, total_amount, status, created_at) - OrderItem(id PK, order_id FK, product_id FK, quantity, price_at_purchase) Relationships: - One Product can be in many CartItems and OrderItems - One Cart has many CartItems - One Order has many OrderItems - User has one Cart and many Orders
Scaling Discussion
Bottlenecks
Database contention on Product stock updates during high order volume
Cart data consistency when multiple devices update simultaneously
Latency in order placement under heavy load
Storage growth for order history over time
Solutions
Use optimistic locking or versioning on Product stock to prevent overselling
Implement distributed locks or atomic operations for Cart updates
Introduce caching layers and asynchronous processing for order creation
Archive old orders and use partitioned databases for scalability
Interview Tips
Time: Spend 10 minutes clarifying requirements and constraints, 20 minutes designing classes and their interactions, 10 minutes discussing scaling and trade-offs, and 5 minutes summarizing.
Explain clear separation of concerns between Product, Cart, and Order
Discuss data consistency challenges and solutions
Highlight how the design supports multiple users and concurrent updates
Mention scalability considerations and how to handle growth
Show understanding of real-world e-commerce workflows

Practice

(1/5)
1. Which class is responsible for storing the details like product ID, name, and price?
easy
A. Product class
B. Cart class
C. Order class
D. User class

Solution

  1. Step 1: Understand the role of Product class

    The Product class stores item details such as ID, name, and price.
  2. Step 2: Compare with other classes

    The Cart class holds selected products and quantities, and Order class records purchased items and status, not product details.
  3. Final Answer:

    Product class -> Option A
  4. Quick Check:

    Product details = Product class [OK]
Hint: Product details belong to Product class only [OK]
Common Mistakes:
  • Confusing Cart with Product class
  • Thinking Order stores product details
  • Assuming User class stores product info
2. Which of the following is the correct way to add a product to a cart in a typical class design?
easy
A. order.addProduct(product, quantity)
B. product.addToCart(cart, quantity)
C. cart.addProduct(product, quantity)
D. cart.createOrder(product, quantity)

Solution

  1. Step 1: Identify the class responsible for holding selected products

    The Cart class holds selected products and their quantities before purchase.
  2. Step 2: Check method naming conventions

    Adding a product to a cart is typically done by calling a method on the Cart object, like addProduct(product, quantity).
  3. Final Answer:

    cart.addProduct(product, quantity) -> Option C
  4. Quick Check:

    Adding product to cart = cart.addProduct() [OK]
Hint: Add products via Cart methods, not Product or Order [OK]
Common Mistakes:
  • Calling addToCart on Product class
  • Using Order class to add products before purchase
  • Confusing method names like createOrder in Cart
3. Given the following code snippet, what will be the total cost stored in the Order after checkout?
product1 = Product(id=1, name='Pen', price=2)
product2 = Product(id=2, name='Notebook', price=5)
cart = Cart()
cart.addProduct(product1, 3)
cart.addProduct(product2, 2)
order = Order(cart)
order.checkout()
medium
A. 16
B. 19
C. 10
D. 7

Solution

  1. Step 1: Calculate total cost from cart products and quantities

    Pen price = 2, quantity = 3 -> 2 * 3 = 6
    Notebook price = 5, quantity = 2 -> 5 * 2 = 10
    Total = 6 + 10 = 16
  2. Step 2: Check if any additional charges or taxes apply

    No extra charges mentioned, so total cost should be 16.
  3. Final Answer:

    16 -> Option A
  4. Quick Check:

    2*3 + 5*2 = 16 [OK]
Hint: Multiply price by quantity, then sum all products [OK]
Common Mistakes:
  • Adding quantities instead of multiplying by price
  • Mixing product prices and quantities incorrectly
  • Ignoring one product's cost
4. Identify the error in this Order class method that calculates total cost:
class Order:
def __init__(self, cart):
self.cart = cart
self.total = 0
def calculate_total(self):
for product, qty in self.cart.items():
self.total += product.price * qty
return self.total
medium
A. Returning total instead of printing it
B. Using self.cart.items() instead of self.cart.products.items()
C. Multiplying price by quantity incorrectly
D. Not resetting self.total before calculation

Solution

  1. Step 1: Analyze total calculation logic

    The method adds product price times quantity to self.total in a loop.
  2. Step 2: Check for accumulation errors

    Since self.total is not reset before calculation, repeated calls will add to previous total, causing incorrect sums.
  3. Final Answer:

    Not resetting self.total before calculation -> Option D
  4. Quick Check:

    Reset total before sum to avoid accumulation [OK]
Hint: Reset totals before summing to avoid repeated addition errors [OK]
Common Mistakes:
  • Assuming cart.items() is invalid without context
  • Thinking multiplication is wrong when it is correct
  • Confusing return with print for output
5. You want to design a system where a Cart can hold multiple Products with quantities, and an Order records the purchased items and status. Which design choice best supports scalability and clear responsibility?
hard
A. Make Cart store product IDs only; Order stores full product details and quantities
B. Make Cart hold Product objects with quantities; Order copies Cart items and tracks status separately
C. Make Product class hold quantity and add methods to update Cart and Order directly
D. Make Order class inherit from Cart and add status and total cost fields

Solution

  1. Step 1: Understand separation of concerns

    Cart should hold selected products and quantities before purchase. Order should record purchased items and status separately.
  2. Step 2: Evaluate design options for scalability and clarity

    Make Cart hold Product objects with quantities; Order copies Cart items and tracks status separately keeps Cart holding Product objects with quantities, and Order copies these items to keep a snapshot and track status, which is clean and scalable.
  3. Final Answer:

    Make Cart hold Product objects with quantities; Order copies Cart items and tracks status separately -> Option B
  4. Quick Check:

    Separate Cart and Order responsibilities for scalability [OK]
Hint: Keep Cart and Order responsibilities separate and clear [OK]
Common Mistakes:
  • Making Order inherit Cart causing tight coupling
  • Storing only product IDs in Cart losing details
  • Putting quantity in Product class mixing concerns