Chuyển đến nội dung chính

Bài 3: System Architecture Overview — Microservices, Event-Driven & DDD

High-level system architecture, bounded contexts (Design, Catalog, Order, Production, Fulfillment, Analytics), event-driven architecture, CQRS, technology stack selection, C4 diagrams.

🏗️ Kiến trúc — Bài 3 Bài 3: System Architecture Overview — Microservices, Event-Driven & DDD

Kiến trúc Hệ thống Fashion Design & Print-on-Demand — Từ Domain Analysis đến Production

Phần 1: Tổng quan Domain Fashion Design & POD

xdev.asia

1. DDD Bounded Contexts

Áp dụng Domain-Driven Design để phân tách hệ thống POD thành các bounded contexts rõ ràng.

┌──────────────────────────────────────────────────────────────────────────┐
│                    Fashion POD Platform                                  │
│                                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                   │
│  │   Design     │  │   Catalog    │  │   Commerce   │                   │
│  │   Context    │  │   Context    │  │   Context    │                   │
│  │              │  │              │  │              │                   │
│  │ • Canvas     │  │ • Product    │  │ • Cart       │                   │
│  │ • AI Gen     │  │ • SKU       │  │ • Checkout   │                   │
│  │ • Assets     │  │ • Mockup    │  │ • Payment    │                   │
│  │ • Templates  │  │ • Channel   │  │ • Pricing    │                   │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘                   │
│         │                 │                 │                            │
│         ▼                 ▼                 ▼                            │
│  ┌────────────────────────────────────────────────┐                     │
│  │              Event Bus (Kafka)                  │                     │
│  └────────────────────────────────────────────────┘                     │
│         │                 │                 │                            │
│         ▼                 ▼                 ▼                            │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                   │
│  │   Order      │  │  Production  │  │  Fulfillment │                   │
│  │   Context    │  │   Context    │  │   Context    │                   │
│  │              │  │              │  │              │                   │
│  │ • OMS       │  │ • Print Queue│  │ • Shipping   │                   │
│  │ • Saga      │  │ • Supplier   │  │ • Tracking   │                   │
│  │ • Split     │  │ • QC        │  │ • Returns    │                   │
│  │ • Timeline  │  │ • Routing   │  │ • Logistics  │                   │
│  └──────────────┘  └──────────────┘  └──────────────┘                   │
│                                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                   │
│  │  Identity &  │  │   Analytics  │  │   AI/ML      │                   │
│  │  Access      │  │   Context    │  │   Platform   │                   │
│  │              │  │              │  │              │                   │
│  │ • Auth      │  │ • Warehouse  │  │ • Feature    │                   │
│  │ • RBAC      │  │ • Dashboard  │  │   Store      │                   │
│  │ • Teams     │  │ • Reports   │  │ • Training   │                   │
│  │ • API Keys  │  │ • BI        │  │ • Serving    │                   │
│  └──────────────┘  └──────────────┘  └──────────────┘                   │
└──────────────────────────────────────────────────────────────────────────┘

2. Context Map — Relationships

UpstreamDownstreamRelationshipIntegration
DesignCatalogCustomer-SupplierDesign asset → Product image
CatalogCommercePublished LanguageProduct data → Storefront
CommerceOrderCustomer-SupplierCheckout → Order created
OrderProductionCustomer-SupplierOrder → Print job
ProductionFulfillmentCustomer-SupplierPrinted → Ship
All contextsAnalyticsConformistEvents → Data warehouse
AI/MLDesign, Catalog, ProductionOpen Host ServiceML inference API
Channel (Shopify/Etsy)Catalog, OrderAnti-corruption LayerExternal API → Internal model

3. Event-Driven Architecture

Core Domain Events

// Design Context Events
interface DesignCreatedEvent {
  type: 'design.created';
  designId: string;
  designerId: string;
  imageUrl: string;
  metadata: { width: number; height: number; dpi: number };
  timestamp: string;
}

interface DesignApprovedEvent {
  type: 'design.approved';
  designId: string;
  qcScore: number;
  ipCheckResult: 'clean' | 'flagged';
}

// Catalog Context Events
interface ProductPublishedEvent {
  type: 'product.published';
  productId: string;
  designId: string;
  channels: string[];  // ['shopify', 'etsy', 'amazon']
  variants: Array<{ sku: string; size: string; color: string; price: number }>;
}

// Order Context Events
interface OrderCreatedEvent {
  type: 'order.created';
  orderId: string;
  customerId: string;
  items: Array<{ sku: string; quantity: number; designId: string }>;
  shippingAddress: Address;
  totalAmount: number;
}

interface OrderSplitEvent {
  type: 'order.split';
  orderId: string;
  subOrders: Array<{
    subOrderId: string;
    supplierId: string;
    items: Array<{ sku: string; quantity: number }>;
  }>;
}

// Production Context Events
interface PrintJobCompletedEvent {
  type: 'print_job.completed';
  subOrderId: string;
  supplierId: string;
  qcResult: 'pass' | 'fail';
  completedAt: string;
}

// Fulfillment Context Events
interface ShipmentCreatedEvent {
  type: 'shipment.created';
  shipmentId: string;
  orderId: string;
  carrier: string;
  trackingNumber: string;
  estimatedDelivery: string;
}

Event Flow — Order Lifecycle

Commerce                    Order                     Production              Fulfillment
   │                          │                          │                       │
   │  checkout.completed      │                          │                       │
   │─────────────────────────▶│                          │                       │
   │                          │  order.created           │                       │
   │                          │─────────────────────────▶│                       │
   │                          │  order.split             │                       │
   │                          │─────────────────────────▶│                       │
   │                          │                          │  print_job.queued     │
   │                          │                          │──────────────────────▶│
   │                          │                          │  print_job.completed  │
   │                          │◀─────────────────────────│                       │
   │                          │                          │                       │
   │                          │  sub_order.ready_to_ship │                       │
   │                          │──────────────────────────────────────────────────▶│
   │                          │                          │  shipment.created     │
   │                          │◀─────────────────────────────────────────────────│
   │                          │  order.shipped           │                       │
   │                          │──▶ (notify customer)     │                       │

4. CQRS Pattern

// Command Side — Write path
interface CreateProductCommand {
  designId: string;
  baseProductIds: string[];
  pricing: PricingConfig;
  publishTo: string[];
}

// Query Side — Read path (denormalized for performance)
interface ProductReadModel {
  id: string;
  title: string;
  designThumbnail: string;
  mockupImages: string[];
  variants: Array<{
    sku: string;
    size: string;
    color: string;
    price: number;
    inStock: boolean;
  }>;
  rating: number;
  reviewCount: number;
  salesCount: number;
  // Denormalized — no JOINs needed
}

5. Technology Stack

LayerTechnologyLý do
API GatewayKong / AWS API GatewayRate limiting, auth, routing
Backend ServicesNode.js (NestJS) / GoHigh throughput, TypeScript ecosystem
AI/ML ServicesPython (FastAPI)ML ecosystem, GPU inference
FrontendNext.js / ReactSSR for SEO, design studio SPA
Event BusApache KafkaHigh throughput, event sourcing
Primary DBPostgreSQLACID, JSONB, full-text search
CacheRedis ClusterSession, product cache, rate limiting
SearchElasticsearch / MeilisearchProduct search, faceting
Object StorageS3 / MinIODesign files, mockups, print files
CDNCloudFront / CloudflareImage delivery, edge caching
Task QueueBullMQ (Redis)Image processing, email, sync
GPU InferenceNVIDIA Triton / vLLMAI design generation, CLIP
OrchestrationKubernetes (EKS/GKE)Auto-scaling, multi-region
MonitoringPrometheus + GrafanaMetrics, alerting, dashboards
Data WarehouseClickHouse / BigQueryAnalytics, reporting

6. High-Level Architecture Diagram

                          ┌─────────────┐
                          │   CDN Edge   │
                          │ (Cloudflare) │
                          └──────┬───────┘
                                 │
                          ┌──────▼───────┐
                          │ API Gateway  │
                          │ (Kong)       │
                          └──────┬───────┘
                                 │
              ┌──────────────────┼──────────────────┐
              ▼                  ▼                  ▼
     ┌────────────────┐ ┌───────────────┐ ┌────────────────┐
     │ Design Service │ │Catalog Service│ │Commerce Service│
     │ (NestJS)       │ │ (NestJS)      │ │ (NestJS)       │
     └───────┬────────┘ └───────┬───────┘ └───────┬────────┘
             │                  │                  │
             ▼                  ▼                  ▼
     ┌────────────────────────────────────────────────────┐
     │                  Kafka Cluster                      │
     └────────────────────────┬───────────────────────────┘
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
     ┌────────────────┐ ┌──────────────┐ ┌────────────────┐
     │ Order Service  │ │ Production   │ │ Fulfillment    │
     │ (NestJS)       │ │ Service (Go) │ │ Service (NestJS│
     └───────┬────────┘ └──────┬───────┘ └───────┬────────┘
             │                 │                  │
             ▼                 ▼                  ▼
     ┌──────────────┐  ┌──────────────┐  ┌──────────────┐
     │ PostgreSQL   │  │ PostgreSQL   │  │ PostgreSQL   │
     │ (Orders)     │  │ (Production) │  │ (Shipping)   │
     └──────────────┘  └──────────────┘  └──────────────┘

     ┌────────────────┐ ┌──────────────┐ ┌────────────────┐
     │ AI/ML Service  │ │ Analytics    │ │ Channel Sync   │
     │ (FastAPI+GPU)  │ │ (ClickHouse) │ │ (Workers)      │
     └────────────────┘ └──────────────┘ └────────────────┘

7. Data Flow Patterns

FlowPatternLatency
Design → MockupSync (real-time preview)< 2s
Design → QC/IP CheckAsync (queue)5-30s
Product → Channel SyncAsync (event → worker)1-5 min
Order → ProductionAsync (saga orchestrator)seconds
Production → QCSync (inline)< 5s
All → AnalyticsAsync (CDC → Kafka → DW)1-5 min
Product SearchCQRS read model< 100ms

8. Tổng kết

  • 9 Bounded Contexts — Design, Catalog, Commerce, Order, Production, Fulfillment, Identity, Analytics, AI/ML

  • Event-Driven — Kafka event bus, domain events cho loose coupling

  • CQRS — Tách read/write cho performance (product catalog, search)

  • Saga Pattern — Distributed transactions cho order lifecycle

  • Tech Stack — NestJS + Go + FastAPI + PostgreSQL + Kafka + Redis + K8s