Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Case Study 4: E‑commerce Platform (Amazon)

Sàn thương mại điện tử với product catalog, cart, order, payment, recommendations.


Bước 1: Thu thập yêu cầu

Functional requirements

  • Product catalog: Browse, search, filter products.
  • Shopping cart: Add/remove items, update quantity.
  • Order processing: Checkout, payment, shipping.
  • Inventory management: Track stock levels.
  • Recommendations: Personalized product suggestions.
  • User accounts: Profiles, order history, addresses.
  • Reviews & Ratings: User feedback.

Non‑functional requirements

  • High availability: 99.99% uptime (critical for sales).
  • Consistency: Inventory và orders phải consistent.
  • Low latency: Page load < 2s, search < 200ms.
  • Scalability: Handle traffic spikes (Black Friday, sales).
  • Security: PCI DSS compliance cho payment.

Scale estimation

  • Users: 100 triệu DAU.
  • Products: 100 triệu SKUs.
  • Orders per day: 10 triệu.
  • Page views per day: 1 tỷ.
  • Peak traffic: 10x normal (sales events).

Bước 2: Ước lượng

Traffic estimates

  • Page views: 1B / 86400 ≈ 12,000 RPS (average).
  • Search requests: 100M / 86400 ≈ 1,200 RPS.
  • Orders: 10M / 86400 ≈ 120 RPS.
  • Peak RPS: ~10x → 120,000 page views, 1,200 orders.

Storage estimates

  • Product catalog: 100M products * 10 KB ≈ 1 TB.
  • User data: 100M users * 1 KB ≈ 100 GB.
  • Orders: 10M/day * 1 KB * 365 * 5 ≈ 18 TB (5 years).
  • Images: 100M products * 5 images * 500 KB ≈ 250 TB.

Bandwidth estimates

  • Page load: 12,000 RPS * 100 KB ≈ 1.2 GB/s.
  • Images: Significant, cần CDN.

Bước 3: Thiết kế High‑Level

Components chính

┌──────────┐     ┌─────────────┐     ┌──────────────┐
│  Client  │ ──→ │ CDN / WAF   │ ──→ │ API Gateway  │
│          │     │ (CloudFlare)│     │              │
└──────────┘     └─────────────┘     └──────────────┘
                                            │
        ┌───────────────────────────────────┼───────────────────────────────────┐
        ▼                                   ▼                                   ▼
┌───────────────┐                  ┌───────────────┐                  ┌───────────────┐
│   Product     │                  │    Cart       │                  │    Order      │
│   Service     │                  │    Service    │                  │    Service    │
└───────────────┘                  └───────────────┘                  └───────────────┘
        │                                   │                                   │
        ▼                                   ▼                                   ▼
┌───────────────┐                  ┌───────────────┐                  ┌───────────────┐
│  PostgreSQL   │                  │    Redis      │                  │  PostgreSQL   │
│  (Products)   │                  │    (Cart)     │                  │  (Orders)     │
└───────────────┘                  └───────────────┘                  └───────────────┘
        │
        ▼
┌───────────────┐
│ Elasticsearch │
│   (Search)    │
└───────────────┘

Technology selection

  • Frontend: React/Next.js với SSR.
  • API Gateway: Kong hoặc AWS API Gateway.
  • Services: Microservices (Java/Spring hoặc Node.js).
  • Database: PostgreSQL cho transactions, Redis cho cart.
  • Search: Elasticsearch cho product search.
  • Cache: Redis cho sessions, cart, popular products.
  • CDN: CloudFront cho static content, images.
  • Message Queue: Kafka cho events (order placed, inventory updated).

Bước 4: Thiết kế Chi tiết

Database Schema

Table: products

ColumnTypeDescription
product_idBIGINTPrimary key
titleVARCHAR(500)Product name
descriptionTEXTProduct description
priceDECIMAL(10,2)Current price
category_idBIGINTForeign key
inventory_countINTStock level
created_atTIMESTAMPCreated time

Table: users

ColumnTypeDescription
user_idBIGINTPrimary key
emailVARCHAR(255)Unique, indexed
password_hashVARCHAR(255)Hashed password
created_atTIMESTAMPJoin date

Table: orders

ColumnTypeDescription
order_idUUIDPrimary key
user_idBIGINTForeign key
total_amountDECIMAL(10,2)Order total
statusTINYINTPending/Paid/Shipped/Delivered
created_atTIMESTAMPOrder time
Index: (user_id, created_at)

Table: order_items

ColumnTypeDescription
order_idUUIDForeign key
product_idBIGINTForeign key
quantityINTQuantity ordered
priceDECIMAL(10,2)Price at time of order

API Design

GET /api/v1/products?category=electronics&q=laptop&page=1&limit=20

GET /api/v1/products/{id}

POST /api/v1/cart/items
{
  "product_id": 12345,
  "quantity": 2
}

GET /api/v1/cart

POST /api/v1/orders
{
  "items": [
    { "product_id": 12345, "quantity": 2 }
  ],
  "shipping_address": {...},
  "payment_method": {...}
}

POST /api/v1/payments
{
  "order_id": "uuid",
  "card_token": "tok_xxx"
}

Data Flow

Browse Products:

  1. Client request /products với filters.
  2. API Gateway → Product Service.
  3. Query Elasticsearch với filters.
  4. Return results với pagination.
  5. Cache popular searches.

Add to Cart:

  1. Client POST /cart/items.
  2. Cart Service validate product availability.
  3. Store in Redis hash: cart:{user_id}.
  4. Set TTL 30 days.
  5. Return updated cart.

Checkout:

  1. Client POST /orders.
  2. Order Service create order (PENDING).
  3. Reserve inventory (decrement count).
  4. Call Payment Service.
  5. Payment success → update order status (PAID).
  6. Publish order.placed event.
  7. Inventory Service consume event, update stock.
  8. Shipping Service consume event, prepare shipment.

Payment Processing:

  1. Payment Service call Stripe/PayPal API.
  2. Handle 3D Secure nếu cần.
  3. Store payment result.
  4. Idempotency key để tránh double charge.
  5. Webhook handling cho async payment status.

Bước 5: Bottlenecks & Tối ưu

Single Point of Failure

  • Database: PostgreSQL với streaming replication (1 master, 2 slaves).
  • Payment: Multiple payment providers (Stripe + PayPal).
  • API Gateway: Multiple instances với health checks.

Scalability Bottlenecks

  • Database write: Orders table partitioning theo created_at (monthly).
  • Search: Elasticsearch cluster với sharding.
  • Cart: Redis cluster cho horizontal scaling.
  • Inventory: Optimistic locking để tránh overselling.

Performance Optimization

  • CDN: Cache product images, static assets.
  • Database read replicas: Cho product browsing.
  • Caching:
    • Redis cho popular products, categories.
    • Application-level cache cho product details.
  • Async processing:
    • Email notifications via Kafka.
    • Recommendation updates batched.

Inventory Consistency

  • Optimistic locking: UPDATE products SET inventory = inventory - 1 WHERE id = ? AND inventory > 0.
  • Reserve timeout: Release reserved inventory sau 15 phút nếu không thanh toán.
  • Queue-based: Serialze inventory updates qua message queue.

Bước 6: Trade‑offs

Consistency vs Availability

  • CP system cho inventory và orders: Strong consistency required.
  • AP system cho product browsing: Eventual consistency acceptable.

Latency vs Throughput

  • Checkout: Low latency critical → synchronous processing.
  • Notifications: High throughput → async via Kafka.

Monolith vs Microservices

ApproachProsCons
MonolithSimple, ACID transactionsHard to scale, deployment risk
MicroservicesIndependent scaling, deploymentDistributed transactions, complexity

Database per Service vs Shared Database

  • Database per service: Isolation, independent scaling, nhưng cần saga pattern cho transactions.
  • Shared database: Easier transactions, nhưng coupling và scaling khó.

Kết luận

E-commerce platform là hệ thống phức tạp với nhiều requirements:

  • Transaction integrity: Payment và inventory phải consistent.
  • High availability: Downtime = mất revenue.
  • Traffic spikes: Black Friday, flash sales.
  • Security: PCI DSS, user data protection.
  • Personalization: Recommendations, search ranking.

← Social Media Feed | Xem tiếp: Ride‑sharing →