Shopping Cart Architecture
Learn Shopping Cart Architecture as part of the Domain Knowledge learning path for software engineers and architects.
A shopping cart is one of the most important components of an e-commerce platform. It allows customers to collect products, select variants and quantities, review estimated prices, apply promotions, and prepare their selections for checkout.
Although a shopping cart may look like a simple list of products on the screen, the underlying system must solve several challenging engineering problems. It must preserve cart state across sessions, support guest and authenticated customers, handle concurrent updates, validate product availability, calculate totals correctly, and integrate with pricing, promotion, inventory, identity, and order management systems.
For software engineers and solution architects, designing a shopping cart means balancing responsiveness, consistency, scalability, and a smooth customer experience.
This article explains shopping cart architecture from business concepts to domain modeling, API design, Java and Spring Boot implementation, distributed system patterns, security, scalability, and production operations.
Learning Flow
flowchart TD
A[Shopping Cart Fundamentals] --> B[Cart Domain Model]
B --> C[Guest and Authenticated Carts]
C --> D[Cart APIs and Persistence]
D --> E[Pricing and Promotions]
E --> F[Inventory Validation]
F --> G[Checkout Preparation]
G --> H[Java and Spring Boot]
H --> I[Concurrency and Distributed Systems]
I --> J[Security and Observability]
J --> K[Hands-on Shopping Cart Project]
1. What Is a Shopping Cart?
A shopping cart is a stateful commerce capability that maintains a customer's intended purchase before an order is created.
For example, a customer visits an online store and adds:
- Two wireless headphones
- One laptop
- Three USB-C cables
The cart stores the selected products and quantities, along with relevant references to product variants. The customer can return later, change quantities, remove items, review estimated totals, and proceed to checkout.
The cart is not the same as an order. A cart represents purchase intent; an order represents a transaction that has been accepted by the commerce platform according to its order-creation rules.
1.1 Core shopping cart responsibilities
A typical cart service supports:
- Creating a cart
- Adding an item
- Updating item quantities
- Removing an item
- Retrieving cart details
- Merging a guest cart into a customer cart
- Validating product and variant references
- Recalculating price estimates
- Applying promotion information
- Preparing a cart for checkout
- Expiring inactive carts
- Handling concurrent updates
- Tracking cart lifecycle and audit events
Not every implementation needs a separate microservice. A modular commerce application may implement the cart as a module, while a large platform may operate it as an independently deployed service.
1.2 Why shopping cart design matters
Poor cart behavior can directly affect revenue and customer trust.
Examples include:
- A cart disappears when the customer signs in.
- A quantity update silently overwrites another update.
- A promotion appears valid but fails unexpectedly at checkout.
- A stale product reference causes a checkout failure.
- The cart displays an incorrect total.
- A guest cart cannot be merged safely with an existing customer cart.
- A slow inventory service prevents customers from viewing their carts.
The architecture should make normal cart operations fast and predictable while ensuring that the final purchase is validated against authoritative systems.
2. Shopping Cart Versus Checkout Versus Order
These concepts are related but have different responsibilities.
| Capability | Shopping cart | Checkout | Order management |
|---|---|---|---|
| Primary purpose | Maintain purchase intent | Validate and submit a purchase | Manage an accepted order |
| Product selection | Core responsibility | Uses selected cart items | Preserves ordered items |
| Quantity updates | Supported | Usually limited or frozen during submission | Governed by order-change rules |
| Price | Estimated or refreshed | Validates final applicable price | Preserves purchase-time price |
| Promotions | Evaluates or previews eligibility | Confirms applicable discounts | Records accepted discount details |
| Inventory | May check availability | Coordinates reservation or validation | Tracks fulfillment-related commitments |
| Payment | Usually no payment capture | Coordinates payment authorization and related steps | Tracks payment state through integration |
| Order identifier | Usually absent | Obtains or creates order identity | Core responsibility |
| Lifecycle | Active, expired, converted | In progress, submitted, failed | Created, confirmed, fulfilled, cancelled, and other states |
A cart total is generally an estimate until the checkout process validates the final terms. Taxes, shipping, discounts, and inventory can change based on address, customer eligibility, delivery method, or current business rules.
Architectural principle: Do not treat the shopping cart as the authoritative record of a completed purchase.
3. High-Level Shopping Cart Architecture
A shopping cart sits between the storefront and several commerce services.
flowchart TD
A[Web / Mobile Storefront] --> B[API Gateway / BFF]
B --> C[Shopping Cart Service]
C --> D[(Cart Database)]
C --> E[Catalog Service]
C --> F[Pricing Service]
C --> G[Promotion Service]
C --> H[Inventory Service]
C --> I[Identity Service]
C --> J[Cache]
C --> K[Event Outbox]
K --> L[Event Broker]
L --> M[Analytics]
L --> N[Cart Recovery]
B --> O[Checkout Service]
O --> P[Order Management]
O --> Q[Payment Service]
O --> R[Inventory Reservation]
This is a logical architecture. In a smaller platform, some components may be combined. In a large platform, each may be independently scaled and owned.
3.1 Storefront
The storefront provides the customer experience for adding products, updating quantities, viewing totals, and beginning checkout.
The browser or mobile application may keep a temporary UI representation of the cart, but the server should remain authoritative for persisted cart state.
3.2 API gateway or backend-for-frontend
The gateway handles cross-cutting concerns such as routing, authentication enforcement, rate limiting, and request tracing.
A backend-for-frontend (BFF) can shape responses for a particular client. For example, a mobile application may need a compact cart summary while a desktop storefront may need additional presentation details.
The gateway should not become the home of complex cart business rules.
3.3 Shopping cart service
The cart service owns cart lifecycle and item-selection behavior.
Its responsibilities usually include:
- Cart creation and retrieval
- Item addition and removal
- Quantity updates
- Cart ownership and access control
- Version management
- Guest-cart handling
- Cart expiration
- Checkout eligibility checks
- Cart event publication
3.4 Catalog service
The catalog supplies product and variant information, including identifiers, names, and descriptions.
The cart should normally store stable product and variant identifiers rather than duplicating the entire catalog record. It may cache display snapshots for responsiveness, but these snapshots must not become the authoritative catalog.
3.5 Pricing and promotion services
Pricing determines applicable prices. Promotion services evaluate discounts and eligibility rules.
The cart can request current price and promotion information to display an estimate. Checkout must revalidate the applicable commercial terms before accepting the purchase.
3.6 Inventory service
Inventory determines whether a SKU is available in a relevant location or fulfillment network.
A cart may display availability information, but adding an item to the cart does not necessarily reserve inventory. Reservation usually occurs during checkout or a specific purchasing workflow.
3.7 Checkout service
Checkout coordinates the transition from purchase intent to order creation. It may validate the cart, calculate taxes and shipping, reserve inventory, authorize payment, and invoke order management.
The exact sequence depends on the business's transaction model and failure-handling requirements.
4. Shopping Cart Domain Model
A useful cart model separates the cart, cart items, customer identity, and any associated checkout attempt.
4.1 Core entities
Cart
Represents a customer's current purchase intent.
Typical fields:
- Cart ID
- Customer ID, if authenticated
- Guest-session reference, if applicable
- Cart status
- Currency
- Version
- Creation and update timestamps
- Expiration timestamp
Cart item
Represents a selected product variant and quantity.
Typical fields:
- Cart item ID
- Cart ID
- Product ID
- Variant ID or SKU reference
- Quantity
- Optional display snapshot
- Creation and update timestamps
Promotion reference
Represents a customer-selected coupon or promotion code. Its presence does not guarantee that the discount remains valid.
Checkout attempt
Represents a particular attempt to submit a cart. It helps track retries and prevents duplicate order creation.
4.2 Entity relationship diagram
erDiagram
CUSTOMER ||--o{ CART : owns
CART ||--o{ CART_ITEM : contains
CART ||--o{ CART_PROMOTION : references
CART ||--o{ CHECKOUT_ATTEMPT : has
CART {
UUID id
UUID customer_id
string guest_session_ref
string status
string currency
bigint version
timestamp created_at
timestamp updated_at
timestamp expires_at
}
CART_ITEM {
UUID id
UUID cart_id
UUID product_id
UUID variant_id
int quantity
timestamp created_at
timestamp updated_at
}
CART_PROMOTION {
UUID id
UUID cart_id
string promotion_code
}
CHECKOUT_ATTEMPT {
UUID id
UUID cart_id
string idempotency_key
string status
string order_id
}
The diagram is a starting point. A real schema may include tenant identifiers, seller identifiers, fulfillment groups, item-level customization, and additional audit information.
4.3 Should cart items store prices?
This is a key design decision.
One option is to store only product references and quantity, then request current pricing when the cart is displayed.
Another option is to store a price snapshot for display or comparison purposes.
A practical design may store:
- Product and variant identifiers
- Quantity
- The last displayed price snapshot, if useful
- Currency
- Price observation timestamp or version
The price snapshot is not automatically the final agreed purchase price. Checkout must apply the business's price-validity and repricing rules.
Never rely on a price sent by the browser as the authoritative amount to charge.
5. Cart Lifecycle
A shopping cart typically has a lifecycle independent of the order lifecycle.
stateDiagram-v2
[*] --> Active
Active --> Active: Add / Update / Remove Item
Active --> CheckoutPending: Start Checkout
CheckoutPending --> Converted: Order Accepted
CheckoutPending --> Active: Recoverable Failure
CheckoutPending --> Abandoned: Checkout Abandoned
Active --> Expired: Expiration Policy
Abandoned --> Active: Customer Returns
Expired --> Active: Restore If Policy Allows
Converted --> [*]
This is an illustrative state model. Some systems do not need explicit Abandoned or CheckoutPending states in the cart table and instead track them through checkout attempts and analytics events.
5.1 Active
The customer can add items, change quantities, and remove selections.
5.2 Checkout pending
A checkout attempt is underway. The cart may be protected from conflicting changes or the checkout service may work against a stable cart version.
The system should define what happens if the customer modifies the cart in another browser tab during checkout.
5.3 Converted
The cart has been associated with an accepted order according to the platform's order-creation rules.
The cart or its snapshot may be retained for support, analytics, and audit purposes, but it should no longer behave as an ordinary active cart.
5.4 Expired
An inactive cart may be marked expired after a configured period.
Expiration should be a business policy rather than an assumption that all carts disappear after the same duration. Customer account carts may have different retention requirements from anonymous session carts.
5.5 Abandoned
An abandoned cart represents purchase intent that did not result in a completed order within the business's defined measurement window.
Abandonment is often an analytics concept rather than a permanent cart status. A customer can return later and continue shopping.
6. Guest Carts and Authenticated Carts
Most e-commerce platforms support both anonymous visitors and signed-in customers.
6.1 Guest cart
A guest cart is associated with an anonymous session or a server-issued cart token.
Typical behavior:
- A visitor opens the storefront.
- The application obtains a cart session.
- The visitor adds products.
- The cart service persists the cart.
- The visitor returns while the session remains valid.
The guest identity should not depend on trusting an arbitrary cart ID supplied by the client. The server must verify that the request is authorized to access the cart.
6.2 Authenticated cart
An authenticated cart is associated with a customer identity established through the platform's identity and authorization mechanisms.
A customer may access their cart from multiple devices. The platform needs to define whether there is one active cart per customer, multiple carts, or carts scoped by region, channel, or currency.
6.3 Cart merge after login
Suppose a guest has three items and an existing customer cart has two items. When the guest signs in, the platform may merge the two carts.
Example:
Guest Cart
----------
SKU-A: 2
SKU-B: 1
Customer Cart
-------------
SKU-A: 1
SKU-C: 3
Merged Cart
-----------
SKU-A: 3
SKU-B: 1
SKU-C: 3
This example uses quantity addition for matching SKUs. It is only one possible policy.
Other merge policies include:
- Prefer the authenticated cart's quantity
- Prefer the most recently updated item
- Apply a maximum allowed quantity
- Reject or flag incompatible variants
- Revalidate products and promotions before merging
The merge operation should be atomic or protected against partial completion. If it is retried, it must not add the guest quantities repeatedly.
6.4 Guest cart security
A guest cart token is effectively a capability to access that cart. Protect it carefully.
Use secure, high-entropy tokens, avoid exposing sensitive cart data in URLs, and apply appropriate cookie settings when cookies are used.
A guest token must not grant access to customer account information or other carts. Authentication and authorization checks remain necessary after login and during cart merging.
7. Shopping Cart REST API Design
A REST API should make cart operations clear, consistent, and safe to retry where appropriate.
7.1 Common endpoints
POST /api/store/v1/carts
GET /api/store/v1/carts/{cartId}
POST /api/store/v1/carts/{cartId}/items
PATCH /api/store/v1/carts/{cartId}/items/{itemId}
DELETE /api/store/v1/carts/{cartId}/items/{itemId}
DELETE /api/store/v1/carts/{cartId}/items
POST /api/store/v1/carts/{cartId}/promotions
DELETE /api/store/v1/carts/{cartId}/promotions/{promotionCode}
POST /api/store/v1/carts/{cartId}/checkout
The checkout endpoint may belong to a dedicated checkout service rather than the cart service. The API boundary should reflect service ownership.
7.2 Create a cart
Request:
POST /api/store/v1/carts
Content-Type: application/json
{
"currency": "USD"
}
Example response:
{
"cartId": "7f9d5f9a-6e35-4a2e-87d2-b19f0d2f1a12",
"status": "ACTIVE",
"currency": "USD",
"items": [],
"version": 0
}
In production, the server should determine or validate the currency against the storefront, customer, and market rules. Do not blindly accept arbitrary currency values from the client.
7.3 Add an item
Request:
POST /api/store/v1/carts/{cartId}/items
Content-Type: application/json
{
"variantId": "e22c14b4-a8d9-4fd0-80fd-3d7eaa9a19f1",
"quantity": 2
}
The cart service should validate the identifier and quantity. It may verify that the variant exists and is eligible for cart selection.
A product being eligible for the cart does not guarantee it will still be available when the customer submits the order.
7.4 Update item quantity
Request:
PATCH /api/store/v1/carts/{cartId}/items/{itemId}
Content-Type: application/json
{
"quantity": 3
}
Define the semantics explicitly:
- Quantity greater than zero updates the item.
- Quantity equal to zero may remove the item if the API contract supports it.
- Negative quantities are rejected.
- Maximum quantity and purchase limits are enforced by business rules.
An alternative is to use DELETE to remove an item, keeping update and removal behavior separate.
7.5 Idempotency and retries
Network requests can time out after the server has already processed them.
If the client retries an add item operation, the system must know whether the retry should create another unit, add a new line, or return the original result.
These are different semantics:
- Set quantity: set the line quantity to three. Repeating the request leaves it at three.
- Increment quantity: add one unit. Repeating the request could add two units unless the operation is protected.
- Add item: create or merge an item according to the documented contract.
Use idempotency keys where appropriate, particularly for operations that create checkout attempts or can trigger external side effects. For simple cart mutations, also consider version checks and explicit quantity semantics.
8. Price Calculation and Cart Totals
Displaying an accurate estimate requires careful separation of product data, price rules, discounts, tax, and shipping.
A simplified cart calculation is:
[ \text{Subtotal} = \sum_{i=1}^{n}(\text{Unit Price}_i \times \text{Quantity}_i) ]
[ \text{Estimated Total} = \text{Subtotal} - \text{Discounts}
- \text{Estimated Tax}
- \text{Estimated Shipping} ]
This is a simplified model. Actual commerce calculations may include fees, deposits, duties, item-level taxes, rounding rules, and more complex discount allocation.
8.1 Example calculation
Suppose a cart contains:
| Item | Unit price | Quantity | Line subtotal |
|---|---|---|---|
| Headphones | $80.00 | 1 | $80.00 |
| USB-C cable | $12.00 | 2 | $24.00 |
| Laptop stand | $35.00 | 1 | $35.00 |
| Subtotal | $139.00 |
If an eligible discount is $10, estimated tax is $9, and shipping is $5, then:
[ 139 - 10 + 9 + 5 = 143 ]
The estimated total is $143.00.
The actual tax and shipping may change after the customer provides the delivery address and selects a shipping method.
8.2 Money representation
Avoid using binary floating-point types such as float or double for monetary calculations.
In Java, use BigDecimal with explicit scale and rounding rules, or use an integer minor-unit representation when the currency and calculation model support it.
Example:
import java.math.BigDecimal;
import java.math.RoundingMode;
public final class MoneyCalculator {
private MoneyCalculator() {
}
public static BigDecimal lineSubtotal(
BigDecimal unitPrice,
int quantity) {
if (unitPrice == null || unitPrice.signum() < 0) {
throw new IllegalArgumentException(
"Unit price must be non-negative");
}
if (quantity <= 0) {
throw new IllegalArgumentException(
"Quantity must be greater than zero");
}
return unitPrice
.multiply(BigDecimal.valueOf(quantity))
.setScale(2, RoundingMode.HALF_UP);
}
}
This example uses two decimal places for illustration. Currency-specific precision and rounding rules should be configured explicitly. Some currencies use different minor-unit scales, and tax calculations may require intermediate precision before final rounding.
8.3 Price authority
The cart service should not trust a price submitted by the browser.
A safer flow is:
- The customer selects a product variant.
- The cart service records the variant and quantity.
- The pricing service provides an applicable price or quote.
- The cart displays the latest estimate.
- Checkout validates the applicable price again.
- The order records the accepted purchase-time amounts.
The business must define what happens when the price changes between cart creation and checkout. Some platforms notify the customer; others require explicit confirmation for material changes.
9. Promotion and Coupon Handling
Promotions may depend on many conditions:
- Minimum order value
- Eligible products or categories
- Customer segment
- Geographic market
- Promotion dates
- Usage limits
- Coupon eligibility
- Quantity thresholds
- Stacking rules
- Excluded items
The cart can request a discount estimate, but final eligibility should be evaluated under the checkout rules.
9.1 Example promotion
Suppose a promotion offers 10% off eligible accessories when the customer purchases at least $50 of qualifying products.
The promotion service must determine:
- Which cart lines are eligible.
- Whether their combined value reaches the threshold.
- Whether other promotions conflict.
- Whether the customer has exceeded usage limits.
- How the discount is allocated across eligible lines.
A cart should not simply subtract 10% from every item unless that is exactly how the promotion is defined.
9.2 Store promotion references, not unquestioned discounts
The cart may store a promotion code selected by the customer. It can also store the latest displayed discount estimate for user experience.
However, checkout should revalidate the code, eligibility, dates, and stacking rules. A stored discount estimate is not necessarily a guaranteed discount.
9.3 Promotion failure behavior
If a promotion becomes invalid, provide a clear response.
For example:
- The coupon has expired.
- The minimum spend requirement is no longer met.
- The promotion excludes one of the selected products.
- The customer has already reached the usage limit.
Avoid silently changing the total without explaining the reason to the customer.
10. Inventory Availability and Reservation
A cart and an inventory reservation serve different purposes.
A cart expresses what a customer intends to purchase. An inventory reservation temporarily allocates stock according to a business workflow.
10.1 Why adding to cart does not always reserve stock
If every cart reserved inventory indefinitely, inactive carts could block stock for customers who are ready to buy.
For that reason, many systems check availability when displaying the cart but reserve inventory during checkout.
Some businesses do reserve inventory earlier, such as during ticketing, limited-release products, or high-demand sales. Those systems require explicit reservation expiration and release policies.
10.2 Availability can change
A cart may show that five units are available. Before checkout, another customer may purchase the remaining stock.
The cart service should not promise that availability is guaranteed unless the inventory service has confirmed a valid reservation.
10.3 Typical checkout reservation flow
sequenceDiagram
participant Customer
participant Checkout
participant Cart
participant Inventory
participant Payment
participant Order
Customer->>Checkout: Submit checkout
Checkout->>Cart: Validate cart version
Cart-->>Checkout: Current cart items
Checkout->>Inventory: Reserve required quantities
Inventory-->>Checkout: Reservation result
Checkout->>Payment: Authorize payment
Payment-->>Checkout: Authorization result
Checkout->>Order: Create order
Order-->>Checkout: Order accepted
Checkout-->>Customer: Confirmation
This is an illustrative happy path. Real implementations must define what happens if payment authorization fails, order creation fails, or an inventory reservation expires.
If a downstream step fails, the workflow may need to release inventory, void a payment authorization, retry safely, or enter a recoverable state.
11. Cart Persistence and Storage Design
Shopping carts need persistence so customers can return after navigating away, closing a browser, or signing in on another device.
11.1 Relational database
A relational database is a strong choice when the cart requires transactions, constraints, customer relationships, and reliable updates.
Advantages include:
- Transactional updates
- Foreign keys and constraints
- Structured queries
- Mature backup and recovery
- Clear consistency behavior
Challenges include high read/write volume, contention on heavily updated carts, and the need for careful indexing.
11.2 Key-value or document store
A key-value or document database can work well when the application frequently reads and writes an entire cart as a document.
Example:
{
"cartId": "cart-100",
"customerId": "customer-200",
"currency": "USD",
"version": 7,
"items": [
{
"variantId": "variant-101",
"quantity": 2
},
{
"variantId": "variant-205",
"quantity": 1
}
],
"status": "ACTIVE"
}
Advantages include simple retrieval by cart ID and flexible document structure.
Challenges include concurrent document updates, schema evolution, and the need to prevent one request from overwriting another request's changes.
11.3 Cache
A cache can reduce repeated database reads for active carts, but it should not be treated as the only durable store unless the chosen data platform explicitly provides the required durability and recovery guarantees.
For cart updates, cache invalidation and concurrent writes require special care.
A practical starting architecture is a durable database with optional caching for measured hot paths. Add a cache only when workload measurements justify the complexity.
11.4 Sample relational schema
CREATE TABLE carts (
id UUID PRIMARY KEY,
customer_id UUID NULL,
guest_session_ref VARCHAR(200) NULL,
status VARCHAR(30) NOT NULL,
currency CHAR(3) NOT NULL,
version BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP NULL
);
CREATE INDEX idx_carts_customer_status
ON carts(customer_id, status);
CREATE TABLE cart_items (
id UUID PRIMARY KEY,
cart_id UUID NOT NULL REFERENCES carts(id),
variant_id UUID NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
CREATE INDEX idx_cart_items_cart_id
ON cart_items(cart_id);
CREATE TABLE checkout_attempts (
id UUID PRIMARY KEY,
cart_id UUID NOT NULL REFERENCES carts(id),
idempotency_key VARCHAR(200) NOT NULL,
status VARCHAR(30) NOT NULL,
order_id VARCHAR(100) NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL,
CONSTRAINT uq_checkout_idempotency
UNIQUE (idempotency_key)
);
This is an illustrative schema. Production implementations may require a tenant or customer scope on the idempotency key, additional constraints, database-specific timestamp types, and a stronger model for checkout state transitions.
The schema deliberately does not store a final order total in the cart table as the authoritative amount. A cart total can be derived from the latest applicable pricing and checkout calculations.
12. Implementing a Shopping Cart with Java and Spring Boot
Let's build a simplified shopping cart service using Java, Spring Boot, Spring Data JPA, and a relational database.
The example covers the core cart and cart-item entities, quantity validation, and basic cart operations. It is a learning implementation, not a complete production checkout system.
12.1 Define the cart status
public enum CartStatus {
ACTIVE,
CHECKOUT_PENDING,
CONVERTED,
ABANDONED,
EXPIRED
}
The exact states depend on business requirements. Keep the state machine as simple as possible while still representing meaningful business transitions.
12.2 Define the cart entity
import jakarta.persistence.*;
import java.time.Instant;
import java.util.UUID;
@Entity
@Table(name = "carts")
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
private UUID customerId;
@Column(length = 200)
private String guestSessionRef;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 30)
private CartStatus status = CartStatus.ACTIVE;
@Column(nullable = false, length = 3)
private String currency;
@Version
private long version;
@Column(nullable = false, updatable = false)
private Instant createdAt;
@Column(nullable = false)
private Instant updatedAt;
protected Cart() {
}
public Cart(String currency) {
this.currency = currency;
this.status = CartStatus.ACTIVE;
}
@PrePersist
void onCreate() {
Instant now = Instant.now();
this.createdAt = now;
this.updatedAt = now;
}
@PreUpdate
void onUpdate() {
this.updatedAt = Instant.now();
}
public UUID getId() {
return id;
}
public CartStatus getStatus() {
return status;
}
public String getCurrency() {
return currency;
}
public long getVersion() {
return version;
}
public void markCheckoutPending() {
if (status != CartStatus.ACTIVE) {
throw new IllegalStateException(
"Only active carts can enter checkout");
}
status = CartStatus.CHECKOUT_PENDING;
}
public void markConverted() {
if (status != CartStatus.CHECKOUT_PENDING) {
throw new IllegalStateException(
"Cart must be in checkout before conversion");
}
status = CartStatus.CONVERTED;
}
}
The entity uses optimistic locking through @Version. This can help detect conflicting updates, but the service must still handle optimistic-lock failures and define retry behavior.
12.3 Define the cart item entity
import jakarta.persistence.*;
import java.time.Instant;
import java.util.UUID;
@Entity
@Table(name = "cart_items")
public class CartItem {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@Column(nullable = false)
private UUID cartId;
@Column(nullable = false)
private UUID variantId;
@Column(nullable = false)
private int quantity;
@Column(nullable = false, updatable = false)
private Instant createdAt;
@Column(nullable = false)
private Instant updatedAt;
protected CartItem() {
}
public CartItem(
UUID cartId,
UUID variantId,
int quantity) {
validateQuantity(quantity);
this.cartId = cartId;
this.variantId = variantId;
this.quantity = quantity;
}
public void changeQuantity(int quantity) {
validateQuantity(quantity);
this.quantity = quantity;
}
private void validateQuantity(int quantity) {
if (quantity <= 0) {
throw new IllegalArgumentException(
"Quantity must be greater than zero");
}
}
@PrePersist
void onCreate() {
Instant now = Instant.now();
this.createdAt = now;
this.updatedAt = now;
}
@PreUpdate
void onUpdate() {
this.updatedAt = Instant.now();
}
public UUID getId() {
return id;
}
public UUID getCartId() {
return cartId;
}
public UUID getVariantId() {
return variantId;
}
public int getQuantity() {
return quantity;
}
}
This simplified entity uses a scalar cart ID rather than a JPA relationship. A production implementation may choose @ManyToOne relationships, aggregate-oriented persistence, or a different storage model based on the application design.
A full implementation should also enforce that a cart item belongs to a cart owned by the requesting customer or guest session.
12.4 Define repositories
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface CartRepository
extends JpaRepository<Cart, UUID> {
}
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.UUID;
public interface CartItemRepository
extends JpaRepository<CartItem, UUID> {
List<CartItem> findByCartId(UUID cartId);
}
The repository layer provides persistence operations. More advanced queries may need locking, explicit update statements, or aggregate loading to preserve concurrency and consistency requirements.
12.5 Define the add-item request
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.UUID;
public record AddCartItemRequest(
@NotNull UUID variantId,
@Min(1)
@Max(100) int quantity
) {
}
The maximum quantity is illustrative. A real limit should come from business rules and may depend on the product, seller, customer, or market.
12.6 Define the cart service
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
@Service
public class ShoppingCartService {
private final CartRepository cartRepository;
private final CartItemRepository cartItemRepository;
public ShoppingCartService(
CartRepository cartRepository,
CartItemRepository cartItemRepository) {
this.cartRepository = cartRepository;
this.cartItemRepository = cartItemRepository;
}
@Transactional
public Cart createCart(String currency) {
if (currency == null || currency.isBlank()) {
throw new IllegalArgumentException(
"Currency is required");
}
return cartRepository.save(
new Cart(currency.trim().toUpperCase())
);
}
@Transactional
public CartItem addItem(
UUID cartId,
AddCartItemRequest request) {
Cart cart = cartRepository.findById(cartId)
.orElseThrow(() ->
new IllegalArgumentException("Cart not found"));
if (cart.getStatus() != CartStatus.ACTIVE) {
throw new IllegalStateException(
"Cart is not active");
}
// A production implementation should validate the variant
// with the catalog and enforce cart ownership here.
CartItem item = new CartItem(
cartId,
request.variantId(),
request.quantity()
);
return cartItemRepository.save(item);
}
@Transactional
public CartItem updateQuantity(
UUID cartId,
UUID itemId,
int quantity) {
Cart cart = cartRepository.findById(cartId)
.orElseThrow(() ->
new IllegalArgumentException("Cart not found"));
if (cart.getStatus() != CartStatus.ACTIVE) {
throw new IllegalStateException(
"Cart is not active");
}
CartItem item = cartItemRepository.findById(itemId)
.orElseThrow(() ->
new IllegalArgumentException("Item not found"));
if (!cartId.equals(item.getCartId())) {
throw new IllegalArgumentException(
"Item does not belong to the specified cart");
}
item.changeQuantity(quantity);
return cartItemRepository.save(item);
}
}
This example demonstrates the basic domain flow, but it is not concurrency-complete. It also uses general exceptions for brevity; production code should use domain-specific exceptions and consistent HTTP error mapping.
For a production service, consider:
- Validating cart ownership through the authenticated principal or guest token
- Validating the variant through the catalog service
- Defining whether duplicate variant additions create separate lines or merge quantities
- Handling optimistic-lock failures
- Applying maximum purchase limits
- Adding idempotency where necessary
- Returning response DTOs instead of JPA entities
- Publishing events through a transactional outbox
12.7 Define the REST controller
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@RestController
@RequestMapping("/api/store/v1/carts")
public class ShoppingCartController {
private final ShoppingCartService cartService;
public ShoppingCartController(
ShoppingCartService cartService) {
this.cartService = cartService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Cart createCart(
@RequestParam(defaultValue = "USD")
String currency) {
return cartService.createCart(currency);
}
@PostMapping("/{cartId}/items")
@ResponseStatus(HttpStatus.CREATED)
public CartItem addItem(
@PathVariable UUID cartId,
@Valid @RequestBody AddCartItemRequest request) {
return cartService.addItem(cartId, request);
}
@PatchMapping("/{cartId}/items/{itemId}")
public CartItem updateQuantity(
@PathVariable UUID cartId,
@PathVariable UUID itemId,
@RequestParam int quantity) {
return cartService.updateQuantity(
cartId, itemId, quantity);
}
}
For learning purposes, this controller shows the endpoint structure. A production API should use validated DTOs for all input, response DTOs for output, appropriate status codes, and authentication and authorization on every cart operation.
The example does not implement pricing, promotions, inventory reservations, or checkout. Those capabilities should be introduced through well-defined interfaces rather than being hidden inside the controller.
13. Concurrency and Consistency
Shopping carts are vulnerable to concurrent updates.
A customer may open the same cart on a phone and laptop, or two requests may update the same item at nearly the same time.
13.1 Lost update problem
Suppose the cart contains quantity two.
Two requests read the same state:
- Request A changes quantity to three.
- Request B changes quantity to four.
If both requests read version one and then overwrite the row without concurrency protection, one update may silently replace the other.
The final quantity could be three or four depending on execution order.
13.2 Optimistic locking
Optimistic locking uses a version number to detect conflicting updates.
Conceptually:
UPDATE carts
SET version = version + 1
WHERE id = :cartId
AND version = :expectedVersion;
If no row is updated, the version has changed and the operation must be reconsidered.
With JPA, @Version can provide optimistic locking for entity updates. The application still needs to handle the resulting exception and decide whether to retry, return a conflict response, or reload and merge the changes.
13.3 Compare-and-set with API versions
An API can expose a cart version or ETag.
Example:
PATCH /api/store/v1/carts/cart-100
If-Match: "7"
If the cart version no longer matches, the server can return 412 Precondition Failed or another documented conflict response.
This makes concurrent modification behavior explicit to clients.
13.4 When to use pessimistic locking
Pessimistic locking can be useful for operations that must serialize updates to a particular cart or checkout attempt.
However, holding database locks while calling remote pricing, promotion, inventory, or payment services is risky. Remote calls can be slow and may cause lock contention.
Keep database transactions short. Prefer explicit workflow state, optimistic locking, and idempotency for many distributed operations.
14. Checkout as a Distributed Workflow
Checkout is not simply a button that changes the cart status to CONVERTED.
It coordinates multiple services that may fail independently.
A typical workflow may include:
- Verify cart ownership and status.
- Read a stable cart version.
- Validate product and variant eligibility.
- Recalculate prices and promotions.
- Calculate taxes and shipping.
- Reserve inventory.
- Authorize payment.
- Create or confirm the order.
- Finalize the cart conversion.
- Confirm the result to the customer.
The order and payment flow can vary by platform. Some systems create a pending order before payment authorization; others create the accepted order only after certain checks pass.
14.1 The partial failure problem
Imagine the inventory service successfully reserves stock, but the payment service times out.
The system cannot assume that the entire checkout transaction has failed or that the payment authorization did not happen. The payment request may have succeeded even if its response was lost.
The workflow needs to query or retry safely using an idempotency key, then either continue or compensate.
14.2 Saga pattern
A saga coordinates a multi-step business transaction using local transactions and compensating actions.
Example:
flowchart TD
A[Start Checkout] --> B[Validate Cart]
B --> C[Recalculate Price]
C --> D[Reserve Inventory]
D --> E[Authorize Payment]
E --> F[Create Order]
F --> G[Confirm Checkout]
E -->|Failure| H[Release Inventory]
F -->|Recoverable Failure| I[Resolve Order State]
I --> J[Retry or Compensate]
H --> K[Return Recoverable Result]
Compensation does not mean the distributed system can erase history. It means the business performs an action that counteracts an earlier action, such as releasing a reservation or voiding an authorization.
14.3 Idempotent checkout
The client may submit checkout more than once due to a timeout, browser refresh, or repeated tap.
Use an idempotency key that is scoped appropriately to the customer and checkout operation.
The system should persist the relationship between the key and the checkout result. Repeating the same request should return or resume the existing attempt rather than create another order.
14.4 Cart snapshot
Checkout should work against a stable cart version or snapshot.
If the cart changes while checkout is running, the platform must define whether:
- The change is rejected while checkout is pending.
- Checkout continues using the captured snapshot.
- The checkout attempt is invalidated and must restart.
The important requirement is that the order reflects the exact cart and commercial terms accepted by the customer.
15. Shopping Cart Events and Analytics
Cart events can support operational workflows, analytics, personalization, and cart recovery.
Common events include:
CartCreated
CartItemAdded
CartItemQuantityChanged
CartItemRemoved
CartPromotionApplied
CartPromotionRemoved
CartMerged
CheckoutStarted
CheckoutFailed
CartConverted
CartExpired
15.1 Example event
{
"eventId": "evt-1001",
"eventType": "CartItemAdded",
"eventVersion": 1,
"occurredAt": "2026-06-24T14:25:00Z",
"cartId": "cart-100",
"itemId": "item-200",
"variantId": "variant-300",
"quantity": 2
}
This event is illustrative. A real event contract should define required fields, schema versioning, privacy requirements, and the intended consumers.
15.2 Analytics use cases
Cart events can help measure:
- Product add-to-cart rate
- Cart modification frequency
- Checkout initiation rate
- Checkout completion rate
- Cart abandonment rate
- Promotion usage
- Product combinations
- Funnel drop-off
Use a consistent definition for each metric. For example, abandoned-cart calculations need a defined inactivity window and a rule for excluding converted carts.
15.3 Cart recovery
Some platforms use cart events to support reminders or recovery campaigns.
Such workflows should follow customer consent, privacy rules, communication preferences, and applicable marketing requirements. Do not assume that every anonymous cart can be associated with an identifiable customer.
15.4 Transactional outbox
If cart updates must reliably produce events, the service can use the transactional outbox pattern.
The cart mutation and outbox record are committed in one database transaction. A background publisher then sends events to the broker.
Consumers should be idempotent because messages may be delivered more than once.
For high-volume cart operations, event selection and payload size should be deliberate. Do not publish every internal implementation detail if downstream systems do not need it.
16. Security and Privacy
Shopping carts may contain information about a customer's purchasing interests and can become sensitive when combined with identity, address, or account information.
16.1 Cart ownership
Every operation must verify that the caller is authorized to access the requested cart.
Do not assume that a UUID is secret enough to provide authorization.
For authenticated customers, verify ownership or an explicit permission. For guest carts, validate the server-issued session or cart token.
16.2 API validation
Validate:
- Quantity boundaries
- Product and variant identifiers
- Cart status
- Currency and market constraints
- Promotion codes
- Request size
- Idempotency keys
- Expected cart versions
Apply rate limits to protect against abusive requests and accidental request storms.
16.3 Sensitive information
Avoid storing payment card numbers, security codes, or other payment credentials in the cart database.
Payment information should be handled through a compliant payment provider and the platform's approved payment architecture.
Avoid putting customer details, guest tokens, or sensitive purchase data into logs, metrics labels, and public URLs.
16.4 Retention and deletion
Define retention policies for:
- Anonymous carts
- Authenticated carts
- Expired carts
- Converted carts
- Cart analytics
- Audit records
Retention should balance customer experience, business needs, legal obligations, and privacy requirements.
17. Performance and Scalability
Cart workloads are often read- and write-intensive. The service should be designed for short requests, efficient persistence, and controlled dependencies.
17.1 Optimize the critical path
Common optimizations include:
- Keep basic add, update, and remove operations lightweight.
- Avoid calling every downstream service synchronously for every mutation.
- Cache appropriate product display information.
- Batch pricing and availability lookups when possible.
- Use connection pooling.
- Add database indexes based on measured query patterns.
- Apply timeouts to remote calls.
- Use bounded retries with backoff.
- Separate analytics processing from synchronous customer requests.
For example, adding a product to the cart may only require validating the variant and saving the mutation. Full tax, shipping, and promotion calculations may be deferred until the customer opens the cart or starts checkout, depending on business requirements.
17.2 Avoid excessive synchronous dependencies
Suppose viewing a cart requires sequential calls to catalog, pricing, promotion, inventory, shipping, and recommendation services.
If each service adds latency, the overall response can become slow and fragile.
Consider:
- Parallel calls for independent lookups
- Timeouts and graceful degradation
- Cached display snapshots
- A dedicated cart-summary composition layer
- Refreshing expensive estimates only when needed
Do not degrade silently when a critical calculation is unavailable. The system must distinguish between an optional display enrichment and a required checkout validation.
17.3 Database indexing
Potential indexes include:
CREATE INDEX idx_cart_items_cart_id
ON cart_items(cart_id);
CREATE INDEX idx_carts_customer_status
ON carts(customer_id, status);
CREATE INDEX idx_carts_expires_at
ON carts(expires_at);
These are examples, not a universal recommendation. Validate query plans and index selectivity using actual workloads.
If multiple active carts are allowed, define that behavior in the data model. If only one active cart per customer and scope is allowed, consider an appropriate database constraint or another concurrency-safe mechanism.
17.4 Expiration jobs
Inactive carts may be expired by a scheduled job or a lifecycle process.
For large datasets:
- Process carts in bounded batches.
- Use indexed expiration fields.
- Avoid long-running transactions.
- Make the operation idempotent.
- Record processing failures.
- Preserve carts that are currently in a protected checkout state.
Do not delete active carts merely because a timestamp has passed if the business allows recovery or the cart is associated with an in-progress checkout.
18. Reliability and Failure Handling
A production cart service must handle failures in the database, caches, message broker, and downstream commerce services.
18.1 Dependency timeout
If the pricing service is unavailable, the cart may still be retrievable using a last-known display estimate, provided the response clearly indicates that the price needs refresh.
Checkout should not proceed on an unverified price if current validation is required by business policy.
18.2 Database failure
The cart service should return a clear failure rather than pretending a mutation succeeded when persistence is uncertain.
For operations that may have committed before a network timeout, clients should retry using a documented idempotency or versioning strategy.
18.3 Message broker failure
If the database update succeeds but the broker is unavailable, the transactional outbox allows the event to remain pending for later publication.
Monitor outbox age, retry counts, and event-processing lag.
18.4 Cache inconsistency
A stale cache can display an outdated quantity or cart state.
Use versioning, explicit invalidation, or cache-aside patterns with defined consistency expectations. Never assume cache contents are always current.
18.5 Graceful degradation
Not all features have the same criticality.
| Dependency or feature | Possible degradation strategy |
|---|---|
| Product display metadata | Use a valid cached snapshot |
| Recommendation service | Omit recommendations |
| Analytics pipeline | Queue events for later processing |
| Price estimate | Mark estimate stale and refresh when possible |
| Promotion estimate | Explain that eligibility must be revalidated |
| Inventory availability | Display unknown status if safe and clearly explained |
| Checkout inventory reservation | Do not confirm purchase without required reservation |
| Payment authorization | Do not treat an uncertain result as a confirmed payment |
Graceful degradation must preserve business correctness. A cart can often remain viewable during a pricing outage, but a purchase should not be confirmed without the required validations.
19. Observability and Business Metrics
A shopping cart service needs both technical monitoring and business-level measurement.
19.1 Technical metrics
Track:
- Request rate
- Latency percentiles
- Error rate
- Database query latency
- Database connection utilization
- Cache hit ratio
- Optimistic-lock conflict rate
- Downstream service timeouts
- Event publication lag
- Expired-cart processing failures
19.2 Business metrics
Track:
- Active cart count
- Items per cart
- Add-to-cart success rate
- Quantity update success rate
- Checkout initiation rate
- Checkout completion rate
- Cart conversion rate
- Cart abandonment rate
- Promotion application success rate
- Cart merge success rate
19.3 Distributed tracing
Trace important workflows across:
- Storefront request
- API gateway or BFF
- Cart service
- Database
- Pricing and inventory lookups
- Checkout service
- Payment provider
- Order management
- Event broker
Use correlation IDs and structured logs to troubleshoot slow requests and duplicate submissions.
Do not use raw customer IDs, cart tokens, or other high-cardinality sensitive values as unrestricted metric labels.
20. Common Shopping Cart Architecture Mistakes
Mistake 1: Treating the cart as an order
A cart can change and may never be purchased.
Better approach: Keep cart and order lifecycles separate, and create a stable order snapshot at the appropriate point in checkout.
Mistake 2: Trusting browser-submitted prices
Client-side values can be stale or manipulated.
Better approach: Obtain prices from the pricing authority and validate them during checkout.
Mistake 3: Reserving inventory indefinitely
This can block stock for inactive carts.
Better approach: Define when inventory is reserved, how long reservations last, and how they are released.
Mistake 4: Ignoring guest-cart ownership
An exposed cart identifier should not allow arbitrary access.
Better approach: Use secure guest-session tokens and enforce authorization on every request.
Mistake 5: Losing concurrent updates
Multiple tabs or devices can update the same cart simultaneously.
Better approach: Use optimistic locking, version checks, and clearly defined update semantics.
Mistake 6: Making every cart operation call every downstream service
This creates unnecessary latency and dependency failures.
Better approach: Keep mutations lightweight, cache appropriate display information, and defer nonessential calculations.
Mistake 7: Ignoring duplicate requests
A timeout can lead to retries and unexpected quantity increases.
Better approach: Define idempotent behavior for operations and use idempotency keys for critical workflows.
Mistake 8: Treating cart totals as final
Taxes, shipping, prices, promotions, and inventory can change.
Better approach: Present estimates honestly and validate the final terms during checkout.
Mistake 9: Creating too many microservices too early
Splitting every cart capability into separate services can increase complexity without providing meaningful benefits.
Better approach: Start with clear modules and introduce service boundaries when scaling, ownership, or deployment requirements justify them.
Mistake 10: Forgetting operational recovery
A service may work in normal conditions but fail when events, caches, or downstream systems are unavailable.
Better approach: Define retries, idempotency, timeouts, recovery procedures, and monitoring before production deployment.
21. Hands-On Project: Build a Shopping Cart Service
Build a shopping cart service for an online store using Java and Spring Boot.
Functional requirements
- Create a guest cart.
- Create or retrieve a customer cart.
- Add a product variant.
- Update an item quantity.
- Remove an item.
- Retrieve cart details.
- Merge a guest cart after login.
- Display estimated pricing.
- Apply and remove promotion codes.
- Validate cart contents before checkout.
- Track checkout attempts.
- Prevent duplicate checkout submissions.
- Publish cart events.
- Expire inactive carts.
Suggested technology stack
| Layer | Technology |
|---|---|
| Language | Java |
| Framework | Spring Boot |
| REST APIs | Spring MVC |
| Persistence | Spring Data JPA |
| Database | PostgreSQL |
| Cache | Redis, if justified |
| Messaging | Kafka or another supported broker |
| Security | Spring Security and OAuth 2.0/OIDC |
| Testing | JUnit, Mockito, Testcontainers |
| Observability | Micrometer and OpenTelemetry |
| Containerization | Docker |
| Deployment | Kubernetes or a managed application platform |
Start with PostgreSQL and Spring Boot. Introduce caching and messaging after the core cart behavior is correct.
Phase 1: Basic cart APIs
Implement:
- Cart creation
- Cart retrieval
- Add item
- Update quantity
- Remove item
- Input validation
- Database persistence
- Global exception handling
Deliverable: A working cart API with unit and integration tests.
Phase 2: Guest and customer identity
Implement:
- Guest cart token
- Authenticated customer association
- Cart ownership validation
- Cart merge
- Duplicate merge protection
- Cart expiration
Deliverable: Guest and authenticated users can manage carts securely.
Phase 3: Pricing and promotions
Implement:
- Pricing service interface
- Price estimate response
- Promotion code management
- Discount eligibility response
- Stale price handling
- Checkout-time repricing
Deliverable: The cart can display estimates without treating them as guaranteed final totals.
Phase 4: Concurrency and idempotency
Implement:
- Optimistic locking
- Cart version checks
- Duplicate request handling
- Checkout idempotency keys
- Conflict responses
- Retry behavior
Deliverable: Concurrent changes and repeated requests have predictable results.
Phase 5: Checkout integration
Implement:
- Cart validation
- Stable cart snapshot
- Inventory reservation interface
- Payment authorization interface
- Order creation interface
- Recoverable checkout state
- Compensation and retry handling
Deliverable: Checkout can recover safely from partial failures.
Phase 6: Events and observability
Implement:
- Cart lifecycle events
- Transactional outbox
- Idempotent consumers
- Structured logging
- Metrics and tracing
- Event lag monitoring
Deliverable: Cart changes can be observed and consumed reliably.
Phase 7: Production readiness
Add:
- Rate limiting
- Security testing
- Load testing
- Database migration strategy
- Backup and recovery procedures
- Expiration job
- API documentation
- Operational runbook
Deliverable: A documented cart service ready for deployment in a controlled environment.
22. What to Practice
Use this checklist to evaluate your understanding and implementation.
- Explain the difference between a cart, checkout, and order.
- Design a cart and cart-item data model.
- Define guest and authenticated cart behavior.
- Design a secure guest-cart token strategy.
- Implement add, update, remove, and retrieve operations.
- Explain the difference between setting and incrementing quantity.
- Define how duplicate product variants are handled within a cart.
- Explain why the browser must not be trusted as the source of price.
- Design cart totals with currency-specific monetary precision.
- Define how promotions are validated and applied.
- Explain why cart availability checks do not guarantee inventory.
- Implement optimistic locking and conflict handling.
- Design idempotent checkout submission.
- Explain how a saga can coordinate inventory, payment, and order creation.
- Design a reliable event publication mechanism.
- Define cart expiration and recovery policies.
- Identify the difference between technical metrics and business metrics.
- Test the service under concurrent requests and downstream failures.
23. Solution Architect Interview Questions
Fundamental questions
1. What is the responsibility of a shopping cart service?
It manages purchase intent, including selected product variants, quantities, cart ownership, persistence, and cart lifecycle. It can provide price estimates and prepare the cart for checkout, but it does not replace order management.
2. Why should a cart be separate from an order?
A cart is mutable and may never be purchased. An order records an accepted transaction and must preserve the relevant purchase-time details, including items, prices, discounts, and other commercial terms.
3. Should adding a product to a cart reserve inventory?
Usually not by default, because inactive carts could block available stock. Reservation timing is a business decision. If stock is reserved, the system needs expiration, release, and recovery rules.
Data and API questions
4. How do you handle duplicate add-item requests?
First define the API semantics. Setting a quantity is naturally repeatable, while incrementing a quantity is not. Use appropriate idempotency controls, request identifiers, or version checks to avoid unintended duplicate effects.
5. How do you merge guest and customer carts?
Authenticate the customer, verify guest-cart ownership, apply a defined merge policy, validate product references and quantity limits, and persist the merge safely. The operation must be protected against repeated execution.
6. How do you prevent users from accessing other customers' carts?
Enforce authorization on every request. Verify cart ownership against the authenticated principal or validate a secure guest token. Do not rely on an unguessable cart ID alone.
Architecture questions
7. Why should pricing be a separate capability?
Pricing may depend on promotions, customer segments, currency, geography, and time. A dedicated pricing capability can own these rules and provide consistent results to the cart, checkout, and other channels.
8. How do you handle concurrent updates to a cart?
Use optimistic locking or version checks, define conflict responses, and implement retries where safe. Avoid long database transactions that remain open while waiting for remote services.
9. How would you prevent duplicate orders when checkout is submitted twice?
Persist an idempotency key and its checkout result. A repeated submission should return or resume the existing checkout attempt instead of creating another order.
10. What happens if inventory reservation succeeds but payment authorization fails?
The checkout workflow should follow a defined compensation or recovery strategy, such as releasing the reservation. It must also handle uncertain payment outcomes safely rather than assuming a timeout means authorization failed.
Scalability and reliability questions
11. How would you support millions of active carts?
Use an appropriate durable storage model, efficient indexes, short transactions, connection pooling, measured caching, bounded expiration jobs, and horizontal scaling where the service architecture supports it.
12. How would you design cart recovery?
Define inactivity and retention policies, preserve eligible cart state, associate carts with customers only through authorized mechanisms, and follow consent and privacy requirements for recovery communications.
13. How would you handle pricing-service outages?
The cart may show a clearly marked last-known estimate if that is safe. Checkout must enforce required price validation and should not confirm a purchase using an unverified amount.
14. How would you measure shopping cart performance?
Measure request latency, error rates, database performance, conflict rates, downstream dependency latency, and cache behavior. Also measure add-to-cart success, checkout initiation, conversion, and abandonment.
24. Key Takeaways
- A shopping cart represents customer purchase intent, while checkout validates a purchase and order management records and manages the accepted order.
- The cart service owns item selection, quantities, cart state, ownership, and cart lifecycle.
- Guest carts require secure session handling and explicit merge policies.
- Price estimates, promotions, taxes, and shipping should be clearly distinguished from final checkout amounts.
- Adding an item to a cart does not automatically reserve inventory.
- Stable cart versions, optimistic locking, and idempotency help control concurrent updates and retries.
- Checkout is a distributed workflow that must account for partial failures and uncertain external outcomes.
- The transactional outbox and idempotent consumers help make event-driven integration reliable.
- Security, retention, monitoring, and operational recovery are essential production requirements.
- Start with clear domain boundaries and introduce additional infrastructure only when requirements justify it.
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.