Design an Online Shopping Cart
What is the Online Shopping Cart Problem?
Section titled “What is the Online Shopping Cart Problem?”Design an online shopping cart system that allows customers to add items to their cart, update quantities, apply discounts and coupons, calculate totals (subtotal, tax, shipping, final total), and persist cart state. The system should handle multiple cart items with the same product, validate inventory before checkout, and support various discount strategies and shipping calculations.
In this problem, you’ll design a system that manages items, quantities, and coupons, ensuring that the final “Checkout” total is accurate and transparent.
Problem Overview
Section titled “Problem Overview”Design a robust shopping cart that allows users to aggregate products, apply promotional codes, and transition smoothly into the order creation process.
Core Requirements
Section titled “Core Requirements”Functional Requirements:
- Cart Management: Add, remove, and update quantities; aggregate quantities for duplicate products.
- Inventory Validation: Check availability when adding to cart and prevent checkout if stock is insufficient.
- Discount Strategies: Support percentage, fixed-amount, Buy-X-Get-Y, and category-based discounts using Strategy Pattern.
- Coupon System: Apply coupon codes with validation (minimum order, expiration) to trigger discounts.
- Total Calculation: Compute subtotal, applied discounts, tax (percentage of subtotal), and shipping costs.
- Shipping Strategies: Support fixed, weight-based, distance-based, and free shipping using Strategy Pattern.
- Persistence: Save cart state (serialization) so customers can return later.
- Notifications: Inform customers of price changes or stock updates via Observer Pattern.
- Order Creation: Generate an Order containing all items and cost breakdowns during checkout.
Non-Functional Requirements:
- Thread Safety: Ensure concurrent cart updates from multiple sessions are handled safely.
- Accuracy: Calculations must handle financial precision issues using appropriate numeric types.
- Extensibility: Modular design to easily add new discount types, shipping providers, or tax rules.
- OOD Principles: Well-defined separation between Products, Carts, Strategies, and Observers.
What’s Expected?
Section titled “What’s Expected?”1. System Architecture
Section titled “1. System Architecture”The Cart acts as the central entity, coordinating between Products, DiscountStrategies, and ShippingStrategies.
2. Key Classes to Design
Section titled “2. Key Classes to Design”classDiagram
class Cart {
-List~CartItem~ items
-Coupon appliedCoupon
+addItem(product, qty)
+updateQty(productId, qty)
+calculateTotal()
}
class CartItem {
-Product product
-int quantity
+getSubtotal()
}
class DiscountStrategy {
<<interface>>
+applyDiscount(subtotal)
}
class Coupon {
-String code
-DiscountStrategy strategy
}
Cart "1" *-- "many" CartItem
Cart o-- Coupon
Coupon --> DiscountStrategy
System Flow
Section titled “System Flow”Checkout Calculation Flow
Section titled “Checkout Calculation Flow”Key Design Challenges
Section titled “Key Design Challenges”1. Managing Overlapping Discounts
Section titled “1. Managing Overlapping Discounts”What if a user has a 10% coupon AND a product is already on sale? Should they stack?
Solution: Use the Strategy Pattern. Encapsulate each discount rule in a strategy class. Create a DiscountManager that takes all applicable strategies and chooses the best one (or combines them) based on business logic.
2. Inventory Race Conditions
Section titled “2. Inventory Race Conditions”A user adds the last item to their cart, but while they are shopping, another user completes their checkout.
Solution: Implement Double Validation. Check stock when the item is added to the cart (to provide immediate feedback) and perform a “final check” at the moment of checkout before deducting inventory.
3. Handling Precision
Section titled “3. Handling Precision”Using floating-point numbers (floats/doubles) for currency leads to rounding errors (e.g., $0.1 + 0.2 = 0.30000000004$).
Solution: Always use a language-specific Decimal/Money type (like BigDecimal in Java or Decimal in Python) to ensure financial accuracy.
What You’ll Learn
Section titled “What You’ll Learn”By solving this problem, you’ll master:
- ✅ Strategy Pattern - Building flexible rule engines.
- ✅ State Management - Syncing cart data across sessions.
- ✅ Numerical Accuracy - Handling financial data in software.
- ✅ Separation of Concerns - Isolating tax, shipping, and core cart logic.
View Complete Solution & Practice
Section titled “View Complete Solution & Practice”Ready to see the full implementation? Open the interactive playground to access:
- 🎯 Step-by-step guidance through the 8-step LLD approach
- 📊 Interactive UML builder to visualize your design
- 💻 Complete Code Solutions in Python, Java, C++, TypeScript, JavaScript, C#
- 🤖 AI-powered review of your design and code
Related Problems
Section titled “Related Problems”After mastering the Shopping Cart, try these similar problems:
- Payment Processor - Handling transactions and refunds.
- Vending Machine - Simple inventory and change logic.
- Restaurant Management - Orders, menus, and bill splitting.