HLD of Shopping Cart

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2022-05-27

Problem Statement

Designing the Shopping Cart service of an e-commerce platform (like Amazon/Flipkart). The system should allow users to add, remove, and update items in their cart, while ensuring scalability, availability, and data consistency across millions of concurrent users.


Functional Requirements


1.User Cart Management
•Create a cart for each user (guest + registered).
•Add, update, or remove products in the cart.
•Support multiple carts per user (e.g., wishlist vs checkout cart).
2.Product & Inventory Validation
•Check item availability and pricing in real time.
•Handle promotions, discounts, and coupons.
3.Persistence
•Cart should be durable (available across sessions and devices).
•Support cart recovery for abandoned carts.
4.Checkout Support
•Convert cart items into an order.
•Lock inventory during checkout to avoid overselling.
5.Concurrency Handling
•Ensure updates from multiple sessions/devices do not conflict.


Non-Functional Requirements


•Scalability → Handle millions of concurrent carts and requests.
•Low Latency → Cart operations must be fast (<100ms).
•High Availability → No downtime during sales/flash events.
•Consistency → Show correct prices and quantities.
•Fault Tolerance → Recover from server crashes without data loss.


Design Considerations


•Cart Storage
•In-memory store (Redis/Memcached) for quick reads/writes.
•Persistent DB (SQL/NoSQL) for long-term durability.
•TTL for guest carts.
•APIs
•createCart(userId)
•addItem(userId, productId, quantity)
•removeItem(userId, productId)
•updateItem(userId, productId, quantity)
•getCart(userId)
•checkoutCart(userId)
•Architecture
•Microservices approach: Cart Service, Product Service, Inventory Service, Pricing Service.
•Use event-driven design (Kafka/RabbitMQ) to sync prices, stock, and promotions.
•Concurrency Control
•Optimistic locking for cart updates.
•Distributed locks for checkout (to prevent race conditions).
•Performance Enhancements
•Cache cart items close to the user (edge caching/CDN for static product data).
•Use sharding/partitioning for cart storage.


Example HLD Components


•Cart Service → Core service for managing user carts.
•Product & Pricing Service → Provides updated product details.
•Inventory Service → Validates stock availability.
•Order Service → Converts cart into an order.
•Notification Service → Alerts for stock out / price changes.
•Cache Layer (Redis) → Fast cart retrieval.
•Database Layer (NoSQL/SQL) → Persistent storage of carts.


Solution

Comments