Microservice Architecture for a Large E-Commerce Platform
As Sherlock, I'll design and provide a complete, production-ready blueprint for a microservices-based e-commerce platform using Docker for containerization and Kubernetes (K8s) for orchestration. This architecture scales to handle millions of users, high traffic, and fault tolerance.
1. Architecture Overview
Key Principles
- Domain-Driven Design (DDD): Each microservice owns its bounded context.
- Event-Driven: Async communication via Apache Kafka for orders, inventory updates.
- 12-Factor App: Stateless services, config via env vars/Secrets.
- CQRS/Event Sourcing: Optional for high-scale services like Orders.
- API Gateway: Central entry point with auth (JWT/OAuth), rate limiting.
- Observability: Prometheus + Grafana for metrics, ELK for logs, Jaeger for tracing.
- Security: mTLS between services, RBAC in K8s.
- Scalability: HPA (Horizontal Pod Autoscaler), Cluster Autoscaler.
Microservices
| Service | Responsibilities | Database/Storage | Ports |
|---|
| API Gateway | Routing, auth, rate limiting, circuit breaker | N/A (Redis for sessions) | 8080 |
| User Service | Auth, profiles, registration | PostgreSQL | 3001 |
| Product Service | Catalog, search (Elasticsearch) | MongoDB | 3002 |
| Cart Service | Shopping cart management | Redis | 3003 |
| Order Service | Order creation, history | PostgreSQL | 3004 |
| Payment Service | Payment processing (Stripe integration) | PostgreSQL | 3005 |
| Inventory Service | Stock management, reservations | PostgreSQL + Redis | 3006 |
| Notification Service | Emails, SMS (async via Kafka) | N/A | 3007 |
| Recommendation Service | ML-based recs (async) | Cassandra | 3008 |
Communication
- Sync: REST/gRPC via Service Mesh (Istio optional).
- Async: Kafka topics (e.g.,
order-created, payment-processed).
- Databases: Per-service (Database-per-Service pattern).
Text-Based Diagram (Mermaid-like)
[Internet] --> Ingress (Nginx) --> API Gateway
API Gateway --> [UserSvc] [ProductSvc] [CartSvc] [OrderSvc] [PaymentSvc]
OrderSvc --> Kafka --> [InventorySvc] [NotificationSvc] [RecommendationSvc]
Databases: Postgres (User/Order/Payment/Inventory) | Mongo (Product) | Redis (Cart/Session) | ES (Search) | Kafka | Cassandra (Recs)
Monitoring: Prometheus --> Grafana | Jaeger (Tracing)
2. Tech Stack
- Languages/Frameworks: Node.js + Express (simple, scalable).
- Databases: Postgres (relational), MongoDB (products), Redis (cache/cart), Kafka (events).
- Tools: Docker 24+, Kubernetes 1.28+, Helm for DBs.
- Others: Nginx Ingress, Cert-Manager (TLS), ArgoCD (GitOps).
3. Docker Setup
Sample Dockerfile (for User Service - Node.js)
All services follow this pattern. Build with docker build -t user-service ..
# Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build # Assumes TypeScript
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./
EXPOSE 3001
CMD ["npm", "start"]
docker-compose.yml (Local Development)
Run with docker-compose up. Includes all services + DBs.
version: '3.8'
services:
postgres:
image: postgres:15
environment:
POSTGRES_DB: ecommerce
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
volumes: ['./data/postgres:/var/lib/postgresql/data']
ports: ['5432:5432']
mongodb:
image: mongo:7
volumes: ['./data/mongo:/data/db']
ports: ['27017:27017']
redis:
image: redis:7-alpine
ports: ['6379:6379']
kafka:
image: confluentinc/cp-kafka:7.5.0
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
depends_on: [zookeeper]
ports: ['9092:9092']
zookeeper:
image: confluentinc/cp-zookeeper:7.5.0
environment: {KAFKA_ZOOKEEPER_CLIENT_PORT: 2181}
ports: ['2181:2181']
api-gateway:
build: ./gateway
ports: ['8080:8080']
depends_on: [redis]
environment:
REDIS_URL: redis:6379
user-service:
build: ./services/user
ports: ['3001:3001']
depends_on: [postgres]
environment:
DB_URL: postgresql://user:pass@postgres:5432/ecommerce
# ... Repeat for other services (product, cart, etc.)
Sample User Service Code (Express app - services/user/index.js):
const express = require('express');
const { Pool } = require('pg');
const app = express();
app.use(express.json());
const pool = new Pool({ connectionString: process.env.DB_URL });
app.post('/register', async (req, res) => {
// Registration logic
const { name, email, password } = req.body;
await pool.query('INSERT INTO users (name, email, password) VALUES ($1, $2, $3)', [name, email, password]);
res.json({ message: 'User registered' });
});
app.listen(3001, () => console.log('User Service on 3001'));
Build/push images: docker build -t yourrepo/user-service:latest . && docker push yourrepo/user-service:latest
4. Kubernetes Deployment
Use Minikube for local: minikube start. For prod, EKS/GKE/AKS.
Prerequisites
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.4/cert-manager.yaml
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm install ingress-nginx ingress-nginx/ingress-nginx
helm repo add bitnami && helm install postgresql bitnami/postgresql # Or use operators
helm repo add confluent && helm install kafka confluentinc/cp-kafka # Simplified
Namespace
# k8s/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: ecommerce
---
Secrets/ConfigMaps
# k8s/secrets.yaml
apiVersion: v1
kind: Secret
metadata:
name: db-secrets
namespace: ecommerce
type: Opaque
data:
POSTGRES_PASSWORD: cGFzcw== # base64 'pass'
---
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
namespace: ecommerce
data:
KAFKA_BOOTSTRAP_SERVERS: "kafka:9092"
Deployment Example (User Service)
Apply with kubectl apply -k k8s/. Use Kustomize for overlays.
# k8s/user-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
namespace: ecommerce
spec:
replicas: 3
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
spec:
containers:
- name: user-service
image: yourrepo/user-service:latest
ports:
- containerPort: 3001
envFrom:
- configMapRef:
name: app-config
- secretRef:
name: db-secrets
resources:
requests: { cpu: '100m', memory: '128Mi' }
limits: { cpu: '500m', memory: '512Mi' }
---
apiVersion: v1
kind: Service
metadata:
name: user-service
namespace: ecommerce
spec:
selector:
app: user-service
ports:
- port: 3001
targetPort: 3001
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: user-service-hpa
namespace: ecommerce
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: user-service
minReplicas: 3
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
Repeat for other services (change image, port, env).
API Gateway Deployment + Ingress
# k8s/gateway-deployment.yaml + ingress.yaml
# Deployment similar to above, port 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ecommerce-ingress
namespace: ecommerce
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
cert-manager.io/cluster-issuer: "letsencrypt-prod" # TLS
spec:
ingressClassName: nginx
tls:
- hosts:
- ecommerce.example.com
rules:
- host: ecommerce.example.com
http:
paths:
- path: /users
pathType: Prefix
backend:
service:
name: user-service
port:
number: 3001
- path: /products
pathType: Prefix
backend:
service:
name: product-service
port:
number: 3002
# ... Add others
Kafka (via Helm)
helm install kafka confluentinc/cp-helm-charts --set kafka.replicaCount=3 -n ecommerce
5. Deployment & Operations
Deploy All
kubectl create ns ecommerce
kubectl apply -f k8s/ # All YAMLs
kubectl rollout status deployment/user-service -n ecommerce
Scaling & Monitoring
- HPA: Auto-scales on CPU/Metrics.
- Prometheus:
helm install prometheus prometheus-community/kube-prometheus-stack -n monitoring
- Port-Forward:
kubectl port-forward svc/api-gateway 8080:8080 -n ecommerce
CI/CD (GitHub Actions Example)
# .github/workflows/deploy.yaml
name: Deploy to K8s
on: [push]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build & Push
uses: docker/build-push-action@v5
with:
push: true
tags: yourrepo/user-service:${{ github.sha }}
- name: Deploy
uses: steebchen/kubectl@v2
with:
config: ${{ secrets.KUBE_CONFIG }}
command: apply -f k8s/
Performance & Cost Optimization
- Multi-Region: Use K8s Federation or Istio.
- Cost: Spot Instances, Vertical Pod Autoscaler.
- Testing: Chaos Engineering with Litmus.
This is a fully functional, scalable architecture. Clone a repo template from GitHub (e.g., adapt "microservices-demo") or ask for specific service code expansions. Productionize by adding Istio, ArgoCD, and external DBs (RDS/DocumentDB). Questions?