E-Commerce System Design

A system design case study for an e-commerce platform covering catalog, search, cart, inventory, checkout, payments, and fulfillment.

Designing a Modern Amazon/Flipkart-Style Platform

E-Commerce is one of the most demanding software domains because it combines millions of users, products, payments, inventory updates, logistics, recommendations, and real-time order processing into a single platform.

Unlike traditional web applications, an e-commerce platform must handle massive traffic spikes during flash sales, Black Friday events, and holiday shopping seasons while ensuring inventory accuracy, payment reliability, and excellent customer experience.

In this case study, we'll design a cloud-native enterprise E-Commerce platform capable of supporting millions of customers and sellers using modern system design principles.


Learning Objectives

After completing this series, you'll understand:

  • E-Commerce domain fundamentals
  • Product Catalog architecture
  • Shopping Cart design
  • Inventory Management
  • Order Management
  • Payment Processing
  • Shipping & Logistics
  • Search architecture
  • Recommendation systems
  • Event-driven architecture
  • Production deployment
  • Enterprise scalability

What is an E-Commerce Platform?

An E-Commerce platform enables customers to browse products, compare prices, purchase items, make payments, track shipments, and manage returns online.

Large platforms include:

  • Amazon
  • Flipkart
  • Walmart
  • eBay
  • Shopify
  • Target

Types of E-Commerce

Type Description
B2C Business to Customer
B2B Business to Business
C2C Customer to Customer
D2C Direct to Customer
Marketplace Multiple sellers on one platform

This case study focuses on a Marketplace architecture similar to Amazon or Flipkart.


Business Requirements

The platform should support:

  • Customer registration
  • Seller onboarding
  • Product catalog
  • Product search
  • Categories
  • Shopping cart
  • Wishlist
  • Checkout
  • Payments
  • Coupons
  • Inventory
  • Orders
  • Shipping
  • Notifications
  • Reviews & Ratings
  • Returns
  • Refunds
  • Reporting
  • Analytics

Functional Requirements

Customer Management

Customers should be able to:

  • Register
  • Login
  • Update profile
  • Save addresses
  • Manage payment methods
  • View order history

Seller Management

Sellers should be able to:

  • Register
  • List products
  • Manage inventory
  • Update pricing
  • View orders
  • Process shipments

Product Catalog

Support:

  • Categories
  • Brands
  • Product images
  • Product descriptions
  • Product specifications
  • Variants (Color, Size)
  • Product availability

Customers should search by:

  • Product name
  • Brand
  • Category
  • Price
  • Rating
  • Seller
  • Keywords

Shopping Cart

Customers should:

  • Add products
  • Remove products
  • Update quantity
  • Save for later
  • View estimated totals

Wishlist

Support:

  • Add item
  • Remove item
  • Move to cart
  • Share wishlist

Checkout

Support:

  • Address selection
  • Shipping options
  • Coupon application
  • Payment selection
  • Order confirmation

Payment

Support:

  • Credit Card
  • Debit Card
  • UPI
  • Digital Wallet
  • Net Banking
  • Gift Cards

Shipping

Support:

  • Warehouse allocation
  • Shipment tracking
  • Delivery updates
  • Delivery confirmation

Returns & Refunds

Support:

  • Return request
  • Pickup scheduling
  • Refund approval
  • Replacement orders

Notification Service

Notify customers for:

  • Order placed
  • Payment received
  • Order shipped
  • Out for delivery
  • Delivered
  • Return approved
  • Refund completed

Channels:

  • Email
  • SMS
  • Push Notifications

Non-Functional Requirements

Requirement Target
Availability 99.99%
Scalability Hundreds of millions of users
Response Time Less than 300 ms
Reliability No order loss
Security Encryption + MFA
Performance Fast product search
Disaster Recovery Multi-region
Auditability Complete order history

Capacity Estimation

Assume a global marketplace.

Customers

300 Million

Sellers

5 Million

Products

500 Million

Daily Orders

30 Million

Daily Searches

2 Billion

Daily API Requests

15 Billion

Storage Estimation

Entity Estimated Size
Customer 10 KB
Product 8 KB
Product Image Metadata 5 KB
Order 6 KB
Cart 4 KB
Payment 3 KB
Review 2 KB

Large product images and videos should be stored in object storage instead of relational databases.


Core E-Commerce Concepts

Understanding the business domain is essential before designing the architecture.


Customer

A registered user who browses products and places orders.

A customer may have:

  • Multiple addresses
  • Multiple carts
  • Multiple orders
  • Multiple payment methods
  • Multiple wishlists

Seller

A business or individual that sells products on the marketplace.

A seller manages:

  • Product listings
  • Inventory
  • Pricing
  • Shipments

Product

A product represents an item available for purchase.

Example:

Apple iPhone 17 Pro

Contains:

  • Images
  • Price
  • Brand
  • Description
  • Specifications
  • Reviews
  • Inventory

SKU

SKU (Stock Keeping Unit) uniquely identifies a sellable product variant.

Example:

iPhone 17 Pro

↓

128 GB

↓

Black

↓

SKU-100001

Each variant has its own inventory.


Category

Products belong to hierarchical categories.

Example:

Electronics

↓

Mobiles

↓

Smartphones

Inventory

Tracks product availability.

Example:

Warehouse A

250 Units

Warehouse B

80 Units

Inventory changes after:

  • Purchase
  • Return
  • Cancellation
  • Warehouse transfer

Shopping Cart

A temporary collection of products before checkout.

Supports:

  • Quantity updates
  • Coupon estimation
  • Shipping estimates

Wishlist

Allows customers to save products for future purchases.


Order

An order is created after successful checkout.

Contains:

  • Customer
  • Items
  • Shipping Address
  • Payment
  • Shipment
  • Taxes
  • Discounts

Payment

Represents financial authorization.

Typical states:

  • Pending
  • Authorized
  • Completed
  • Failed
  • Refunded

Shipment

Represents logistics information.

Typical states:

  • Packed
  • Shipped
  • In Transit
  • Out for Delivery
  • Delivered

High-Level Architecture

The E-Commerce platform is built using independently deployable microservices.

flowchart LR

Customer

Customer --> Mobile

Customer --> Web

Mobile --> Gateway

Web --> Gateway

Gateway --> Auth

Gateway --> CustomerService

Gateway --> ProductService

Gateway --> CartService

Gateway --> OrderService

Gateway --> PaymentService

Gateway --> InventoryService

Gateway --> ShippingService

Why Microservices?

Different business capabilities have different traffic patterns.

Examples:

  • Search receives the highest traffic.
  • Cart updates happen continuously.
  • Checkout peaks during sales.
  • Payments require high reliability.
  • Inventory changes after every order.

Independent services allow teams to scale and deploy each capability separately.


Core Microservices

Service Responsibility
API Gateway Entry point
Authentication Login & Security
Customer Service Customer profiles
Seller Service Seller management
Product Service Product catalog
Search Service Product search
Cart Service Shopping cart
Wishlist Service Wishlist
Order Service Order lifecycle
Inventory Service Stock management
Payment Service Payment processing
Shipping Service Logistics
Review Service Ratings & Reviews
Notification Service Email, SMS, Push
Reporting Service Analytics

High-Level Service Architecture

flowchart TD

Gateway

Gateway --> Auth

Gateway --> Customer

Gateway --> Seller

Gateway --> Product

Gateway --> Search

Gateway --> Cart

Gateway --> Wishlist

Gateway --> Order

Gateway --> Inventory

Gateway --> Payment

Gateway --> Shipping

Gateway --> Notification

Customer Shopping Journey

A typical customer journey:

  1. Register or login.
  2. Search products.
  3. Browse product details.
  4. Add products to cart.
  5. Apply coupons.
  6. Checkout.
  7. Complete payment.
  8. Receive order confirmation.
  9. Track shipment.
  10. Receive delivery.
  11. Leave product review.

Order Lifecycle

flowchart LR

Created

Created --> Payment

Payment --> Confirmed

Confirmed --> Packed

Packed --> Shipped

Shipped --> Delivered

Created --> Cancelled

Return Lifecycle

flowchart LR

ReturnRequested

ReturnRequested --> Pickup

Pickup --> Inspection

Inspection --> Refund

Inspection --> Replacement

Service Responsibilities

Customer Service

Responsible for:

  • Customer profiles
  • Addresses
  • Payment methods
  • Preferences

Product Service

Responsible for:

  • Product catalog
  • Product specifications
  • Images
  • Variants
  • Brands

Search Service

Responsible for:

  • Keyword search
  • Filters
  • Sorting
  • Suggestions
  • Autocomplete

Cart Service

Responsible for:

  • Shopping cart
  • Quantity updates
  • Cart totals
  • Saved items

Order Service

Responsible for:

  • Order creation
  • Order tracking
  • Order history
  • Order cancellation

Inventory Service

Responsible for:

  • Warehouse stock
  • Stock reservation
  • Stock deduction
  • Stock replenishment

Payment Service

Responsible for:

  • Payment authorization
  • Refunds
  • Payment status
  • Transaction history

Shipping Service

Responsible for:

  • Warehouse allocation
  • Shipment creation
  • Tracking
  • Delivery updates

Notification Service

Responsible for:

  • Order confirmation
  • Shipping notifications
  • Delivery alerts
  • Promotional notifications

Design Considerations

When designing an enterprise e-commerce platform, prioritize:

  • Fast product search
  • Inventory consistency
  • Reliable payments
  • High availability
  • Horizontal scalability
  • Secure checkout
  • Event-driven communication
  • Multi-region deployment
  • Excellent customer experience
  • Fault tolerance

we'll design the implementation details, including:

  • Low-Level Architecture (LLD)
  • Database Design
  • Entity Relationship (ER) Diagram
  • Product Catalog
  • Inventory Management
  • Shopping Cart
  • Wishlist
  • Pricing
  • Promotion & Coupons
  • Order Management
  • Payment Management
  • Shipping Management
  • Reviews & Ratings
  • Search Architecture
  • REST API Design
  • Event-Driven Architecture
  • Kafka Topics

Low-Level Architecture

Each business capability is implemented as an independent microservice.

flowchart LR

Client

Client --> Gateway

Gateway --> Auth

Gateway --> Customer

Gateway --> Seller

Gateway --> Product

Gateway --> Search

Gateway --> Cart

Gateway --> Wishlist

Gateway --> Order

Gateway --> Inventory

Gateway --> Pricing

Gateway --> Promotion

Gateway --> Payment

Gateway --> Shipping

Gateway --> Review

Gateway --> Notification

Why Database per Service?

Each microservice owns its own database.

Benefits:

  • Loose coupling
  • Independent deployments
  • Independent scaling
  • Better fault isolation
  • Technology flexibility

Database Architecture

flowchart TD

CustomerService --> CustomerDB

SellerService --> SellerDB

ProductService --> ProductDB

InventoryService --> InventoryDB

CartService --> CartDB

OrderService --> OrderDB

PaymentService --> PaymentDB

ShippingService --> ShippingDB

ReviewService --> ReviewDB

Customer Database

Customer Table

Column Type
customer_id UUID
first_name VARCHAR
last_name VARCHAR
email VARCHAR
phone VARCHAR
status VARCHAR
created_at TIMESTAMP

Address Table

Column Type
address_id UUID
customer_id UUID
address_line1 VARCHAR
city VARCHAR
state VARCHAR
postal_code VARCHAR
country VARCHAR

Seller Database

Seller Table

Column Type
seller_id UUID
seller_name VARCHAR
email VARCHAR
phone VARCHAR
rating DECIMAL
status VARCHAR

Product Catalog Database

Product Table

Column Type
product_id UUID
seller_id UUID
product_name VARCHAR
brand VARCHAR
category_id UUID
description TEXT
status VARCHAR
created_at TIMESTAMP

Product Variant Table

Each product can have multiple variants.

Example:

  • iPhone 17
  • 128 GB
  • Black
Column Type
variant_id UUID
product_id UUID
sku VARCHAR
color VARCHAR
size VARCHAR
storage VARCHAR
price DECIMAL

Category Table

Column Type
category_id UUID
parent_category UUID
category_name VARCHAR

Product Image Table

Column Type
image_id UUID
product_id UUID
image_url VARCHAR
display_order INTEGER

Large images should be stored in object storage.


Inventory Database

Inventory Table

Column Type
inventory_id UUID
sku VARCHAR
warehouse_id UUID
available_quantity INTEGER
reserved_quantity INTEGER
updated_at TIMESTAMP

Warehouse Table

Column Type
warehouse_id UUID
warehouse_name VARCHAR
city VARCHAR
state VARCHAR

Pricing Database

Price Table

Column Type
price_id UUID
sku VARCHAR
selling_price DECIMAL
mrp DECIMAL
currency VARCHAR
effective_from TIMESTAMP

Promotion Database

Coupon Table

Column Type
coupon_id UUID
coupon_code VARCHAR
discount_type VARCHAR
discount_value DECIMAL
start_date TIMESTAMP
end_date TIMESTAMP

Shopping Cart Database

Cart Table

Column Type
cart_id UUID
customer_id UUID
created_at TIMESTAMP

Cart Item Table

Column Type
cart_item_id UUID
cart_id UUID
sku VARCHAR
quantity INTEGER
unit_price DECIMAL

Wishlist Database

Wishlist Table

Column Type
wishlist_id UUID
customer_id UUID

Wishlist Item Table

Column Type
item_id UUID
wishlist_id UUID
sku VARCHAR

Order Database

Order Table

Column Type
order_id UUID
customer_id UUID
total_amount DECIMAL
order_status VARCHAR
payment_status VARCHAR
shipping_status VARCHAR
created_at TIMESTAMP

Order Item Table

Column Type
item_id UUID
order_id UUID
sku VARCHAR
quantity INTEGER
selling_price DECIMAL

Order Status

Status
Created
Payment Pending
Confirmed
Packed
Shipped
Delivered
Cancelled
Returned
Refunded

Payment Database

Payment Table

Column Type
payment_id UUID
order_id UUID
payment_method VARCHAR
transaction_id VARCHAR
payment_status VARCHAR
amount DECIMAL

Shipping Database

Shipment Table

Column Type
shipment_id UUID
order_id UUID
warehouse_id UUID
tracking_number VARCHAR
carrier VARCHAR
shipment_status VARCHAR

Review Database

Review Table

Column Type
review_id UUID
customer_id UUID
product_id UUID
rating INTEGER
review_text TEXT
created_at TIMESTAMP

Entity Relationship

flowchart TD

Customer

Product

Cart

Order

Payment

Shipment

Review

Customer --> Cart

Cart --> Order

Order --> Payment

Order --> Shipment

Product --> Review

Customer --> Review

Why UUID?

Benefits:

  • Globally unique
  • Easy event correlation
  • Multi-region support
  • No ID collisions

Product Catalog Design

The Product Service manages:

  • Products
  • Categories
  • Variants
  • Brands
  • Images
  • Specifications

Category Hierarchy

flowchart TD

Electronics

Electronics --> Mobiles

Electronics --> Laptops

Mobiles --> Smartphones

Mobiles --> FeaturePhones

Inventory Workflow

flowchart LR

Warehouse

Warehouse --> Inventory

Inventory --> Reservation

Reservation --> Order

Inventory is:

  • Reserved during checkout
  • Deducted after successful payment
  • Released if payment fails

Shopping Cart Workflow

flowchart LR

Browse

Browse --> AddToCart

AddToCart --> UpdateQuantity

UpdateQuantity --> Checkout

Wishlist Workflow

flowchart LR

Browse

Browse --> Wishlist

Wishlist --> Cart

Pricing Workflow

Price calculation includes:

  • Base price
  • Coupon
  • Discount
  • Tax
  • Shipping charge
Final Price

=

Product Price

-

Discount

+

Tax

+

Shipping

Coupon Validation

Coupon validation checks:

  • Expiration date
  • Customer eligibility
  • Minimum purchase
  • Product restrictions
  • Usage limit

Order Workflow

flowchart LR

Checkout

Checkout --> Payment

Payment --> Inventory

Inventory --> Order

Order --> Shipping

Payment Workflow

flowchart LR

Checkout

Checkout --> Gateway

Gateway --> Bank

Bank --> Success

Bank --> Failure

Shipping Workflow

flowchart LR

Order

Order --> Warehouse

Warehouse --> Packing

Packing --> Carrier

Carrier --> Customer

Review Workflow

flowchart LR

Delivered

Delivered --> Review

Review --> Rating

Only verified customers should be allowed to review products.


Search Architecture

Search supports:

  • Keyword search
  • Filters
  • Brand
  • Category
  • Price
  • Rating
  • Availability
  • Suggestions
  • Autocomplete

Search Components

flowchart LR

Product

Product --> SearchIndex

Customer --> SearchAPI

SearchAPI --> SearchIndex

REST API Design


Customer APIs

Register Customer

POST /customers

Get Customer

GET /customers/{id}

Update Customer

PUT /customers/{id}

Product APIs

Search Products

GET /products

Example

GET /products?category=Mobiles&brand=Apple

Get Product

GET /products/{id}

Cart APIs

Add Item

POST /cart/items

Request

{
  "sku":"SKU10001",
  "quantity":2
}

Response

{
  "status":"ADDED"
}

Update Quantity

PUT /cart/items/{id}

Delete Item

DELETE /cart/items/{id}

Wishlist APIs

POST /wishlist/items
DELETE /wishlist/items/{id}

Order APIs

Create Order

POST /orders

Response

{
  "orderId":"ORD10001",
  "status":"CREATED"
}

Get Order

GET /orders/{id}

Cancel Order

POST /orders/{id}/cancel

Payment APIs

POST /payments
GET /payments/{id}

Shipping APIs

GET /shipments/{id}
GET /shipments/{id}/tracking

Review APIs

POST /reviews
GET /products/{id}/reviews

Event-Driven Architecture

Business events are published to Kafka.

flowchart LR

Order

Order --> Kafka

Inventory --> Kafka

Payment --> Kafka

Shipping --> Kafka

Kafka --> Notification

Kafka --> Analytics

Kafka --> Reporting

Kafka Topics

Topic Producer Consumer
customer-created Customer Service Analytics
product-created Product Service Search
inventory-updated Inventory Service Search
cart-created Cart Service Analytics
order-created Order Service Payment
payment-success Payment Service Inventory
payment-failed Payment Service Order
inventory-reserved Inventory Service Order
shipment-created Shipping Service Notification
shipment-delivered Shipping Service Review
review-created Review Service Product

Sample Kafka Event

{
  "event":"ORDER_CREATED",
  "orderId":"ORD10001",
  "customerId":"CUS1001",
  "totalAmount":1499.99,
  "createdAt":"2026-08-01T10:20:30Z"
}

Service Communication

Use synchronous communication for:

  • Authentication
  • Product details
  • Price calculation
  • Payment authorization
  • Inventory validation

Use asynchronous communication for:

  • Notifications
  • Analytics
  • Search indexing
  • Recommendation updates
  • Shipping events

Data Consistency

Strong consistency is required for:

  • Payments
  • Orders
  • Inventory
  • Refunds

Eventual consistency is acceptable for:

  • Search index
  • Product recommendations
  • Reporting
  • Analytics
  • Notifications

Error Handling

Error Action
Product unavailable Reject checkout
Inventory shortage Suggest lower quantity
Payment failed Retry or cancel order
Coupon expired Reject coupon
Shipment failed Retry logistics
Duplicate order Use idempotency key

Best Practices

  • Database per microservice
  • UUID for distributed systems
  • Event-driven communication
  • Idempotent checkout APIs
  • Inventory reservation before payment capture
  • Store images in object storage
  • Maintain immutable order history
  • Validate coupons centrally
  • Allow reviews only after successful delivery
  • Keep search index separate from transactional databases


Enterprise Architecture

flowchart LR

Customer

Customer --> Gateway

Gateway --> Customer

Gateway --> Product

Gateway --> Cart

Gateway --> Order

Gateway --> Inventory

Gateway --> Payment

Gateway --> Shipping

Gateway --> Notification

Customer Registration Workflow

Customer onboarding consists of:

  1. Register account
  2. Verify email or phone
  3. Create customer profile
  4. Create empty shopping cart
  5. Initialize wishlist
  6. Send welcome notification

Registration Workflow

flowchart TD

Register

Register --> Verification

Verification --> Profile

Profile --> Cart

Cart --> Wishlist

Wishlist --> Notification

Shopping Cart Workflow

The shopping cart is temporary storage for products before checkout.

Supported operations:

  • Add product
  • Remove product
  • Update quantity
  • Save for later
  • Apply coupon
  • Estimate shipping

Shopping Cart Flow

flowchart LR

Browse

Browse --> Product

Product --> Cart

Cart --> Coupon

Coupon --> Checkout

Cart Validation

Before checkout validate:

  • Product exists
  • Product is active
  • Inventory available
  • Seller active
  • Pricing valid
  • Coupon eligibility

Checkout Workflow

Checkout is the most critical business workflow.

Steps:

  1. Validate cart
  2. Reserve inventory
  3. Calculate taxes
  4. Apply discounts
  5. Calculate shipping
  6. Process payment
  7. Create order
  8. Generate shipment
  9. Notify customer

Checkout Architecture

flowchart TD

Cart

Cart --> Pricing

Pricing --> Inventory

Inventory --> Payment

Payment --> Order

Order --> Shipping

Shipping --> Notification

Inventory Reservation

Inventory should not be permanently reduced during checkout.

Instead:

  • Reserve inventory
  • Complete payment
  • Deduct inventory
  • Release reservation if payment fails

Benefits:

  • Prevent overselling
  • Faster recovery
  • Better customer experience

Inventory States

Available

↓

Reserved

↓

Sold

Cancelled orders move inventory back to Available.


Inventory Reservation Workflow

flowchart LR

Available

Available --> Reserved

Reserved --> Sold

Reserved --> Available

Payment Gateway Integration

Supported payment methods:

  • Credit Card
  • Debit Card
  • Digital Wallet
  • UPI
  • Net Banking
  • Gift Card
  • Buy Now Pay Later

Payment Processing

flowchart TD

Checkout

Checkout --> Gateway

Gateway --> Bank

Bank --> Authorized

Authorized --> Captured

Captured --> Order

Payment States

Status
Pending
Authorized
Captured
Failed
Cancelled
Refunded

Idempotent Payments

Payment APIs must be idempotent.

Example:

Payment Request

↓

Network Timeout

↓

Retry

↓

Same Transaction

No duplicate payments should occur.


Order Fulfillment

After payment:

  1. Create order
  2. Reserve warehouse inventory
  3. Pick items
  4. Pack items
  5. Generate shipping label
  6. Assign carrier
  7. Dispatch shipment

Fulfillment Workflow

flowchart LR

Order

Order --> Warehouse

Warehouse --> Picking

Picking --> Packing

Packing --> Shipment

Warehouse Management

Warehouse responsibilities:

  • Stock storage
  • Picking
  • Packing
  • Inventory updates
  • Shipment generation
  • Stock replenishment

Warehouse Allocation

Select warehouse using:

  • Customer location
  • Inventory availability
  • Shipping cost
  • Delivery SLA
  • Warehouse capacity

Shipping Workflow

flowchart TD

Warehouse

Warehouse --> Carrier

Carrier --> Transit

Transit --> Delivery

Delivery --> Customer

Shipment Status

Status
Created
Packed
Shipped
In Transit
Out for Delivery
Delivered
Failed

Return Workflow

Customers may request returns for:

  • Damaged product
  • Wrong item
  • Defective item
  • Size mismatch
  • Product not as expected

Return Process

flowchart LR

Return

Return --> Pickup

Pickup --> Inspection

Inspection --> Refund

Inspection --> Replacement

Refund Workflow

flowchart LR

RefundRequest

RefundRequest --> Approval

Approval --> PaymentGateway

PaymentGateway --> Customer

CQRS

E-Commerce platforms generate far more reads than writes.

Examples

Writes:

  • Add product
  • Place order
  • Update inventory
  • Submit review

Reads:

  • Product search
  • Home page
  • Recommendations
  • Product details
  • Order history

CQRS Architecture

flowchart LR

User

User --> CommandAPI

User --> QueryAPI

CommandAPI --> WriteDB

WriteDB --> Kafka

Kafka --> ReadDB

ReadDB --> QueryAPI

Benefits of CQRS

  • Faster product pages
  • Independent scaling
  • Better reporting
  • Optimized dashboards
  • Reduced database contention

Saga Pattern

Checkout spans multiple services.

Workflow:

  1. Reserve inventory
  2. Authorize payment
  3. Create order
  4. Generate shipment
  5. Send notification

Each service manages its own local transaction.


Saga Workflow

flowchart TD

Inventory

Inventory --> Payment

Payment --> Order

Order --> Shipping

Shipping --> Notification

Compensation Example

Payment fails after inventory reservation.

Compensation:

flowchart TD

InventoryReserved

InventoryReserved --> PaymentFailed

PaymentFailed --> InventoryReleased

This avoids distributed database transactions while maintaining consistency.


Redis Caching

Cache frequently accessed information.

Examples:

  • Product details
  • Category list
  • Popular products
  • Inventory availability
  • Seller ratings
  • Homepage content

Cache Architecture

flowchart LR

Application

Application --> Redis

Redis --> Database

Data TTL
Product Details 15 Minutes
Category List 6 Hours
Homepage Banners 30 Minutes
Seller Rating 1 Hour
Inventory Availability 30 Seconds
Popular Products 10 Minutes

Never Cache

Avoid caching:

  • Payment authorization
  • Checkout session state
  • Active order status during payment
  • Authentication tokens
  • Refund processing state

Elasticsearch

Product search should not query the transactional database directly.

Instead:

  • Product changes
  • Kafka events
  • Elasticsearch indexing

Search Architecture

flowchart LR

Product

Product --> Kafka

Kafka --> Elasticsearch

Customer --> SearchAPI

SearchAPI --> Elasticsearch

Search Features

Support:

  • Full-text search
  • Autocomplete
  • Typo tolerance
  • Faceted filtering
  • Brand filtering
  • Category filtering
  • Price range
  • Relevance ranking

Recommendation Engine

Generate recommendations using:

  • Purchase history
  • Browsing history
  • Wishlist
  • Frequently bought together
  • Trending products
  • Similar products

Recommendation Flow

flowchart LR

Customer

Customer --> Behavior

Behavior --> Recommendation

Recommendation --> Homepage

Fraud Detection

Detect suspicious activities:

  • Multiple failed payments
  • High-value orders
  • Multiple cards
  • Rapid purchases
  • Fake reviews
  • Coupon abuse
  • Bot activity

Fraud Workflow

flowchart LR

Order

Order --> FraudCheck

FraudCheck --> Approved

FraudCheck --> ManualReview

Security Architecture

Follow Zero Trust principles.

Protect:

  • Customer accounts
  • Payments
  • Seller data
  • Personally Identifiable Information (PII)
  • Order history

Authentication

Support:

  • Username & Password
  • OAuth2 Login
  • Multi-Factor Authentication
  • Social Login

Authorization

Typical roles:

  • Customer
  • Seller
  • Warehouse Staff
  • Delivery Partner
  • Customer Support
  • Finance
  • Marketplace Administrator

Security Flow

flowchart LR

User

User --> Login

Login --> MFA

MFA --> JWT

JWT --> API

API Security

Secure every API using:

  • HTTPS
  • OAuth2
  • JWT
  • Rate Limiting
  • Input Validation
  • Request Signing
  • Correlation IDs
  • Idempotency Keys

Encryption

Encrypt:

  • Customer information
  • Payment information
  • Saved addresses
  • Order history
  • Personal identifiers

Recommended:

  • TLS 1.3 for data in transit
  • AES-256 for stored sensitive data

Secrets Management

Never store secrets in application code.

Examples:

  • Database credentials
  • API keys
  • JWT signing keys
  • Payment gateway credentials
  • Encryption keys

Use centralized secret management.


Multi-Region Deployment

Global marketplaces require multiple regions.

Goals:

  • Lower latency
  • Disaster recovery
  • High availability
  • Regulatory compliance

Multi-Region Architecture

flowchart LR

Users

Users --> RegionA

Users --> RegionB

RegionA --> DatabaseA

RegionB --> DatabaseB

DatabaseA --> Replication

Replication --> DatabaseB

High Availability

Target:

99.99%

Achieve this using:

  • Multiple Availability Zones
  • Auto Scaling
  • Read replicas
  • Load balancers
  • Database replication
  • Health checks

Reliability Patterns

Use:

  • Retry
  • Timeout
  • Circuit Breaker
  • Bulkhead
  • Rate Limiting
  • Dead Letter Queue

These patterns improve resilience and prevent cascading failures during high-traffic events.


Best Practices

  • Reserve inventory before payment capture.
  • Use idempotency keys for checkout and payment APIs.
  • Separate search infrastructure from transactional databases.
  • Cache read-heavy data using Redis.
  • Use CQRS for large-scale read workloads.
  • Coordinate distributed transactions using the Saga Pattern.
  • Encrypt sensitive customer information.
  • Continuously monitor fraud signals.
  • Publish business events through Kafka.
  • Design for multi-region deployment and fault tolerance.

Production Deployment, Kubernetes, Observability, Disaster Recovery & Production Operations

Topics covered:

  • Production Deployment Architecture
  • Docker
  • Kubernetes
  • API Gateway
  • Service Discovery
  • Load Balancing
  • CI/CD Pipeline
  • Rolling, Blue-Green & Canary Deployment
  • Monitoring
  • Logging
  • Distributed Tracing
  • Alerting
  • Disaster Recovery
  • Performance Optimization
  • Cost Optimization
  • Production Operations

Production Goals

A production-ready E-Commerce platform should provide:

  • 99.99% availability
  • Zero downtime deployment
  • High scalability
  • Low latency
  • Secure transactions
  • Automatic recovery
  • Complete observability
  • Disaster recovery
  • Global availability

Production Deployment Architecture

flowchart TD

Users

Users --> DNS

DNS --> CDN

CDN --> WAF

WAF --> LoadBalancer

LoadBalancer --> Gateway

Gateway --> Kubernetes

Kubernetes --> Customer

Kubernetes --> Product

Kubernetes --> Search

Kubernetes --> Cart

Kubernetes --> Order

Kubernetes --> Inventory

Kubernetes --> Payment

Kubernetes --> Shipping

Kubernetes --> Notification

Enterprise Infrastructure

Layer Technology
DNS Route53 / Cloud DNS
CDN CloudFront / Azure CDN
WAF AWS WAF
Load Balancer ALB / NGINX
API Gateway Kong / Spring Cloud Gateway
Container Runtime Docker
Orchestration Kubernetes
Messaging Kafka
Cache Redis
Search Elasticsearch
Database PostgreSQL
Monitoring Prometheus
Dashboard Grafana
Logging ELK / OpenSearch
Tracing Jaeger / Zipkin

Docker

Each microservice runs inside its own Docker container.

Benefits:

  • Environment consistency
  • Easy deployment
  • Fast rollback
  • Isolation
  • Better scalability

Sample Dockerfile

FROM eclipse-temurin:21-jre

WORKDIR /app

COPY target/order-service.jar app.jar

EXPOSE 8080

ENTRYPOINT ["java","-jar","app.jar"]

Kubernetes

Kubernetes manages:

  • Deployment
  • Scaling
  • Self-healing
  • Rolling updates
  • Service discovery
  • Failover

Kubernetes Architecture

flowchart TD

Users

Users --> Ingress

Ingress --> Gateway

Gateway --> ProductPods

Gateway --> SearchPods

Gateway --> CartPods

Gateway --> OrderPods

Gateway --> PaymentPods

Kubernetes Resources

Resource Purpose
Pod Runs containers
Deployment Replica management
Service Internal networking
Ingress External routing
ConfigMap Configuration
Secret Sensitive data
StatefulSet Stateful workloads
HPA Auto Scaling

Namespace Strategy

Separate environments:

production

staging

uat

development

Benefits:

  • Isolation
  • Security
  • Resource quotas
  • Easier deployments

Service Discovery

Applications communicate using service names.

Examples:

product-service

order-service

payment-service

inventory-service

Applications never depend on fixed IP addresses.


Internal Service Communication

flowchart LR

Order

Order --> Inventory

Inventory --> Payment

Payment --> Shipping

Shipping --> Notification

API Gateway

Responsibilities:

  • Authentication
  • Authorization
  • SSL termination
  • Rate limiting
  • Request routing
  • Request validation
  • API aggregation
  • Logging

Load Balancing

Traffic is distributed across healthy pods.

flowchart TD

Users

Users --> LoadBalancer

LoadBalancer --> Pod1

LoadBalancer --> Pod2

LoadBalancer --> Pod3

Benefits:

  • Better throughput
  • Lower latency
  • High availability

Horizontal Scaling

Increase pod count during traffic spikes.

Example:

5 Pods

↓

20 Pods

↓

100 Pods

Typical triggers:

  • CPU usage
  • Memory usage
  • Request rate
  • Kafka consumer lag

Vertical Scaling

Increase:

  • CPU
  • Memory
  • Storage

Typically used for:

  • PostgreSQL
  • Kafka Brokers
  • Elasticsearch Nodes

Scaling Strategy

Service Scaling Requirement
API Gateway Very High
Product High
Search Extremely High
Cart Very High
Order High
Inventory High
Payment High
Shipping Medium
Notification Very High
Recommendation High

CI/CD Pipeline

Every deployment follows an automated pipeline.

flowchart LR

Developer

Developer --> Git

Git --> Build

Build --> Test

Test --> SecurityScan

SecurityScan --> Docker

Docker --> Registry

Registry --> Kubernetes

Continuous Integration

Pipeline steps:

  1. Checkout code
  2. Compile
  3. Unit tests
  4. Integration tests
  5. Sonar analysis
  6. Dependency scanning
  7. Docker image build
  8. Push to registry

Continuous Delivery

Deployment flow:

Development

↓

QA

↓

UAT

↓

Performance Testing

↓

Security Validation

↓

Production Approval

↓

Production Deployment

Deployment Strategies

Rolling Deployment

flowchart LR

Old

Old --> Mixed

Mixed --> New

Advantages:

  • Zero downtime
  • Automatic rollback
  • Gradual rollout

Blue-Green Deployment

flowchart LR

Users

Users --> Blue

Blue --> Green

Suitable for:

  • Payment services
  • Checkout
  • Critical releases

Canary Deployment

Deploy to a small percentage of users.

5%

↓

20%

↓

50%

↓

100%

Ideal for:

  • Recommendation engine
  • Search improvements
  • New checkout features

Monitoring Architecture

flowchart LR

Applications

Applications --> Metrics

Applications --> Logs

Applications --> Traces

Metrics --> Prometheus

Prometheus --> Grafana

Logs --> ELK

Traces --> Jaeger

Technical Metrics

Monitor:

  • API latency
  • Throughput
  • Error rate
  • JVM Heap
  • CPU
  • Memory
  • Disk usage
  • Kafka lag
  • Elasticsearch latency
  • Database response time

Business Metrics

Track:

  • Orders per minute
  • Checkout success rate
  • Payment success rate
  • Cart abandonment rate
  • Average order value
  • Daily revenue
  • Refund rate
  • Search success rate
  • Inventory accuracy
  • Customer signups

Golden Signals

Signal Description
Latency Response time
Traffic Requests/sec
Errors Failed requests
Saturation Resource utilization

Logging Strategy

Every request should include:

  • Timestamp
  • Trace ID
  • Correlation ID
  • Customer ID
  • Order ID
  • Request ID
  • Response time
  • HTTP status

Sample Structured Log

{
  "traceId":"TR10001",
  "orderId":"ORD1001",
  "customerId":"CUS100",
  "service":"order-service",
  "status":"CONFIRMED",
  "responseTime":78
}

Log Levels

Level Purpose
INFO Business events
WARN Recoverable issues
ERROR Failures
DEBUG Development only

Avoid DEBUG logging in production except during controlled troubleshooting.


Distributed Tracing

One checkout request travels across multiple services.

flowchart LR

Gateway

Gateway --> Cart

Cart --> Inventory

Inventory --> Payment

Payment --> Order

Order --> Shipping

Shipping --> Notification

Trace IDs enable end-to-end request tracking.


Health Checks

Expose actuator endpoints.

GET /actuator/health

GET /actuator/liveness

GET /actuator/readiness

Kubernetes uses these endpoints to determine application health.


Alerting Strategy

Condition Severity
Checkout Failure > 3% Critical
Payment Failure > 5% Critical
Inventory Sync Delay Warning
Kafka Consumer Lag Warning
Search Cluster Down Critical
Pod CrashLoop Critical
CPU > 90% Warning
Database Replication Failure Critical

Backup Strategy

Protect critical business data.

Recommended schedule:

  • Hourly incremental backup
  • Daily full backup
  • Weekly archive
  • Cross-region replication

Perform restoration testing regularly.


Disaster Recovery

The platform should survive:

  • Data center outage
  • Cloud region failure
  • Database failure
  • Kubernetes cluster failure
  • Payment gateway outage

Disaster Recovery Architecture

flowchart TD

PrimaryRegion

PrimaryRegion --> DatabaseA

PrimaryRegion --> KafkaA

DatabaseA --> Replication

KafkaA --> Replication

Replication --> SecondaryRegion

SecondaryRegion --> DatabaseB

SecondaryRegion --> KafkaB

Recovery Objectives

Objective Target
Recovery Point Objective (RPO) Near Zero
Recovery Time Objective (RTO) Less than 30 Minutes

Failure Scenarios

Payment Gateway Failure

Recovery:

  • Retry payment
  • Switch to secondary provider
  • Notify customer

Kubernetes Node Failure

Recovery:

  • Restart pods
  • Redistribute workload
  • Health-based traffic routing

Database Failure

Recovery:

  • Promote read replica
  • Redirect traffic
  • Validate consistency

Kafka Failure

Recovery:

  • Retry producer
  • Retry consumer
  • Dead Letter Queue
  • Cluster replication

Regional Outage

Recovery:

  • DNS failover
  • Activate secondary region
  • Promote standby databases
  • Resume traffic

Performance Optimization

Improve performance using:

  • Redis caching
  • Connection pooling
  • Read replicas
  • Database indexing
  • Async messaging
  • Batch processing
  • CDN
  • Image optimization
  • HTTP compression

Search Performance

Optimize search by:

  • Elasticsearch indexing
  • Sharding
  • Replication
  • Autocomplete caching
  • Faceted search optimization
  • Query tuning

Cost Optimization

Reduce infrastructure costs through:

  • Auto Scaling
  • Spot instances (non-critical workloads)
  • Storage lifecycle policies
  • Compress product images
  • Kafka retention optimization
  • Right-size Kubernetes nodes
  • Archive historical logs

Security Operations

Production security should include:

  • Mutual TLS
  • Network Policies
  • Secret rotation
  • Container image scanning
  • Runtime threat detection
  • RBAC
  • WAF
  • Zero Trust networking

Production Readiness Checklist

Area Ready
Docker
Kubernetes
CI/CD
Security Scan
Monitoring
Logging
Distributed Tracing
Auto Scaling
Backup Validation
Disaster Recovery
Alerting
Rollback Strategy

Production Operations

Operations teams should continuously monitor:

  • Checkout success rate
  • Payment latency
  • Search latency
  • Inventory synchronization
  • Order processing time
  • Shipping delays
  • Kafka consumer lag
  • Elasticsearch health
  • Database replication
  • Infrastructure cost

Best Practices

  • Containerize every microservice.
  • Use Kubernetes for orchestration.
  • Keep deployments automated with CI/CD.
  • Prefer rolling or canary deployments for customer-facing services.
  • Monitor both technical and business metrics.
  • Propagate Trace IDs and Correlation IDs.
  • Test disaster recovery regularly.
  • Protect sensitive customer and payment data.
  • Continuously optimize search performance.
  • Validate production readiness before every release.

Real Production Challenges

Large e-commerce platforms process billions of requests every day.

Common production challenges include:

  • Flash sales
  • Black Friday traffic
  • Inventory overselling
  • Payment gateway failures
  • Search spikes
  • Recommendation latency
  • Warehouse synchronization
  • Shipping delays
  • Fraud attacks
  • Distributed system failures

Challenge 1 — Black Friday Scaling

Traffic can increase dramatically.

Example:

Normal Day

150,000 Concurrent Users

↓

Black Friday

12 Million Concurrent Users

Challenges:

  • API overload
  • Database saturation
  • Payment spikes
  • Search latency
  • Cart failures

Solutions:

  • Auto Scaling
  • CDN
  • Redis
  • Kafka
  • Read Replicas
  • Multi-region deployment

Black Friday Architecture

flowchart TD

Users

Users --> CDN

CDN --> Gateway

Gateway --> Product

Gateway --> Search

Gateway --> Cart

Gateway --> Order

Order --> Kafka

Kafka --> Inventory

Kafka --> Notification

Challenge 2 — Flash Sale

During flash sales, thousands of users attempt to buy the same product simultaneously.

Example:

10,000 Units

↓

2 Million Purchase Requests

Without proper architecture:

  • Inventory becomes negative
  • Duplicate orders occur
  • Database locks increase
  • Payment failures rise

Flash Sale Solution

Use:

  • Inventory reservation
  • Redis counters
  • Kafka queue
  • Rate limiting
  • Queue-based checkout

Flash Sale Flow

flowchart LR

Customer

Customer --> Queue

Queue --> Inventory

Inventory --> Payment

Payment --> Order

Challenge 3 — Inventory Overselling

Overselling occurs when multiple customers purchase the last available inventory simultaneously.

Example:

Available Inventory

1 Unit

↓

Customer A

↓

Customer B

Without coordination, both orders may succeed.


Preventing Overselling

Recommended techniques:

  • Optimistic locking
  • Inventory reservation
  • Distributed locks
  • Atomic Redis operations
  • FIFO processing
  • Saga Pattern

Inventory Lifecycle

flowchart LR

Available

Available --> Reserved

Reserved --> Sold

Reserved --> Available

Challenge 4 — Search Traffic

Product search usually generates the highest request volume.

Example:

Search Requests

120,000/sec

Solutions:

  • Elasticsearch
  • Redis cache
  • CDN
  • Search replicas
  • Autocomplete cache

Search Architecture

flowchart LR

Customer

Customer --> SearchAPI

SearchAPI --> Elasticsearch

Elasticsearch --> Redis

Challenge 5 — Recommendation System

Recommendation engines require near real-time updates.

Inputs:

  • Purchase history
  • Browsing history
  • Wishlist
  • Cart activity
  • Trending products
  • Frequently bought together

Recommendation Flow

flowchart LR

Behavior

Behavior --> Kafka

Kafka --> Recommendation

Recommendation --> Homepage

Challenge 6 — Payment Gateway Failure

External payment providers occasionally become unavailable.

Recovery strategy:

  • Retry
  • Timeout
  • Secondary gateway
  • Circuit Breaker
  • Manual reconciliation

Payment Failover

flowchart LR

Checkout

Checkout --> GatewayA

GatewayA --> Success

GatewayA --> GatewayB

Challenge 7 — Warehouse Synchronization

Large retailers have multiple warehouses.

Inventory changes because of:

  • Orders
  • Returns
  • Transfers
  • Damage
  • Restocking

Synchronize inventory through event-driven messaging.


Warehouse Architecture

flowchart LR

WarehouseA

WarehouseA --> Kafka

WarehouseB --> Kafka

Kafka --> Inventory

Challenge 8 — Fraud Detection

Fraud scenarios include:

  • Fake accounts
  • Card testing
  • Coupon abuse
  • Fake reviews
  • Account takeover
  • Bot traffic

Fraud Detection Flow

flowchart LR

Order

Order --> Fraud

Fraud --> Approved

Fraud --> ManualReview

Scalability Strategy

Each service scales independently.

flowchart TD

Gateway

Gateway --> Search

Gateway --> Cart

Gateway --> Order

Gateway --> Inventory

Gateway --> Payment

Gateway --> Shipping

Gateway --> Notification

Scaling Strategy

Service Scaling Need
Gateway Extremely High
Search Extremely High
Product High
Cart Very High
Order High
Inventory High
Payment High
Shipping Medium
Recommendation Very High
Notification High

Database Scaling

Use:

  • Read Replicas
  • Partitioning
  • Connection Pooling
  • Query Optimization
  • Archiving
  • Sharding (when necessary)

Database Architecture

flowchart LR

Application

Application --> PrimaryDB

PrimaryDB --> ReadReplica1

PrimaryDB --> ReadReplica2

Kafka Scaling

Increase throughput using:

  • Topic partitioning
  • Consumer groups
  • Horizontal scaling

Example:

Order Topic

↓

40 Partitions

↓

120 Consumers

Redis Scaling

flowchart LR

Application

Application --> RedisCluster

RedisCluster --> Node1

RedisCluster --> Node2

RedisCluster --> Node3

Ideal for:

  • Product pages
  • Search cache
  • Categories
  • Inventory lookup
  • Popular products

Cost Optimization

Reduce infrastructure cost by:

  • Auto Scaling
  • Spot instances for background jobs
  • Image compression
  • Storage lifecycle policies
  • Kafka retention optimization
  • CDN caching
  • Archive old orders

Storage Strategy

Storage Tier Data
Hot Active products
Warm Recent orders
Cold Historical orders
Archive Audit records

Performance Optimization

Improve performance through:

  • Redis caching
  • Read replicas
  • Connection pooling
  • Batch processing
  • Async messaging
  • CDN
  • Image optimization
  • GZIP/Brotli compression

Reliability Patterns

Use:

  • Retry
  • Timeout
  • Circuit Breaker
  • Bulkhead
  • Rate Limiting
  • Dead Letter Queue

These patterns improve resiliency and isolate failures.


Architecture Trade-offs

Monolith vs Microservices

Monolith Microservices
Faster initial development Independent deployments
Easier debugging Better scalability
Shared database Database per service
Simpler operations Better fault isolation

SQL vs NoSQL

SQL NoSQL
Strong consistency Flexible schema
ACID transactions Massive scalability
Orders & Payments Catalog & Analytics

REST vs Event-Driven

REST Event-Driven
Immediate response Asynchronous
Easier debugging Loose coupling
Request/Response Event streaming

Synchronous vs Asynchronous

Use synchronous communication for:

  • Login
  • Product details
  • Price calculation
  • Payment authorization

Use asynchronous communication for:

  • Notifications
  • Analytics
  • Search indexing
  • Recommendation updates
  • Shipment tracking

Architecture Decision Records (ADR)

ADR-001

Decision

Use Microservices.

Reason:

Independent deployments and scaling.


ADR-002

Decision

Use Kafka.

Reason:

Reliable event streaming between services.


ADR-003

Decision

Use Elasticsearch.

Reason:

High-performance product search.


ADR-004

Decision

Use Redis.

Reason:

Low-latency access for frequently requested data.


ADR-005

Decision

Use Saga Pattern.

Reason:

Distributed transaction management without two-phase commit.


ADR-006

Decision

Deploy on Kubernetes.

Reason:

Self-healing, auto scaling, rolling deployments, and operational consistency.


Common Production Issues

Issue Solution
Slow Product Search Elasticsearch
Cart Expiration Redis
Payment Timeout Retry + Circuit Breaker
Inventory Mismatch Reservation System
Kafka Consumer Lag Scale Consumers
Search Cluster Down Read Replica
High Database CPU Read Replicas
Flash Sale Queue Growth Horizontal Scaling
Pod CrashLoop Kubernetes Restart
Region Failure Disaster Recovery

Production Readiness Checklist

Area Ready
Security Review
Performance Testing
Load Testing
Monitoring
Logging
Tracing
Backup Validation
Disaster Recovery
Auto Scaling
Rollback Strategy
Capacity Planning
Cost Review

Best Practices

  • Reserve inventory before payment capture.
  • Use idempotency keys for checkout.
  • Publish business events through Kafka.
  • Separate search from transactional databases.
  • Cache read-heavy data with Redis.
  • Protect payment APIs using rate limiting and MFA where appropriate.
  • Monitor business KPIs continuously.
  • Encrypt sensitive customer information.
  • Test disaster recovery regularly.
  • Scale services independently.

Common Mistakes

Shared Database

Creates tight coupling between services.


Updating Inventory Before Payment

Can result in lost sales if payment fails.


Missing Idempotency

Causes duplicate orders and duplicate payments.


Tight Service Coupling

Reduces scalability and increases deployment risk.


Ignoring Cache Invalidation

Customers may see stale prices or incorrect inventory.


Blocking Synchronous Workflows

Long-running operations should use asynchronous messaging.


E-Commerce System Design Interview Questions

1. How would you design Amazon?

Use microservices for catalog, search, cart, orders, inventory, payments, shipping, notifications, and recommendations connected through event-driven messaging.


2. How would you prevent inventory overselling?

Use inventory reservation, optimistic locking, distributed locks where appropriate, Redis atomic counters, and Saga compensation.


3. Why separate Product and Inventory services?

Product metadata changes infrequently, while inventory changes continuously and has different scalability requirements.


4. Why use Elasticsearch?

To provide fast full-text search, filtering, autocomplete, typo tolerance, and relevance ranking.


5. What data should be cached?

Product details, categories, popular products, search results, seller ratings, and homepage content.


6. What should never be cached?

Payment authorization state, active checkout sessions, refund processing state, and authentication credentials.


7. Why use CQRS?

Product browsing is read-heavy, while orders and inventory are write-heavy. CQRS allows independent optimization.


8. Why use Saga Pattern?

To coordinate checkout, payment, inventory reservation, shipping, and notifications across multiple services.


9. How do you handle payment failures?

Retry when appropriate, use circuit breakers, switch to secondary gateways, and compensate distributed transactions.


10. How do you secure payment APIs?

HTTPS, OAuth2, JWT, API signing, rate limiting, encryption, idempotency keys, and continuous monitoring.


Use Elasticsearch clusters, shard indexes, replicas, Redis caching, and CDN for static assets.


12. Why separate Search Service?

Search workloads are significantly higher than transactional workloads and require specialized indexing.


13. How do you build recommendations?

Analyze browsing history, purchases, cart activity, wishlists, and trending products.


14. What happens during checkout?

Validate cart, reserve inventory, calculate pricing, authorize payment, create order, trigger shipping, and notify the customer.


15. Why use Kafka?

To decouple services and process orders, inventory updates, notifications, analytics, and search indexing asynchronously.


16. How do you prevent duplicate orders?

Use idempotency keys, unique request identifiers, and transactional order creation.


17. What metrics should be monitored?

Checkout success rate, payment latency, search latency, inventory accuracy, order throughput, API latency, and infrastructure utilization.


18. How do you handle flash sales?

Queue requests, reserve inventory, rate limit customers, scale horizontally, and process asynchronously.


19. Why store images separately?

Images are large binary objects and are better suited for object storage rather than relational databases.


20. How do you manage warehouse selection?

Choose based on inventory availability, customer location, shipping cost, and delivery SLA.


21. How do you process returns?

Validate eligibility, schedule pickup, inspect items, approve refund or replacement, and update inventory.


22. How do you optimize database performance?

Use indexing, read replicas, partitioning, connection pooling, and query optimization.


23. Why use Redis?

To reduce latency for frequently accessed data and reduce load on primary databases.


24. How do you detect fraud?

Use behavioral analysis, velocity checks, risk scoring, anomaly detection, and manual review for suspicious transactions.


25. How do you support multiple sellers?

Separate seller management, inventory ownership, pricing, fulfillment, and settlement processes.


26. How do you support global deployment?

Deploy in multiple regions with replicated databases, global load balancing, CDN, and disaster recovery.


27. Which deployment strategy is safest?

Blue-Green or Canary deployments combined with automated rollback and monitoring.


28. Why is observability important?

Metrics, logs, and traces reduce Mean Time to Detect (MTTD) and Mean Time to Recover (MTTR).


29. What business KPIs should be monitored?

Revenue, conversion rate, cart abandonment, average order value, customer retention, payment success rate, and return rate.


30. What is the most important design principle?

Maintain inventory accuracy, reliable order processing, secure payments, and an excellent customer experience while ensuring scalability and fault tolerance.


E-Commerce Architecture Cheat Sheet

Area Recommended Solution
Architecture Microservices
API Style REST + Event-Driven
Search Elasticsearch
Messaging Kafka
Cache Redis
Workflow Saga Pattern
Read Optimization CQRS
Database PostgreSQL
Images Object Storage
Deployment Kubernetes
Monitoring Prometheus + Grafana
Logging ELK / OpenSearch
Tracing Jaeger / Zipkin
Authentication OAuth2 + JWT
High Availability Multi-Region
Disaster Recovery Active-Active / Active-Passive
Scalability Horizontal Scaling
Security TLS + WAF + RBAC

Complete Enterprise Architecture

flowchart TD

Customer

Customer --> Mobile

Customer --> Web

Mobile --> Gateway

Web --> Gateway

Gateway --> Auth

Gateway --> CustomerService

Gateway --> SellerService

Gateway --> ProductService

Gateway --> SearchService

Gateway --> CartService

Gateway --> OrderService

Gateway --> InventoryService

Gateway --> PaymentService

Gateway --> ShippingService

Gateway --> RecommendationService

ProductService --> Kafka

OrderService --> Kafka

InventoryService --> Kafka

PaymentService --> Kafka

Kafka --> NotificationService

Kafka --> AnalyticsService

Kafka --> SearchIndexer

SearchIndexer --> Elasticsearch

ProductService --> ProductDB

OrderService --> OrderDB

InventoryService --> InventoryDB

PaymentService --> PaymentDB

ProductService --> ObjectStorage

Final Summary

Designing a modern E-Commerce platform involves much more than enabling online purchases. Enterprise marketplaces must coordinate millions of customers, sellers, products, warehouses, payments, and deliveries while maintaining inventory consistency, fast search, secure transactions, and high availability.

Across this five-part case study, we designed the platform from business requirements through production deployment. We applied domain-driven microservices, CQRS, Saga Pattern, Kafka, Redis, Elasticsearch, Kubernetes, event-driven architecture, observability, and cloud-native deployment patterns to build a resilient marketplace capable of handling global-scale traffic and mission-critical business operations.


Key Takeaways

  • ✅ Separate business domains into independently deployable microservices.
  • ✅ Keep inventory consistent using reservation and Saga-based compensation.
  • ✅ Use Elasticsearch for high-performance product discovery.
  • ✅ Cache read-heavy data with Redis while carefully managing cache invalidation.
  • ✅ Publish business events through Kafka to reduce service coupling.
  • ✅ Secure payment workflows with encryption, idempotency, and strong authentication.
  • ✅ Scale services independently to support traffic spikes such as Black Friday.
  • ✅ Monitor both technical metrics and business KPIs.
  • ✅ Design for resilience with retries, circuit breakers, and disaster recovery.
  • ✅ Prioritize customer experience, reliability, and operational excellence in every architectural decision.