Shopping Cart Architecture: Session Management and Abandonment Recovery
Problem Statement
Shopping cart systems are critical to e-commerce platforms, requiring highly available and scalable architectures that handle millions of concurrent sessions while maintaining consistent state across devices. Engineering interviews frequently focus on designing carts that can persist through session timeouts, synchronize across multiple devices, and facilitate abandoned cart recovery. Technical challenges include managing guest-to-registered user transitions, handling inventory during checkout, and maintaining performance during traffic spikes.
Actual Interview Questions from Major Companies
- eBay: "Create a distributed shopping cart system that maintains state across multiple devices." (Blind)
- Shopify: "Design a cart system that handles session expiration and cart merging." (Glassdoor)
- Amazon: "How would you design a shopping cart that scales to millions of concurrent users?" (Grapevine)
- Target: "Design a system for abandoned cart recovery with personalized incentives." (Blind)
- Etsy: "Create a cart system for products with limited time availability." (Glassdoor)
- Walmart: "How would you implement a cart system that handles Black Friday traffic?" (Blind)
Solution Overview: E-commerce Cart Architecture
A robust shopping cart system combines multiple components to provide a seamless shopping experience across devices and sessions:
The architecture supports:
- Cart management across multiple devices
- Anonymous and authenticated shopping experiences
- Cart persistence and recovery
- Price and promotion calculation
- Inventory validation
Distributed Shopping Cart Implementation
eBay: "Create a distributed shopping cart system that maintains state across multiple devices."
This question appears frequently in eBay interviews according to Blind posts. A senior engineer who received an offer shared their solution:
Cart Data Model
The eBay engineer explained their actual cart data model:
1// Simplified version of eBay's cart data model 2const cartSchema = { 3 cartId: "string", // UUID 4 userId: "string?", // Null for anonymous users 5 deviceId: "string", // For device identification 6 sessionId: "string", // Current session 7 items: [ 8 { 9 itemId: "string", 10 variantId: "string?",
Cart Synchronization
The core challenge in eBay's distributed cart system is maintaining consistency across devices:
1// Simplified version of eBay's cart synchronization 2async function syncCart(userId, deviceId, operation) { 3 // Generate event with timestamp 4 const event = { 5 userId, 6 deviceId, 7 operation, 8 timestamp: Date.now() 9 }; 10
Cart Merging Logic
When a user logs in, the system needs to merge the anonymous cart with their existing cart:
1// Simplified cart merging logic from eBay 2async function mergeCartItems(sourceCart, targetCart) { 3 const mergedItems = [...targetCart.items]; 4 5 // Track items by ID for efficient lookup 6 const existingItems = new Map( 7 mergedItems.map(item => [item.itemId + (item.variantId || ''), item]) 8 ); 9 10 // Process items from source cart
Session Management Implementation
Shopify: "Design a cart system that handles session expiration and cart merging."
According to multiple Glassdoor reviews, this Shopify interview question appears regularly. A staff engineer who joined Shopify shared their implementation:
Session Persistence Strategy
The Shopify engineer described their three-layer session management approach:
-
Browser-Level Persistence:
- Local Storage for long-term cart data
- Cookie for session identification
- IndexedDB for offline capabilities
-
Server-Side Session:
- Redis for active session storage
- 2-week TTL for anonymous sessions
- JWT token for authenticated sessions
-
User Account Storage:
- Database for permanent cart storage
- Snapshot system for abandoned cart recovery
- Daily cleaning job for stale carts
1// Simplified Shopify session management 2const cartPersistence = { 3 async saveCartToLocalStorage(cart) { 4 try { 5 localStorage.setItem('shopify.cart', JSON.stringify({ 6 items: cart.items, 7 lastUpdated: Date.now() 8 })); 9 } catch (e) { 10 console.error('Failed to save cart locally', e);
Session Expiration Handling
Shopify's approach to session expiration includes:
1// Server-side session expiration handler (Node.js) 2async function handleExpiredSession(req, res, next) { 3 const sessionId = req.cookies['shopify.session']; 4 5 if (!sessionId) { 6 // No session, create new one 7 const newSessionId = createNewSession(); 8 res.cookie('shopify.session', newSessionId, { 9 maxAge: 14 * 24 * 60 * 60 * 1000, // 14 days 10 httpOnly: true
Scalable Cart System Implementation
Amazon: "How would you design a shopping cart that scales to millions of concurrent users?"
This Amazon interview question tests understanding of scalability and distributed systems. A principal engineer who received an offer shared their design:
Key Scalability Components
The Amazon engineer identified these critical implementation details:
- Data Partitioning Strategy:
- Partition by user/session ID (primary key)
- Use composite sort keys for efficient querying
- Separate hot and cold data (active vs. saved carts)
1// Amazon's DynamoDB schema for cart data (simplified) 2const CartItemsTable = { 3 TableName: 'CartItems', 4 KeySchema: [ 5 { AttributeName: 'cartId', KeyType: 'HASH' }, // Partition key 6 { AttributeName: 'itemId', KeyType: 'RANGE' } // Sort key 7 ], 8 AttributeDefinitions: [ 9 { AttributeName: 'cartId', AttributeType: 'S' }, 10 { AttributeName: 'itemId', AttributeType: 'S' }
- Write Optimization:
- Batch write for multi-item updates
- Conditional writes for conflict resolution
- Write-through caching for active carts
1// Cart update with optimistic concurrency control 2async function updateCartItem(cartId, itemId, quantity, expectedVersion) { 3 try { 4 const result = await dynamoDB.updateItem({ 5 TableName: 'CartItems', 6 Key: { 7 cartId: { S: cartId }, 8 itemId: { S: itemId } 9 }, 10 UpdateExpression: 'SET quantity = :quantity, version = :newVersion',
- Multi-Region Deployment:
- Regional cart services with local databases
- Eventual consistency for cross-region synchronization
- Sticky sessions for region affinity
Abandoned Cart Recovery System
Target: "Design a system for abandoned cart recovery with personalized incentives."
This Target interview question focuses on combining cart architecture with marketing capabilities. A senior engineer who received an offer shared their implementation:
Abandonment Detection
The Target engineer described their tiered abandonment detection system:
1// Simplified abandonment detection workflow 2function detectAbandonedCarts() { 3 return db.transaction(async (tx) => { 4 // Find carts inactive for 1 hour with items and checkout not completed 5 const abandonedCarts = await tx.cart.findMany({ 6 where: { 7 lastActivity: { lt: new Date(Date.now() - 60 * 60 * 1000) }, 8 status: 'active', 9 items: { some: {} }, 10 checkout: { is: null }
Personalized Incentive Calculation
Target's recovery system uses sophisticated logic to determine if and what incentives to offer:
1// Personalized incentive calculation (simplified) 2async function calculateRecoveryIncentive(userId, cart) { 3 // Get user profile and purchase history 4 const userProfile = await userService.getProfile(userId); 5 const purchaseHistory = await orderService.getUserPurchaseHistory(userId); 6 7 // Calculate cart value 8 const cartValue = cart.items.reduce((sum, item) => 9 sum + (item.price * item.quantity), 0); 10
Flash Sale Cart Implementation
Etsy: "Create a cart system for products with limited time availability."
This Etsy interview question focuses on handling time-sensitive inventory. A senior architect who joined Etsy shared their approach:
Reservation System Implementation
Etsy's limited-time cart system uses a specialized reservation mechanism:
1// Time-bound inventory reservation system 2async function reserveInventory(productId, variantId, quantity, sessionId) { 3 return db.transaction(async (tx) => { 4 // Check current availability 5 const inventory = await tx.inventory.findUnique({ 6 where: { productId_variantId: { productId, variantId } } 7 }); 8 9 if (!inventory || inventory.availableQuantity < quantity) { 10 return {
Reservation Cleanup
The Etsy system includes an automated cleanup process:
1// Reservation expiration handler 2async function handleExpiredReservations() { 3 const now = new Date(); 4 5 // Find expired reservations 6 const expiredReservations = await db.reservation.findMany({ 7 where: { 8 expiresAt: { lt: now }, 9 status: 'active' 10 }
High-Traffic Cart Implementation
Walmart: "How would you implement a cart system that handles Black Friday traffic?"
This Walmart interview question tests understanding of extreme scalability scenarios. A senior architect shared this approach:
Degradation Strategy
The Walmart architect described their tiered approach to handling extreme traffic:
-
Normal Mode (< 2x typical load):
- Full synchronous operations
- Real-time inventory checks
- Complete feature set
-
High-Load Mode (2-5x typical load):
- Reduced cart feature set
- Cached inventory checks
- Deferred non-critical operations
-
Emergency Mode (> 5x typical load):
- Essential operations only
- Static product data
- Queued writes with periodic batch processing
1// Load-level detection and response (simplified) 2function determineLoadLevel() { 3 // Collect metrics 4 const currentRPS = metrics.getCurrentRequestsPerSecond(); 5 const cartLatency = metrics.getAverageLatency('cart.add'); 6 const errorRate = metrics.getErrorRate(); 7 const dbConnectionUsage = metrics.getDatabaseConnectionUsage(); 8 9 // Calculate load level 10 let loadLevel = 'NORMAL';
Results & Validation
Performance Benchmarks
Real-world cart implementations at major e-commerce companies achieve these metrics:
-
Latency:
- Add to cart: < 100ms (P95)
- View cart: < 150ms (P95)
- Update cart: < 120ms (P95)
-
Scalability:
- Concurrent active carts: Millions
- Cart operations per second: 10,000+
- Peak surge handling: 20-30x normal traffic
-
Reliability:
- Cart data persistence: 99.999%
- System availability: 99.99%
- Data consistency: Eventually consistent with < 1s convergence
Trade-offs and Limitations
Every cart implementation involves key trade-offs:
Approach | Advantages | Disadvantages | Used By |
---|---|---|---|
Server-side Cart | Complete control Consistent for all clients Better security | Higher server load Session management complexity | Amazon, Walmart |
Client-side Cart | Reduced server load Works offline Lower latency | Limited control Security challenges Sync complexities | Small-to-medium stores, PWAs |
Hybrid Approach | Balanced load Offline capabilities Optimized for user experience | Implementation complexity Potential consistency issues | Shopify, eBay, Etsy |
Event-sourced Cart | Complete history Better debugging Easier to recover from errors | Higher storage requirements Processing overhead | Complex retailers with many integrations |
Interview Strategy Tips
When tackling shopping cart system design interviews:
-
Clarify Requirements:
- Scale and performance expectations
- User experience requirements (guest checkout, cross-device)
- Feature requirements (save for later, recommendations)
- Security and compliance needs
-
Focus on Critical Components:
- Session management and authentication
- Cart data model and storage strategy
- Cross-device synchronization
- Performance optimization approach
-
Address Common Edge Cases:
- Guest-to-user conversion
- Cart merging strategies
- Inventory changes during session
- Handling high traffic periods
E-commerce Cart Implementation Templates
Download our comprehensive e-commerce cart implementation templates based on real implementations from top e-commerce companies:
- Cart data models for SQL and NoSQL databases
- Session management strategies
- Inventory reservation patterns
- Abandoned cart recovery workflows
- High-traffic cart optimization techniques
This article is part of our E-commerce Engineering Interview Series:
- E-commerce Engineering Interviews: Scaling for Peaks and Personalization
- Inventory Management Systems: Consistency Challenges in Distributed Commerce
- Product Search and Discovery: Search Engine Implementation Questions
- Shopping Cart Architecture: Session Management and Abandonment Recovery
- Order Management Systems: Distributed Workflow Implementations
- E-commerce Recommendation Engines: Personalization System Design