MongoDB

Designing a Shopping Cart System

Build a high-performance shopping cart — covering guest vs authenticated carts, session management, price consistency, and cart merging.

S

srikanthtelkalapally888@gmail.com

Designing a Shopping Cart System

A shopping cart is a temporary holding area for items before checkout. It must be fast, persistent across sessions, and handle edge cases like guest users.

Cart Types

Guest Cart:         Stored in browser cookie + server session
Authenticated Cart: Stored server-side (Redis / DB)

Data Model

{
  "cart_id": "cart_abc123",
  "user_id": "user_456",    
  "session_id": "sess_789",  
  "items": [
    {
      "product_id": "prod_001",
      "sku": "RED-L",
      "quantity": 2,
      "price_snapshot": 29.99,
      "added_at": "2026-03-12T10:00:00Z"
    }
  ],
  "updated_at": "2026-03-12T10:30:00Z"
}

Storage Strategy

Redis Hash per cart:
  cart:{cart_id} → JSON blob
  TTL: 30 days for authenticated
       7 days for guest

Cart Merging

When guest user logs in:

1. Retrieve guest cart (from session)
2. Retrieve user's saved cart
3. Merge items:
   - Same product: sum quantities
   - Different products: combine
4. Delete guest cart
5. Update user cart

Price Consistency

Don't trust client-side prices. Store price_snapshot at time of add:

At checkout time:
  Fetch current prices from Product Service
  If price changed: notify user, update snapshot
  Never charge old lower price (fraud prevention)

Inventory Soft-Hold

Don't reserve inventory when adding to cart (premature). Reserve only at checkout start:

Checkout initiated → Reserve items for 10 min
Payment complete  → Deduct from inventory
Payment fails     → Release hold
Timeout           → Auto-release

Cart Recovery

  • Email users with abandoned carts after 1 hour
  • "You left something behind" campaigns
  • Store cart server-side for 30 days

Conclusion

Redis-backed carts with TTL, server-side price validation, and checkout-time inventory reservation are the pillars of a robust cart system.

Share this article