ASD

Python Resilience

Patrones de resiliencia en Python: reintentos automáticos, backoff exponencial, timeouts y decoradores tolerantes a fallos para servicios.

Estrellas
38.8k

en todo el repo

Actividad
47

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
1

últimos 90 días

Contexto
1.5k tok

59 tok en reposo

Paquete
2 archivos

11 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wshobson/agents --skill python-resilience --agent claude-code

Se instala solo en este repositorio.

Este skill makes network requests.

Qué hace

  • Añade decoradores de retry con la librería tenacity usando backoff exponencial y jitter
  • Define qué excepciones y códigos HTTP son transitorios y deben reintentarse frente a errores permanentes
  • Establece patrones para timeouts, límites de reintentos acotados y logging de cada retry

Úsalo cuando

  • Añadir lógica de reintentos a llamadas a servicios externos
  • Implementar timeouts en operaciones de red
  • Construir microservicios tolerantes a fallos
  • Manejar rate limiting y backpressure o diseñar circuit breakers

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • Añade reintentos con backoff exponencial a esta llamada HTTP
    • Cómo hago que este cliente de API sea tolerante a fallos transitorios
    • Necesito un decorador de retry con tenacity para esta función
    • Implementa timeouts y jitter en las llamadas a este servicio externo

    SKILL.md

    En inglés

    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)
        ),
        stop=stop_after_attempt(5),
        wait=wait_exponential_jitter(initial=1, max=30),
        before_sleep=before_sleep_log(logger, logging.WARNING),
    )
    def robust_http_call(
        method: str,
        url: str,
        **kwargs,
    ) -> httpx.Response:
        """HTTP call with comprehensive retry handling."""
        return httpx.request(method, url, timeout=30, **kwargs)
    

    Detailed worked examples and patterns

    Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.

    Best Practices Summary

    1. Retry only transient errors - Don't retry bugs or authentication failures
    2. Use exponential backoff - Give services time to recover
    3. Add jitter - Prevent thundering herd from synchronized retries
    4. Cap total duration - stop_after_attempt(5) | stop_after_delay(60)
    5. Log every retry - Silent retries hide systemic problems
    6. Use decorators - Keep retry logic separate from business logic
    7. Inject dependencies - Make infrastructure testable
    8. Set timeouts everywhere - Every network call needs a timeout
    9. Fail gracefully - Return cached/default values for non-critical paths
    10. Monitor retry rates - High retry rates indicate underlying issues

    Reproducido de wshobson/agents bajo licencia MIT. Leer esta página en markdown.

    Archivos

    2 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Usa la librería tenacity (y opcionalmente httpx) para implementar los patrones de reintento.

    Detalles

    Creador
    wshobson
    Licencia
    MIT
    Recursos incluidos
    referencias
    Repositorio
    wshobson/agents
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wshobson/agents

    Este repo incluye 180 skills. Si instalas uno, normalmente ya tienes los demás.

    Úsalo al seleccionar y colocar iconos, imágenes, SVGs, diagramas o infografías de apoyo aprobados en un PPTX editable.

    Costo de contexto al activarse
    344 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo cuando pidan optimizar un prompt, mejorar su rendimiento, diseñar una plantilla, aplicar chain-of-thought, few-shot prompting o técnicas avanzadas de prompt engineering para producción.

    Costo de contexto al activarse
    1.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Úsalo al redactar o reparar una especificación JSON con coordenadas explícitas para un PPTX editable.

    Costo de contexto al activarse
    489 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo para validar o reparar un PPTX editable en cuanto a geometría, accesibilidad, editabilidad nativa, linaje de fuente e integridad del paquete OOXML.

    Costo de contexto al activarse
    409 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo para analizar un PPTX de referencia en modo solo lectura: estructura, tema, tipografía, ritmo de layout, diagnósticos, catálogos de plantillas derivados o inspección segura del paquete OOXML.

    Costo de contexto al activarse
    689 tok
    Tamaño del paquete
    8 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo al preparar la narrativa, las fuentes y el contexto de diseño para un nuevo deck PPTX editable.

    Costo de contexto al activarse
    415 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Skills relacionados

    Domina el sistema de tipos avanzado de TypeScript: generics, tipos condicionales, mapped types, template literals y utility types para aplicaciones type-safe.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    herramientas desarrollo

    Organización de proyectos Python, arquitectura de módulos y diseño de APIs públicas con __all__, para nuevos proyectos o reorganización de directorios.

    Costo de contexto al activarse
    1.7k tok
    Tamaño del paquete
    1 archivo
    Última actualización
    hace 6 meses
    herramientas desarrollo

    Domina Next.js 14+ App Router con Server Components, streaming, rutas paralelas y data fetching avanzado. Úsalo al construir apps Next.js, implementar SSR/SSG u optimizar React Server Components.

    Costo de contexto al activarse
    929 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    herramientas desarrollo