Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)41k · #6766

python-resilience

Skill này làm gì

Công cụ này giúp chương trình máy tính đáng tin cậy hơn. Nó tự động thử lại nếu có điều gì đó tạm thời trục trặc, như lỗi mạng, và chờ một chút trước khi thử lại.

Khi nào nên dùng

  • ✓Khi một phần của chương trình cần kết nối tới dịch vụ khác và có thể thất bại.
  • ✓Khi bạn muốn chương trình tiếp tục hoạt động dù có trục trặc nhỏ tạm thời.
  • ✓Khi bạn muốn tránh làm quá tải một dịch vụ đang gặp khó khăn bằng cách thử lại dần dần.

Liên kết skill

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resilience/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resilience/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm chương trình thử lại tối đa 3 lần nếu kết nối tới website thất bại, và chờ lâu hơn sau mỗi lần.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Bên trong, code dùng một kỹ thuật gọi là “retry”. Nếu một thao tác thất bại, nó chờ một khoảng thời gian tăng dần sau mỗi lần thử (exponential backoff) trước khi thử lại, giúp chương trình không bị sập.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Python Resilience Patterns

Build fault-tolerant Python applications that gracefully handle transient failures, network issues, and service outages. Resilience patterns keep systems running when dependencies are unreliable.

When to Use This Skill

  • Adding retry logic to external service calls
  • Implementing timeouts for network operations
  • Building fault-tolerant microservices
  • Handling rate limiting and backpressure
  • Creating infrastructure decorators
  • Designing circuit breakers

Core Concepts

1. Transient vs Permanent Failures

Retry transient errors (network timeouts, temporary service issues). Don't retry permanent errors (invalid credentials, bad requests).

2. Exponential Backoff

Increase wait time between retries to avoid overwhelming recovering services.

3. Jitter

Add randomness to backoff to prevent thundering herd when many clients retry simultaneously.

4. Bounded Retries

Cap both attempt count and total duration to prevent infinite retry loops.

Quick Start

from tenacity import retry, stop_after_attempt, wait_exponential_jitter

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
)
def call_external_service(request: dict) -> dict:
    return httpx.post("https://api.example.com", json=request).json()

Fundamental Patterns

Pattern 1: Basic Retry with Tenacity

Use the tenacity library for production-grade retry logic. For simpler cases, consider built-in retry functionality or a lightweight custom implementation.

from tenacity import (
    retry,
    stop_after_attempt,
    stop_after_delay,
    wait_exponential_jitter,
    retry_if_exception_type,
)

TRANSIENT_ERRORS = (ConnectionError, TimeoutError, OSError)

@retry(
    retry=retry_if_exception_type(TRANSIENT_ERRORS),
    stop=stop_after_attempt(5) | stop_after_delay(60),
    wait=wait_exponential_jitter(initial=1, max=30),
)
def fetch_data(url: str) -> dict:
    """Fetch data with automatic retry on transient failures."""
    response = httpx.get(url, timeout=30)
    response.raise_for_status()
    return response.json()

Pattern 2: Retry Only Appropriate Errors

Whitelist specific transient exceptions. Never retry:

  • ValueError, TypeError - These are bugs, not transient issues
  • AuthenticationError - Invalid credentials won't become valid
  • HTTP 4xx errors (except 429) - Client errors are permanent
from tenacity import retry, retry_if_exception_type
import httpx

# Define what's retryable
RETRYABLE_EXCEPTIONS = (
    ConnectionError,
    TimeoutError,
    httpx.ConnectTimeout,
    httpx.ReadTimeout,
)

@retry(
    retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS),
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
)
def resilient_api_call(endpoint: str) -> dict:
    """Make API call with retry on network issues."""
    return httpx.get(endpoint, timeout=10).json()

Pattern 3: HTTP Status Code Retries

Retry specific HTTP status codes that indicate transient issues.

from tenacity import retry, retry_if_result, stop_after_attempt
import httpx

RETRY_STATUS_CODES = {429, 502, 503, 504}

def should_retry_response(response: httpx.Response) -> bool:
    """Check if response indicates a retryable error."""
    return response.status_code in RETRY_STATUS_CODES

@retry(
    retry=retry_if_result(should_retry_response),
    stop=stop_after_attempt(3),
    wait=wait_exponential_jitter(initial=1, max=10),
)
def http_request(method: str, url: str, **kwargs) -> httpx.Response:
    """Make HTTP request with retry on transient status codes."""
    return httpx.request(method, url, timeout=30, **kwargs)

Pattern 4: Combined Exception and Status Retry

Handle both network exceptions and HTTP status codes.

from tenacity import (
    retry,
    retry_if_exception_type,
    retry_if_result,
    stop_after_attempt,
    wait_exponential_jitter,
    before_sleep_log,
)
import logging
import httpx

logger = logging.getLogger(__name__)

TRANSIENT_EXCEPTIONS = (
    ConnectionError,
    TimeoutError,
    httpx.ConnectError,
    httpx.ReadTimeout,
)
RETRY_STATUS_CODES = {429, 500, 502, 503, 504}

def is_retryable_response(response: httpx.Response) -> bool:
    return response.status_code in RETRY_STATUS_CODES

@retry(
    retry=(
        retry_if_exception_type(TRANSIENT_EXCEPTIONS) |
        retry_if_result(is_retryable_response)
    ),

…
Câu hỏi thường gặp

“Transient failures” là gì?

Đó là các vấn đề tự khắc phục, như mạng chậm tạm thời hoặc dịch vụ bị ngừng nhưng sau đó đã hoạt động lại.

Tại sao phải chờ lâu hơn sau mỗi lần thử?

Để cho dịch vụ đang lỗi có thời gian phục hồi. Thử quá nhiều lần liên tiếp có thể làm vấn đề thêm nặng.

“Jitter” là gì?

Đó là việc thêm một khoảng thời gian ngẫu nhiên nhỏ vào thời gian chờ. Điều này tránh việc nhiều chương trình cùng thử lại đúng một thời điểm, có thể làm quá tải dịch vụ.

Chi tiết

Mô tả gốc của tác giả

Python resilience patterns including automatic retries, exponential backoff, timeouts, and fault-tolerant decorators. Use when adding retry logic, implementing timeouts, building fault-tolerant services, or handling transient failures.

repo: wshobson/agents

Độ phổ biến

Sao GitHub
41k
Vị trí xếp hạng
#6766
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự