本文へスキップ
Skillpedia
APIとサーバー(バックエンド)41k · #6766

python-resilience

できること

このツールは、コンピュータープログラムをより信頼性の高いものにする手助けをします。ネットワークの問題などで一時的に何かがうまくいかなかったとき、プログラムが自動的に再試行し、少し待ってからもう一度実行するようにします。

使う場面

  • ✓プログラムの一部が別のサービスに接続する必要があり、失敗する可能性があるとき。
  • ✓小さな一時的な不具合があっても、プログラムを動かし続けたいとき。
  • ✓負荷がかかっているサービスを、再試行を少しずつ行うことで圧倒しないようにしたいとき。

スキルのリンク

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

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resilience/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“Webサイトへの接続が失敗したら、最大3回まで再試行してください。毎回、待つ時間を少しずつ長くしてください。”

毎週5つの新しいスキル。1分で読めます。

仕組み

内部のコードでは「リトライ」という手法を使います。処理が失敗すると、試行のたびに待つ時間を長くしてから(指数バックオフ)もう一度試します。これにより、プログラムがエラーで停止するのを防ぎます。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

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)
    ),

…
よくある質問

一時的な失敗とは何ですか?

しばらくすると自然に直る問題のことです。例えば、一時的に遅くなったネットワークや、一度停止したもののその後復旧したサービスなどが該当します。

なぜ再試行のたびに待つ時間を長くするのですか?

失敗しているサービスに復旧する時間を与えるためです。短い間隔で何度も試すと、問題をさらに悪化させる可能性があります。

「ジッター」とは何ですか?

待ち時間に少しランダムな時間を加えることです。多くのプログラムが全く同じタイミングで再試行するのを防ぎ、サービスに過剰な負荷がかかるのを避けられます。

詳細

作者による元の説明

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

人気

GitHubのスター
41k
ランキング
#6766
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル