Files
pos-system/docs/vi/skills/resilience-patterns.md
Ho Ngoc Hai 2640b351c3 Enhance documentation with detailed diagrams and structured flows
- Added request/response flow diagrams to api-design and api-gateway-advanced skills for better visualization of processes.
- Introduced configuration loading flow in configuration-management skill to clarify the configuration process.
- Included error propagation flow in error-handling-patterns skill to illustrate error handling across layers.
- Enhanced various skills with additional diagrams to improve understanding of complex concepts.

These updates aim to provide clearer guidance and improve the overall documentation experience for developers.
2026-01-01 23:22:54 +07:00

8.4 KiB
Raw Blame History

Các Pattern Resilience

Resilience patterns for GoodGo microservices including circuit breaker, retry strategies, timeout handling, and graceful degradation for improved fault tolerance and system reliability.

Các resilience patterns cho GoodGo microservices bao gồm circuit breaker, retry strategies, timeout handling, và graceful degradation để cải thiện fault tolerance và độ tin cậy hệ thống.

Tổng Quan

Resilience patterns help microservices handle failures gracefully, prevent cascading failures, and maintain system availability even when dependencies fail. This guide covers circuit breaker patterns, retry strategies, timeout handling, and graceful degradation techniques.

Resilience patterns giúp microservices xử lý failures một cách graceful, ngăn chặn cascading failures, và duy trì tính khả dụng của hệ thống ngay cả khi dependencies fail. Hướng dẫn này bao gồm circuit breaker patterns, retry strategies, timeout handling, và các kỹ thuật graceful degradation.

Khi Nào Sử Dụng

Use resilience patterns when:

  • Implementing circuit breaker patterns for external services
  • Adding retry logic for transient failures
  • Setting timeout handling for long-running operations
  • Implementing graceful degradation strategies
  • Handling external service failures
  • Improving system fault tolerance

Sử dụng resilience patterns khi:

  • Implement circuit breaker patterns cho external services
  • Thêm retry logic cho transient failures
  • Thiết lập timeout handling cho long-running operations
  • Implement graceful degradation strategies
  • Xử lý external service failures
  • Cải thiện system fault tolerance

Khái Niệm Chính

Các Pattern Resilience

  1. Circuit Breaker / Ngắt Mạch: Prevents cascading failures by stopping calls to failing services / Ngăn chặn cascading failures bằng cách dừng calls tới services đang fail
  2. Retry / Thử Lại: Automatically retries failed operations with backoff / Tự động retry các operations thất bại với backoff
  3. Timeout / Hết Thời Gian: Sets maximum time limits for operations / Thiết lập giới hạn thời gian tối đa cho operations
  4. Bulkhead / Ngăn Cách: Isolates failures to prevent spread / Cô lập failures để ngăn chặn lây lan
  5. Graceful Degradation / Suy Giảm Nhẹ Nhàng: Provides fallback behavior when services fail / Cung cấp fallback behavior khi services fail

Patterns

Pattern Circuit Breaker

Protects against cascading failures by opening the circuit when error threshold is reached.

Bảo vệ chống lại cascading failures bằng cách mở circuit khi đạt ngưỡng lỗi.

Circuit breaker có ba trạng thái chuyển đổi dựa trên tỷ lệ lỗi và timeout:

stateDiagram-v2
    [*] --> CLOSED: Initial State
    CLOSED --> OPEN: Errors exceed threshold<br/>(errorThresholdPercentage: 50%)
    OPEN --> HALF_OPEN: Reset timeout expires<br/>(resetTimeout: 30s)
    HALF_OPEN --> CLOSED: Request succeeds
    HALF_OPEN --> OPEN: Request fails
    CLOSED --> [*]: Normal operation
    OPEN --> [*]: Circuit open (rejecting requests)
    HALF_OPEN --> [*]: Testing recovery

Circuit Breaker States / Trạng Thái Circuit Breaker:

  • CLOSED: Normal operation, requests pass through / Hoạt động bình thường, requests được cho phép
  • OPEN: Circuit is open, requests are immediately rejected / Circuit mở, requests bị từ chối ngay lập tức
  • HALF-OPEN: Testing if service has recovered, allows limited requests / Kiểm tra service đã phục hồi, cho phép số lượng requests hạn chế
import CircuitBreaker from 'opossum';
import { logger } from '@goodgo/logger';

export const createCircuitBreaker = <TArgs extends any[], TResult>(
  action: (...args: TArgs) => Promise<TResult>,
  name: string,
  options: Partial<CircuitBreaker.Options> = {}
): CircuitBreaker<TArgs, TResult> => {
  const breaker = new CircuitBreaker(action, {
    timeout: 3000,
    errorThresholdPercentage: 50,
    resetTimeout: 30000,
    ...options,
    name,
  });

  breaker.on('open', () => {
${name}`);
  });

  return breaker;
};

// Usage
const externalApiBreaker = createCircuitBreaker(
  async (data) => await externalApi.call(data),
  'external-api'
);

Tham Khảo: services/iam-service/src/modules/common/circuit-breaker.ts

Pattern Retry

Retry transient failures with exponential backoff.

Retry transient failures với exponential backoff.

Pattern retry thử lại operation nhiều lần với delay tăng dần giữa các lần thử:

flowchart TD
    Start([Start Operation]) --> Attempt[Attempt Operation]
    Attempt --> Success{Success?}
    Success -->|Yes| Return([Return Result])
    Success -->|No| CheckRetries{Attempt < Max Retries?}
    CheckRetries -->|No| ThrowError([Throw Error])
    CheckRetries -->|Yes| CalculateDelay[Calculate Delay:<br/>baseDelay × 2^attempt]
    CalculateDelay --> Wait[Wait for Delay]
    Wait --> IncrementAttempt[Increment Attempt]
    IncrementAttempt --> Attempt
    
    style Start fill:#e1f5e1
    style Return fill:#e1f5e1
    style ThrowError fill:#ffe1e1
    style CalculateDelay fill:#fff4e1

Exponential Backoff Example / Ví Dụ Exponential Backoff:

  • Attempt 1: 1s delay
  • Attempt 2: 2s delay
  • Attempt 3: 4s delay
  • Attempt 4: 8s delay
async function retryWithBackoff<T>(
  fn: () => Promise<T>,
  maxRetries: number = 3,
  baseDelay: number = 1000
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (attempt === maxRetries) throw error;
      const delay = baseDelay * Math.pow(2, attempt);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  throw new Error('Retry exhausted');
}

Pattern Timeout

Set maximum time limits for operations.

Thiết lập giới hạn thời gian tối đa cho operations.

Pattern timeout sử dụng Promise.race để thực thi giới hạn thời gian tối đa:

sequenceDiagram
    participant Client
    participant TimeoutWrapper
    participant Operation
    participant TimeoutTimer
    
    Client->>TimeoutWrapper: Execute with timeout
    TimeoutWrapper->>Operation: Start operation
    TimeoutWrapper->>TimeoutTimer: Start timeout timer
    
    alt Operation completes first
        Operation-->>TimeoutWrapper: Return result
        TimeoutWrapper-->>Client: Return result
        TimeoutWrapper->>TimeoutTimer: Cancel timer
    else Timeout expires first
        TimeoutTimer-->>TimeoutWrapper: Timeout error
        TimeoutWrapper->>Operation: (Operation may continue)
        TimeoutWrapper-->>Client: Reject with timeout error
    end

Timeout Behavior / Hành Vi Timeout:

  • Uses Promise.race() to compete operation vs timeout / Sử dụng Promise.race() để so sánh operation với timeout
  • First to resolve/reject wins / Cái nào resolve/reject trước sẽ thắng
  • Operation may continue after timeout, but result is ignored / Operation có thể tiếp tục sau timeout, nhưng kết quả bị bỏ qua
async function withTimeout<T>(
  promise: Promise<T>,
  timeoutMs: number
): Promise<T> {
  const timeout = new Promise<never>((_, reject) => {
    setTimeout(() => reject(new Error('Operation timeout')), timeoutMs);
  });
  
  return Promise.race([promise, timeout]);
}

Thực Hành Tốt Nhất

  1. Circuit Breaker / Circuit Breaker: Sử dụng cho external service calls
  2. Retry / Retry: Chỉ retry transient failures (network, timeout)
  3. Timeout / Timeout: Thiết lập timeouts phù hợp cho tất cả external calls
  4. Fallback / Fallback: Luôn cung cấp fallback behavior
  5. Monitoring / Giám Sát: Monitor circuit breaker states và retry rates
  6. Logging / Ghi Log: Log tất cả resilience actions để debug

Lỗi Thường Gặp

  1. Retrying Non-Retryable Errors / Retry Các Lỗi Không Thể Retry: Retry 4xx errors (client errors)
  2. No Timeout / Không Có Timeout: Thiếu timeouts trên external calls
  3. No Fallback / Không Có Fallback: Không có graceful degradation strategy
  4. Too Many Retries / Retry Quá Nhiều: Retry quá nhiều gây performance issues

Tài Nguyên