# API Gateway Nâng Cao (API Gateway Advanced)

Advanced API Gateway patterns for GoodGo microservices including API composition, request/response transformation, service mesh integration, advanced routing, and gateway-level resilience.
> Các patterns API Gateway nâng cao cho GoodGo microservices bao gồm API composition, request/response transformation, tích hợp service mesh, routing nâng cao, và resilience ở gateway level.

## Tổng Quan

Advanced API Gateway patterns extend basic gateway functionality with composition, transformation, service mesh integration, and gateway-level resilience patterns.

Các patterns API Gateway nâng cao mở rộng chức năng gateway cơ bản với composition, transformation, tích hợp service mesh, và các resilience patterns ở gateway level.

## Khi Nào Sử Dụng

Use this skill when implementing API composition, request/response transformation, or service mesh integration.

Sử dụng skill này khi implement API composition, request/response transformation, hoặc tích hợp service mesh.

## API Gateway Architecture / Kiến Trúc API Gateway

The API Gateway serves as the single entry point for all client requests, handling routing, composition, transformation, and resilience patterns.

API Gateway hoạt động như điểm vào duy nhất cho tất cả client requests, xử lý routing, composition, transformation, và các resilience patterns.

```mermaid
graph TB
    Client[Client Application] --> Gateway[API Gateway]
    
    subgraph Gateway["API Gateway Components"]
        Router[Request Router]
        Auth[Authentication/Authorization]
        RateLimit[Rate Limiting]
        CircuitBreaker[Circuit Breaker]
        Cache[Gateway Cache]
        Transformer[Request/Response Transformer]
        Composition[API Composition Engine]
    end
    
    Gateway --> Router
    Router --> Auth
    Auth --> RateLimit
    RateLimit --> CircuitBreaker
    CircuitBreaker --> Cache
    Cache --> Transformer
    Transformer --> Composition
    
    Composition --> Service1[User Service]
    Composition --> Service2[Order Service]
    Composition --> Service3[Payment Service]
    Composition --> Service4[Other Services]
    
    CircuitBreaker -.-> Service1
    CircuitBreaker -.-> Service2
    CircuitBreaker -.-> Service3
    CircuitBreaker -.-> Service4
    
    Cache --> Redis[(Redis Cache)]
    
    style Gateway fill:#e1f5ff
    style Composition fill:#fff4e1
    style CircuitBreaker fill:#ffe1e1
```

## Request Routing Flow / Luồng Request Routing

Requests flow through the gateway middleware chain in a specific order, ensuring proper handling at each stage.

Requests đi qua chuỗi middleware của gateway theo thứ tự cụ thể, đảm bảo xử lý đúng ở mỗi giai đoạn.

```mermaid
sequenceDiagram
    participant Client
    participant Gateway
    participant RateLimit
    participant Auth
    participant CircuitBreaker
    participant Cache
    participant Transformer
    participant Service
    
    Client->>Gateway: HTTP Request
    Gateway->>RateLimit: Check Rate Limit
    RateLimit-->>Gateway: Allowed
    
    Gateway->>Auth: Validate Token
    Auth-->>Gateway: Authenticated
    
    Gateway->>CircuitBreaker: Check Circuit State
    alt Circuit Open
        CircuitBreaker-->>Gateway: Service Unavailable
        Gateway-->>Client: 503 Error
    else Circuit Closed/Half-Open
        Gateway->>Cache: Check Cache
        alt Cache Hit
            Cache-->>Gateway: Cached Response
            Gateway->>Transformer: Transform Response
            Transformer-->>Gateway: Transformed
            Gateway-->>Client: Response
        else Cache Miss
            Gateway->>Transformer: Transform Request
            Transformer-->>Gateway: Transformed
            Gateway->>Service: Forward Request
            Service-->>Gateway: Response
            Gateway->>Cache: Store in Cache
            Gateway->>Transformer: Transform Response
            Transformer-->>Gateway: Transformed
            Gateway-->>Client: Response
        end
    end
```

## API Composition Patterns / Các Patterns API Composition

API composition enables the gateway to aggregate data from multiple services, reducing client round trips and improving performance.

API composition cho phép gateway tổng hợp dữ liệu từ nhiều services, giảm số lần round trip của client và cải thiện hiệu suất.

### Fan-Out / Fan-In Pattern (Parallel Aggregation) / Pattern Fan-Out / Fan-In (Tổng Hợp Song Song)

```mermaid
graph LR
    Client[Client Request] --> Gateway[API Gateway]
    
    subgraph Gateway["API Composition"]
        Comp[Composition Handler]
    end
    
    Gateway --> Comp
    
    Comp -->|Parallel Calls| S1[User Service]
    Comp -->|Parallel Calls| S2[Order Service]
    Comp -->|Parallel Calls| S3[Payment Service]
    
    S1 -->|Response| Comp
    S2 -->|Response| Comp
    S3 -->|Response| Comp
    
    Comp -->|Aggregated Response| Client
    
    style Comp fill:#fff4e1
    style S1 fill:#e1ffe1
    style S2 fill:#e1ffe1
    style S3 fill:#e1ffe1
```

### Chaining Pattern (Sequential Calls with Compensation) / Pattern Chaining (Gọi Tuần Tự với Compensation)

```mermaid
sequenceDiagram
    participant Client
    participant Gateway
    participant OrderService
    participant PaymentService
    
    Client->>Gateway: Create Order Request
    Gateway->>OrderService: POST /orders
    OrderService-->>Gateway: Order Created
    
    Gateway->>PaymentService: POST /payments
    alt Payment Success
        PaymentService-->>Gateway: Payment Processed
        Gateway-->>Client: Success Response
    else Payment Failed
        PaymentService-->>Gateway: Payment Error
        Gateway->>OrderService: DELETE /orders/:id (Compensate)
        OrderService-->>Gateway: Order Deleted
        Gateway-->>Client: Error Response
    end
```

## Các Patterns Chính

### API Composition / API Composition

```typescript
// EN: Aggregate multiple service responses
// VI: Tổng hợp responses từ nhiều services
const [user, orders, payments] = await Promise.all([
  userClient.get(`/users/${userId}`),
  orderClient.get(`/orders?userId=${userId}`),
  paymentClient.get(`/payments?userId=${userId}`),
]);
```

## Best Practices / Thực Hành Tốt

1. Use API composition for aggregating related data / Sử dụng API composition để tổng hợp dữ liệu liên quan
2. Cache at gateway / Cache ở gateway
3. Implement circuit breaker at gateway / Implement circuit breaker ở gateway

## Skills Liên Quan

- [Middleware Patterns](./middleware-patterns.md) - Middleware patterns / Các patterns middleware
- [Resilience Patterns](./resilience-patterns.md) - Circuit breaker / Circuit breaker

## Tài Nguyên

- Skill Source: `.cursor/skills/api-gateway-advanced/SKILL.md`
