Files
pos-system/docs/vi/skills/resilience-patterns.md
Ho Ngoc Hai 9b6c585f57 Enhance documentation structure and improve bilingual support across skills
- Updated skill documentation files to include structured metadata for better organization.
- Enhanced bilingual descriptions and guidelines for clarity in both English and Vietnamese.
- Refined sections on usage, best practices, and related skills to ensure consistency across all documentation.
- Improved formatting and removed outdated references to streamline the documentation experience.
- Added best practices checklists to relevant skills for better usability and adherence to standards.
2026-01-01 07:35:44 +07:00

5.5 KiB

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.

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.

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.

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