# System Design / Thiết kế Hệ thống

> **EN**: Comprehensive system architecture for the GoodGo Microservices Platform
> **VI**: Kiến trúc hệ thống toàn diện cho GoodGo Microservices Platform

## System Overview / Tổng quan Hệ thống

```mermaid
graph TD
    subgraph "Client Layer / Tầng Client"
        WebApp[Web Application<br/>Next.js 14+]
        MobileApp[Mobile Application<br/>Flutter/React Native]
    end
    
    subgraph "API Gateway Layer / Tầng API Gateway"
        Traefik[Traefik Gateway<br/>Load Balancer + Routing]
    end
    
    subgraph "Services Layer / Tầng Services"
        IAM[IAM Service<br/>Authentication & Authorization]
        Template[Template Service<br/>Example Microservice]
        Future1[Future Service 1<br/>TBD]
        Future2[Future Service 2<br/>TBD]
    end
    
    subgraph "Data Layer / Tầng Dữ liệu"
        PostgreSQL[(PostgreSQL 14+<br/>Primary Database)]
        Redis[(Redis 6+<br/>Cache & Sessions)]
    end
    
    subgraph "Observability / Khả năng quan sát"
        Prometheus[Prometheus<br/>Metrics Collection]
        Grafana[Grafana<br/>Metrics Visualization]
        Loki[Loki<br/>Log Aggregation]
        Jaeger[Jaeger<br/>Distributed Tracing]
    end
    
    WebApp --> Traefik
    MobileApp --> Traefik
    
    Traefik --> IAM
    Traefik --> Template
    Traefik --> Future1
    Traefik --> Future2
    
    IAM --> PostgreSQL
    Template --> PostgreSQL
    Future1 --> PostgreSQL
    Future2 --> PostgreSQL
    
    IAM --> Redis
    Template --> Redis
    Future1 --> Redis
    Future2 --> Redis
    
    IAM -.->|Metrics| Prometheus
    Template -.->|Metrics| Prometheus
    Prometheus --> Grafana
    
    IAM -.->|Logs| Loki
    Template -.->|Logs| Loki
    
    IAM -.->|Traces| Jaeger
    Template -.->|Traces| Jaeger
    
    style Traefik fill:#e1f5ff
    style PostgreSQL fill:#f0e1ff
    style Redis fill:#fff4e1
    style Prometheus fill:#d4edda
```

### EN: Architecture Principles

The GoodGo Microservices Platform follows these core principles:

1. **Service Independence**: Each microservice:
   - Has its own database schema (database per service pattern)
   - Can be deployed independently without affecting others
   - Owns its data and exposes APIs for data access
   - Uses standardized communication patterns

2. **API Gateway Pattern**: Traefik provides:
   - Single entry point for all client requests
   - Path-based routing to appropriate services
   - Load balancing across service instances
   - SSL/TLS termination
   - Rate limiting and security headers

3. **Shared Infrastructure**: Common concerns handled by:
   - Shared packages (@goodgo/logger, @goodgo/types, @goodgo/http-client)
   - Centralized observability stack
   - Distributed caching layer (Redis)
   - Common monitoring and alerting

4. **Infrastructure as Code**: All configurations versioned:
   - Docker Compose for local development
   - Kubernetes manifests for production
   - Traefik dynamic configuration
   - Database migrations with Prisma

5. **Observability First**: Built-in monitoring:
   - Prometheus metrics from all services
   - Structured logging with correlation IDs
   - Distributed tracing with OpenTelemetry
   - Health check endpoints (liveness/readiness)

### VI: Nguyên tắc Kiến trúc

GoodGo Microservices Platform tuân theo các nguyên tắc cốt lõi sau:

1. **Độc lập Service**: Mỗi microservice:
   - Có schema database riêng (pattern database per service)
   - Có thể deploy độc lập mà không ảnh hưởng đến các service khác
   - Sở hữu dữ liệu của mình và expose APIs để truy cập dữ liệu
   - Sử dụng patterns giao tiếp chuẩn hóa

2. **Pattern API Gateway**: Traefik cung cấp:
   - Điểm vào duy nhất cho tất cả client requests
   - Routing dựa trên path tới các service phù hợp
   - Load balancing giữa các service instances
   - SSL/TLS termination
   - Rate limiting và security headers

3. **Infrastructure Chia sẻ**: Các concerns chung được xử lý bởi:
   - Shared packages (@goodgo/logger, @goodgo/types, @goodgo/http-client)
   - Stack observability tập trung
   - Tầng caching phân tán (Redis)
   - Monitoring và alerting chung

4. **Infrastructure as Code**: Tất cả cấu hình được version:
   - Docker Compose cho local development
   - Kubernetes manifests cho production
   - Traefik dynamic configuration
   - Database migrations với Prisma

5. **Observability First**: Monitoring tích hợp sẵn:
   - Prometheus metrics từ tất cả services
   - Structured logging với correlation IDs
   - Distributed tracing với OpenTelemetry
   - Health check endpoints (liveness/readiness)

---

## Detailed Component Architecture / Kiến trúc Component Chi tiết

### 1. Client Layer / Tầng Client

```mermaid
graph LR
    User((User)) --> WebBrowser[Web Browser]
    User --> MobileDevice[Mobile Device]
    
    WebBrowser --> NextJS[Next.js App<br/>Port 3000]
    MobileDevice --> Flutter[Flutter App<br/>iOS/Android]
    
    NextJS --> APIClient[@goodgo/http-client]
    Flutter --> HTTPPackage[HTTP Package]
    
    APIClient --> Gateway[API Gateway<br/>localhost or api.goodgo.com]
    HTTPPackage --> Gateway
    
    style User fill:#e1f5ff
    style Gateway fill:#d4edda
```

**EN Components**:
- **Web Application**: Next.js 14+ with App Router
  - Server-side rendering (SSR)
  - Static site generation (SSG)
  - API routes for BFF pattern
  - Uses `@goodgo/http-client` for API calls
  
- **Mobile Application**: Flutter or React Native
  - Cross-platform (iOS + Android)
  - Offline-first architecture (future)
  - Native HTTP client

**VI Thành phần**:
- **Web Application**: Next.js 14+ với App Router
  - Server-side rendering (SSR)
  - Static site generation (SSG)
  - API routes cho BFF pattern
  - Sử dụng `@goodgo/http-client` cho API calls

- **Mobile Application**: Flutter hoặc React Native
  - Cross-platform (iOS + Android)
  - Kiến trúc offline-first (tương lai)
  - Native HTTP client

---

### 2. API Gateway Layer / Tầng API Gateway

```mermaid
graph TD
    Client[Client Request] --> Traefik
    
    subgraph "Traefik API Gateway"
        Traefik[Traefik Router] --> Middlewares
        
        subgraph Middlewares
            M1[CORS]
            M2[Rate Limiting]
            M3[Headers]
            M4[Compression]
        end
        
        Middlewares --> Router[Dynamic Router]
        Router --> LB[Load Balancer]
    end
    
    LB --> Service1[Service Instance 1]
    LB --> Service2[Service Instance 2]
    LB --> Service3[Service Instance 3]
    
    style Traefik fill:#e1f5ff
    style Router fill:#fff4e1
    style LB fill:#d4edda
```

**EN: Traefik Configuration**

**Static Configuration** (`infra/traefik/traefik.yml`):
- Entry points (HTTP: 80, HTTPS: 443)
- Docker provider for service discovery
- Certificate resolvers (Let's Encrypt)
- Dashboard configuration (port 8080)

**Dynamic Configuration** (`infra/traefik/dynamic/`):
- Middlewares (CORS, rate limiting, security headers)
- Routes (defined via Docker labels or YAML files)
- Services (load balancing strategies)

**Routing Pattern**:
```yaml
http:
  routers:
    iam-service:
      rule: "PathPrefix(`/api/v1/auth`)"
      service: iam-service
      middlewares:
        - cors
        - rate-limit
        - secure-headers
```

**Service Discovery**: Automatic via Docker labels:
```yaml
labels:
  - "traefik.enable=true"
  - "traefik.http.routers.iam.rule=PathPrefix(`/api/v1/auth`)"
  - "traefik.http.services.iam.loadbalancer.server.port=3001"
  - "traefik.http.services.iam.loadbalancer.healthcheck.path=/health/live"
```

**VI: Cấu hình Traefik**

**Cấu hình Tĩnh** (`infra/traefik/traefik.yml`):
- Entry points (HTTP: 80, HTTPS: 443)
- Docker provider cho service discovery
- Certificate resolvers (Let's Encrypt)
- Cấu hình dashboard (port 8080)

**Cấu hình Động** (`infra/traefik/dynamic/`):
- Middlewares (CORS, rate limiting, security headers)
- Routes (định nghĩa qua Docker labels hoặc YAML files)
- Services (chiến lược load balancing)

**Pattern Routing**:
```yaml
http:
  routers:
    iam-service:
      rule: "PathPrefix(`/api/v1/auth`)"
      service: iam-service
      middlewares:
        - cors
        - rate-limit
        - secure-headers
```

**Service Discovery**: Tự động qua Docker labels:
```yaml
labels:
  - "traefik.enable=true"
  - "traefik.http.routers.iam.rule=PathPrefix(`/api/v1/auth`)"
  - "traefik.http.services.iam.loadbalancer.server.port=3001"
  - "traefik.http.services.iam.loadbalancer.healthcheck.path=/health/live"
```

---

### 3. Services Layer / Tầng Services

#### Microservice Template Structure / Cấu trúc Template Microservice

```mermaid
graph TD
    subgraph "Microservice (Template Pattern)"
        HTTP[HTTP Request] --> MW[Middleware Stack]
        
        MW --> Routes[Routes]
        
        subgraph "Feature Module"
            Routes --> Controller
            Controller --> Service
            Service --> Repository
            Repository --> Prisma[Prisma ORM]
        end
        
        Service --> Cache[Cache Service]
        Cache --> Redis[(Redis)]
        
        Prisma --> DB[(PostgreSQL)]
        
        MW --> Metrics[Metrics Middleware]
        Metrics --> Prom[Prometheus]
    end
    
    style MW fill:#e1f5ff
    style Service fill:#f0e1ff
    style Cache fill:#fff4e1
```

**EN: Standard Microservice Structure**

Each microservice follows this pattern (from `services/_template/`):

```
src/
├── config/              # Configuration with Zod validation
│   ├── app.config.ts
│   ├── database.config.ts
│   └── redis.config.ts
├── core/                # Core utilities (IAM service only)
│   ├── cache/           # Multi-layer caching
│   ├── events/          # Event sourcing
│   └── security/        # Zero-trust validator
├── middlewares/         # Express middlewares
│   ├── correlation.middleware.ts
│   ├── logger.middleware.ts
│   ├── metrics.middleware.ts
│   └── error.middleware.ts
├── modules/             # Feature modules
│   ├── common/          # Shared (BaseRepository)
│   ├── feature/         # Example feature
│   ├── health/          # Health checks
│   └── metrics/         # Prometheus metrics
├── routes/              # Route definitions
│   └── index.ts
└── main.ts              # Application entry point
```

**Middleware Execution Order**:
1. Correlation ID → 2. Logger → 3. Metrics → 4. CORS → 5. Rate Limit → 6. Body Parser → 7. Routes → 8. Error Handler

**VI: Cấu trúc Microservice Chuẩn**

Mỗi microservice tuân theo pattern này (từ `services/_template/`):

```
src/
├── config/              # Configuration với Zod validation
│   ├── app.config.ts
│   ├── database.config.ts
│   └── redis.config.ts
├── core/                # Core utilities (chỉ IAM service)
│   ├── cache/           # Multi-layer caching
│   ├── events/          # Event sourcing
│   └── security/        # Zero-trust validator
├── middlewares/         # Express middlewares
│   ├── correlation.middleware.ts
│   ├── logger.middleware.ts
│   ├── metrics.middleware.ts
│   └── error.middleware.ts
├── modules/             # Feature modules
│   ├── common/          # Shared (BaseRepository)
│   ├── feature/         # Example feature
│   ├── health/          # Health checks
│   └── metrics/         # Prometheus metrics
├── routes/              # Route definitions
│   └── index.ts
└── main.ts              # Application entry point
```

**Thứ tự Thực thi Middleware**:
1. Correlation ID → 2. Logger → 3. Metrics → 4. CORS → 5. Rate Limit → 6. Body Parser → 7. Routes → 8. Error Handler

---

### 4. Data Layer / Tầng Dữ liệu

#### Database Architecture / Kiến trúc Database

```mermaid
graph TD
    subgraph "Database Per Service Pattern"
        Service1[IAM Service] --> Schema1[(iam_db<br/>30+ tables)]
        Service2[Template Service] --> Schema2[(template_db<br/>Example tables)]
        Service3[Future Service] --> Schema3[(future_db<br/>TBD)]
    end
    
    subgraph "Shared Infrastructure"
        Schema1 -.->|Connection Pool| PG[PostgreSQL 14+<br/>Neon Cloud]
        Schema2 -.->|Connection Pool| PG
        Schema3 -.->|Connection Pool| PG
    end
    
    subgraph "Cache Layer"
        Service1 --> L1_1[L1: Memory<br/>60s TTL]
        Service2 --> L1_2[L1: Memory<br/>60s TTL]
        
        L1_1 --> L2[L2: Redis<br/>5-15min TTL]
        L1_2 --> L2
        
        L2 -.->|Cache Miss| Schema1
        L2 -.->|Cache Miss| Schema2
    end
    
    style PG fill:#f0e1ff
    style L2 fill:#fff4e1
    style L1_1 fill:#d4edda
    style L1_2 fill:#d4edda
```

**EN: Data Management**

**Database per Service**:
- Each service has its own database schema
- Services own their data exclusively
- Cross-service data access via APIs only
- Independent scaling and optimization

**Multi-Layer Caching** (IAM Service):
```
Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (Database)
```

**Cache Hit Rates**:
- L1: ~40-50% (hot data)
- L2: ~80-90% (permissions, user data)
- L3: 10-20% (cache miss, fetch from DB)

**Database Technology**:
- **Provider**: Neon (Serverless PostgreSQL)
- **Version**: PostgreSQL 14+
- **ORM**: Prisma
- **Connection Pooling**: Prisma (10 connections default)
- **Migrations**: Prisma Migrate

**VI: Quản lý Dữ liệu**

**Database per Service**:
- Mỗi service có schema database riêng
- Services sở hữu dữ liệu độc quyền
- Truy cập dữ liệu cross-service chỉ qua APIs
- Scaling và optimization độc lập

**Multi-Layer Caching** (IAM Service):
```
Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (Database)
```

**Tỷ lệ Cache Hit**:
- L1: ~40-50% (hot data)
- L2: ~80-90% (permissions, user data)
- L3: 10-20% (cache miss, fetch từ DB)

**Công nghệ Database**:
- **Provider**: Neon (Serverless PostgreSQL)
- **Version**: PostgreSQL 14+
- **ORM**: Prisma
- **Connection Pooling**: Prisma (10 connections mặc định)
- **Migrations**: Prisma Migrate

---

## Communication Patterns / Patterns Giao tiếp

### Request Flow / Luồng Request

```mermaid
sequenceDiagram
    participant Client
    participant Traefik as Traefik Gateway
    participant Service
    participant Cache as Redis Cache
    participant DB as PostgreSQL
    
    Client->>Traefik: HTTP Request
    Traefik->>Traefik: Apply Middlewares<br/>(CORS, Rate Limit)
    Traefik->>Service: Forward Request
    Service->>Cache: Check Cache
    
    alt Cache Hit
        Cache-->>Service: Cached Data
        Service-->>Traefik: Response (from cache)
    else Cache Miss
        Cache-->>Service: null
        Service->>DB: Query Database
        DB-->>Service: Data
        Service->>Cache: Store in Cache
        Service-->>Traefik: Response (from DB)
    end
    
    Traefik-->>Client: HTTP Response
```

**EN: Communication Patterns**

1. **Synchronous (HTTP/REST)**:
   - Request-response pattern
   - RESTful API design
   - JSON payload format
   - Standard HTTP status codes

2. **Service-to-Service**:
   - Internal HTTP calls via `@goodgo/http-client`
   - Service authentication with internal API keys
   - Circuit breaker pattern for resilience
   - Correlation ID propagation

3. **Service Discovery**:
   - **Local**: Docker DNS (`http://service-name:port`)
   - **Kubernetes**: Service DNS (`http://service-name.namespace.svc.cluster.local`)
   - **Traefik**: Dynamic configuration via labels

4. **Asynchronous (Future)**:
   - Message queues (RabbitMQ/Kafka)
   - Event-driven architecture
   - Pub/Sub patterns

**VI: Patterns Giao tiếp**

1. **Đồng bộ (HTTP/REST)**:
   - Pattern request-response
   - Thiết kế RESTful API
   - Format payload JSON
   - HTTP status codes chuẩn

2. **Service-to-Service**:
   - Internal HTTP calls qua `@goodgo/http-client`
   - Service authentication với internal API keys
   - Circuit breaker pattern cho resilience
   - Correlation ID propagation

3. **Service Discovery**:
   - **Local**: Docker DNS (`http://service-name:port`)
   - **Kubernetes**: Service DNS (`http://service-name.namespace.svc.cluster.local`)
   - **Traefik**: Dynamic configuration qua labels

4. **Bất đồng bộ (Tương lai)**:
   - Message queues (RabbitMQ/Kafka)
   - Event-driven architecture
   - Pub/Sub patterns

---

## Security Architecture / Kiến trúc Bảo mật

```mermaid
graph TD
    Request[Client Request] --> TLS[TLS/HTTPS]
    TLS --> RateLimit[Rate Limiting]
    RateLimit --> JWT[JWT Validation]
    JWT --> RBAC[RBAC Authorization]
    RBAC --> ZeroTrust[Zero-Trust Validation]
    ZeroTrust --> Service[Service Logic]
    
    Service --> Encrypt[Data Encryption<br/>AES-256-GCM]
    Encrypt --> DB[(Encrypted Data<br/>at Rest)]
    
    Service --> Audit[Audit Logging<br/>Event Sourcing]
    Audit --> AuditDB[(Audit Trail<br/>7-year retention)]
    
    style TLS fill:#d4edda
    style JWT fill:#e1f5ff
    style Encrypt fill:#f8d7da
    style Audit fill:#fff4e1
```

**EN: Security Layers**

1. **Network Security**:
   - TLS 1.2+ for all communications
   - HTTPS enforcement
   - CORS configuration
   - Rate limiting (Redis-backed, distributed)

2. **Authentication**:
   - JWT tokens (15min access, 7 days refresh)
   - bcrypt password hashing (cost 12)
   - Refresh token rotation
   - Multi-factor authentication (TOTP)

3. **Authorization**:
   - Role-Based Access Control (RBAC)
   - Attribute-Based Access Control (ABAC)
   - Permission model: `resource:action:scope`
   - Permission caching (5min TTL)

4. **Data Protection**:
   - AES-256-GCM encryption for PII
   - Token hashing (SHA-256)
   - Secrets management (environment variables, K8s secrets)

5. **Zero-Trust**:
   - Device fingerprinting
   - IP address validation
   - Behavioral analysis
   - Session binding

6. **Audit & Compliance**:
   - Event sourcing for all auth events
   - 7-year retention (GDPR, SOC2)
   - Correlation ID tracking
   - Compliance reporting (GDPR, SOC2, ISO27001, HIPAA)

**VI: Các Tầng Bảo mật**

1. **Network Security**:
   - TLS 1.2+ cho mọi giao tiếp
   - HTTPS enforcement
   - Cấu hình CORS
   - Rate limiting (Redis-backed, phân tán)

2. **Authentication**:
   - JWT tokens (15min access, 7 ngày refresh)
   - bcrypt password hashing (cost 12)
   - Refresh token rotation
   - Multi-factor authentication (TOTP)

3. **Authorization**:
   - Role-Based Access Control (RBAC)
   - Attribute-Based Access Control (ABAC)
   - Permission model: `resource:action:scope`
   - Permission caching (5min TTL)

4. **Data Protection**:
   - AES-256-GCM encryption cho PII
   - Token hashing (SHA-256)
   - Secrets management (environment variables, K8s secrets)

5. **Zero-Trust**:
   - Device fingerprinting
   - IP address validation
   - Behavioral analysis
   - Session binding

6. **Audit & Compliance**:
   - Event sourcing cho tất cả auth events
   - 7-year retention (GDPR, SOC2)
   - Correlation ID tracking
   - Compliance reporting (GDPR, SOC2, ISO27001, HIPAA)

---

## Observability Stack / Stack Khả năng quan sát

```mermaid
graph LR
    subgraph "Services"
        S1[IAM Service]
        S2[Template Service]
    end
    
    subgraph "Metrics"
        S1 -->|/metrics| Prom[Prometheus]
        S2 -->|/metrics| Prom
        Prom --> Grafana[Grafana Dashboard]
    end
    
    subgraph "Logging"
        S1 -->|JSON Logs| Loki[Loki]
        S2 -->|JSON Logs| Loki
        Loki --> GrafanaLog[Grafana Explore]
    end
    
    subgraph "Tracing"
        S1 -->|Spans| Jaeger[Jaeger]
        S2 -->|Spans| Jaeger
        Jaeger --> JaegerUI[Jaeger UI]
    end
    
    style Prom fill:#d4edda
    style Loki fill:#fff4e1
    style Jaeger fill:#e1f5ff
```

**EN: Three Pillars of Observability**

1. **Metrics (Prometheus)**:
   - HTTP request duration (histogram)
   - HTTP request count (counter)
   - Active requests (gauge)
   - Cache hit/miss ratio
   - Database query duration
   - Custom business metrics

2. **Logging (Winston + Loki)**:
   - Structured JSON logs
   - Correlation IDs in every log
   - Request/response logging
   - Error stack traces (dev only)
   - Log levels: error, warn, info, debug

3. **Tracing (OpenTelemetry + Jaeger)**:
   - Distributed tracing across services
   - HTTP request spans
   - Database query spans
   - Cache operation spans
   - End-to-end latency tracking

**Health Checks**:
- `/health` - Overall health status
- `/health/live` - Liveness probe (K8s)
- `/health/ready` - Readiness probe (K8s, checks DB + Redis)

**VI: Ba Trụ cột của Khả năng quan sát**

1. **Metrics (Prometheus)**:
   - HTTP request duration (histogram)
   - HTTP request count (counter)
   - Active requests (gauge)
   - Cache hit/miss ratio
   - Database query duration
   - Custom business metrics

2. **Logging (Winston + Loki)**:
   - Structured JSON logs
   - Correlation IDs trong mọi log
   - Request/response logging
   - Error stack traces (chỉ dev)
   - Log levels: error, warn, info, debug

3. **Tracing (OpenTelemetry + Jaeger)**:
   - Distributed tracing giữa các services
   - HTTP request spans
   - Database query spans
   - Cache operation spans
   - End-to-end latency tracking

**Health Checks**:
- `/health` - Overall health status
- `/health/live` - Liveness probe (K8s)
- `/health/ready` - Readiness probe (K8s, kiểm tra DB + Redis)

---

## Deployment Architecture / Kiến trúc Triển khai

### Local Development / Phát triển Local

```mermaid
graph TD
    subgraph "Docker Compose (deployments/local)"
        Traefik[Traefik<br/>Port 80, 8080]
        IAM[IAM Service<br/>Port 3001]
        Template[Template Service<br/>Port 5000]
        PostgreSQL[PostgreSQL<br/>Port 5432]
        Redis[Redis<br/>Port 6379]
        
        Traefik --> IAM
        Traefik --> Template
        IAM --> PostgreSQL
        IAM --> Redis
        Template --> PostgreSQL
        Template --> Redis
    end
    
    Dev[Developer] -->|localhost| Traefik
    Dev -->|:8080| TraefikDash[Traefik Dashboard]
    
    style Traefik fill:#e1f5ff
    style PostgreSQL fill:#f0e1ff
    style Redis fill:#fff4e1
```

### Production Deployment / Triển khai Production

```mermaid
graph TD
    subgraph "Kubernetes Cluster"
        Ingress[Ingress Controller<br/>Traefik]
        
        subgraph "IAM Service"
            IAM1[IAM Pod 1]
            IAM2[IAM Pod 2]
            IAM3[IAM Pod 3]
        end
        
        subgraph "Template Service"
            T1[Template Pod 1]
            T2[Template Pod 2]
        end
        
        Ingress --> IAM1
        Ingress --> IAM2
        Ingress --> IAM3
        Ingress --> T1
        Ingress --> T2
    end
    
    subgraph "Managed Services"
        Neon[(Neon PostgreSQL<br/>Serverless)]
        RedisCloud[(Redis Cloud)]
    end
    
    IAM1 --> Neon
    IAM2 --> Neon
    IAM3 --> Neon
    T1 --> Neon
    T2 --> Neon
    
    IAM1 --> RedisCloud
    IAM2 --> RedisCloud
    T1 --> RedisCloud
    T2 --> RedisCloud
    
    style Ingress fill:#e1f5ff
    style Neon fill:#f0e1ff
    style RedisCloud fill:#fff4e1
```

**EN: Deployment Environments**

1. **Local (Docker Compose)**:
   - All services run in Docker containers
   - Shared network for service communication
   - Local PostgreSQL and Redis
   - Traefik for routing
   - Hot reload for development

2. **Staging (Kubernetes)**:
   - Kubernetes cluster in cloud (GKE/EKS/AKS)
   - 2 replicas per service
   - Managed PostgreSQL (Neon)
   - Managed Redis (Redis Cloud)
   - Horizontal Pod Autoscaling (HPA)

3. **Production (Kubernetes)**:
   - Production K8s cluster
   - 3+ replicas per service
   - Managed databases with backups
   - Auto-scaling (HPA + VPA)
   - Blue-green deployments
   - Rolling updates with health checks

**VI: Môi trường Triển khai**

1. **Local (Docker Compose)**:
   - Tất cả services chạy trong Docker containers
   - Shared network cho service communication
   - Local PostgreSQL và Redis
   - Traefik cho routing
   - Hot reload cho development

2. **Staging (Kubernetes)**:
   - Kubernetes cluster trên cloud (GKE/EKS/AKS)
   - 2 replicas mỗi service
   - Managed PostgreSQL (Neon)
   - Managed Redis (Redis Cloud)
   - Horizontal Pod Autoscaling (HPA)

3. **Production (Kubernetes)**:
   - Production K8s cluster
   - 3+ replicas mỗi service
   - Managed databases với backups
   - Auto-scaling (HPA + VPA)
   - Blue-green deployments
   - Rolling updates với health checks

---

## Performance Characteristics / Đặc điểm Hiệu suất

**EN: Performance Targets**

| Metric | Target | Notes |
|--------|--------|-------|
| **API Response Time (P95)** | < 100ms | Excluding cold starts |
| **API Response Time (P99)** | < 200ms | |
| **Throughput** | 1000 req/s | Per service instance |
| **Cache Hit Rate** | > 80% | Redis cache |
| **Database Query Time (P95)** | < 50ms | Simple queries |
| **Memory Usage** | < 512MB | Per service instance |
| **CPU Usage** | < 60% | Under normal load |

**Optimization Strategies**:
- Multi-layer caching (L1: Memory, L2: Redis)
- Database connection pooling
- Query optimization with indexes
- Horizontal scaling with HPA
- CDN for static assets

**VI: Mục tiêu Hiệu suất**

| Metric | Mục tiêu | Ghi chú |
|--------|----------|---------|
| **API Response Time (P95)** | < 100ms | Không bao gồm cold starts |
| **API Response Time (P99)** | < 200ms | |
| **Throughput** | 1000 req/s | Mỗi service instance |
| **Cache Hit Rate** | > 80% | Redis cache |
| **Database Query Time (P95)** | < 50ms | Queries đơn giản |
| **Memory Usage** | < 512MB | Mỗi service instance |
| **CPU Usage** | < 60% | Ở normal load |

**Chiến lược Tối ưu**:
- Multi-layer caching (L1: Memory, L2: Redis)
- Database connection pooling
- Query optimization với indexes
- Horizontal scaling với HPA
- CDN cho static assets

---

## Related Documentation / Tài liệu Liên quan

- [Service Communication](./service-communication.md) - EN: Detailed inter-service communication patterns / VI: Patterns giao tiếp giữa services chi tiết
- [IAM Proposal](./iam-proposal.md) - EN: IAM service architecture and features / VI: Kiến trúc và tính năng IAM service
- [Deployment Guide](../guides/deployment.md) - EN: Step-by-step deployment instructions / VI: Hướng dẫn triển khai từng bước
- [Local Development](../guides/local-development.md) - EN: Setting up local environment / VI: Thiết lập môi trường local
- [Project Rules](../skills/project-rules.md) - EN: Project structure and conventions / VI: Cấu trúc dự án và quy ước

---

**Last Updated / Cập nhật lần cuối**: 2026-01-06  
**Authors / Tác giả**: DevOps Team  
**Reviewers / Người review**: Architecture Team
