Python resilience patterns including automatic retries

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.
--- name: python-resilience description: 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. --- # 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
Overview
Build fault-tolerant Python applications that gracefully handle transient failures, network issues, and service outages. Resilience patterns keep systems running when dependencies are unreliable.
Manual install (npx, ZIP)
npx skills add wshobson/agents --skill python-resilience -g -a claude-codemkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \
| tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/python-development/skills/python-resilienceNew-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/8e37e7a833b65a8b943b/python-resilience.zip" -OutFile "$env:TEMP\python-resilience.zip"; Expand-Archive "$env:TEMP\python-resilience.zip" -DestinationPath "$HOME\.claude\skills" -ForceConnects with Agent Alley MCP · agentalley.io/mcp
Files included
SKILL.md5.9 KBreferences/1 file · 5.3 KB
Read the files here
Show the full text196 lines
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 issuesAuthenticationError- 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
- Retry only transient errors - Don't retry bugs or authentication failures
- Use exponential backoff - Give services time to recover
- Add jitter - Prevent thundering herd from synchronized retries
- Cap total duration -
stop_after_attempt(5) | stop_after_delay(60) - Log every retry - Silent retries hide systemic problems
- Use decorators - Keep retry logic separate from business logic
- Inject dependencies - Make infrastructure testable
- Set timeouts everywhere - Every network call needs a timeout
- Fail gracefully - Return cached/default values for non-critical paths
- Monitor retry rates - High retry rates indicate underlying issues
| 1 | |
| 2 | name python-resilience |
| 3 | description 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. |
| 4 | |
| 5 | |
| 6 | # Python Resilience Patterns |
| 7 | |
| 8 | Build fault-tolerant Python applications that gracefully handle transient failures, network issues, and service outages. Resilience patterns keep systems running when dependencies are unreliable. |
| 9 | |
| 10 | ## When to Use This Skill |
| 11 | |
| 12 | Adding retry logic to external service calls |
| 13 | Implementing timeouts for network operations |
| 14 | Building fault-tolerant microservices |
| 15 | Handling rate limiting and backpressure |
| 16 | Creating infrastructure decorators |
| 17 | Designing circuit breakers |
| 18 | |
| 19 | ## Core Concepts |
| 20 | |
| 21 | ### 1. Transient vs Permanent Failures |
| 22 | |
| 23 | Retry transient errors (network timeouts, temporary service issues). Don't retry permanent errors (invalid credentials, bad requests). |
| 24 | |
| 25 | ### 2. Exponential Backoff |
| 26 | |
| 27 | Increase wait time between retries to avoid overwhelming recovering services. |
| 28 | |
| 29 | ### 3. Jitter |
| 30 | |
| 31 | Add randomness to backoff to prevent thundering herd when many clients retry simultaneously. |
| 32 | |
| 33 | ### 4. Bounded Retries |
| 34 | |
| 35 | Cap both attempt count and total duration to prevent infinite retry loops. |
| 36 | |
| 37 | ## Quick Start |
| 38 | |
| 39 | |
| 40 | from tenacity import retry, stop_after_attempt, wait_exponential_jitter |
| 41 | |
| 42 | @retry( |
| 43 | stop=stop_after_attempt(3), |
| 44 | wait=wait_exponential_jitter(initial=1, max=10), |
| 45 | ) |
| 46 | def call_external_service(request: dict) -> dict: |
| 47 | return httpx.post("https://api.example.com", json=request).json() |
| 48 | |
| 49 | |
| 50 | ## Fundamental Patterns |
| 51 | |
| 52 | ### Pattern 1: Basic Retry with Tenacity |
| 53 | |
| 54 | Use the `tenacity` library for production-grade retry logic. For simpler cases, consider built-in retry functionality or a lightweight custom implementation. |
| 55 | |
| 56 | |
| 57 | from tenacity import ( |
| 58 | retry, |
| 59 | stop_after_attempt, |
| 60 | stop_after_delay, |
| 61 | wait_exponential_jitter, |
| 62 | retry_if_exception_type, |
| 63 | ) |
| 64 | |
| 65 | TRANSIENT_ERRORS = (ConnectionError, TimeoutError, OSError) |
| 66 | |
| 67 | @retry( |
| 68 | retry=retry_if_exception_type(TRANSIENT_ERRORS), |
| 69 | stop=stop_after_attempt(5) | stop_after_delay(60), |
| 70 | wait=wait_exponential_jitter(initial=1, max=30), |
| 71 | ) |
| 72 | def fetch_data(url: str) -> dict: |
| 73 | """Fetch data with automatic retry on transient failures.""" |
| 74 | response = httpx.get(url, timeout=30) |
| 75 | response.raise_for_status() |
| 76 | return response.json() |
| 77 | |
| 78 | |
| 79 | ### Pattern 2: Retry Only Appropriate Errors |
| 80 | |
| 81 | Whitelist specific transient exceptions. Never retry: |
| 82 | |
| 83 | `ValueError`, `TypeError` - These are bugs, not transient issues |
| 84 | `AuthenticationError` - Invalid credentials won't become valid |
| 85 | HTTP 4xx errors (except 429) - Client errors are permanent |
| 86 | |
| 87 | |
| 88 | from tenacity import retry, retry_if_exception_type |
| 89 | import httpx |
| 90 | |
| 91 | # Define what's retryable |
| 92 | RETRYABLE_EXCEPTIONS = ( |
| 93 | ConnectionError, |
| 94 | TimeoutError, |
| 95 | httpx.ConnectTimeout, |
| 96 | httpx.ReadTimeout, |
| 97 | ) |
| 98 | |
| 99 | @retry( |
| 100 | retry=retry_if_exception_type(RETRYABLE_EXCEPTIONS), |
| 101 | stop=stop_after_attempt(3), |
| 102 | wait=wait_exponential_jitter(initial=1, max=10), |
| 103 | ) |
| 104 | def resilient_api_call(endpoint: str) -> dict: |
| 105 | """Make API call with retry on network issues.""" |
| 106 | return httpx.get(endpoint, timeout=10).json() |
| 107 | |
| 108 | |
| 109 | ### Pattern 3: HTTP Status Code Retries |
| 110 | |
| 111 | Retry specific HTTP status codes that indicate transient issues. |
| 112 | |
| 113 | |
| 114 | from tenacity import retry, retry_if_result, stop_after_attempt |
| 115 | import httpx |
| 116 | |
| 117 | RETRY_STATUS_CODES = {429, 502, 503, 504} |
| 118 | |
| 119 | def should_retry_response(response: httpx.Response) -> bool: |
| 120 | """Check if response indicates a retryable error.""" |
| 121 | return response.status_code in RETRY_STATUS_CODES |
| 122 | |
| 123 | @retry( |
| 124 | retry=retry_if_result(should_retry_response), |
| 125 | stop=stop_after_attempt(3), |
| 126 | wait=wait_exponential_jitter(initial=1, max=10), |
| 127 | ) |
| 128 | def http_request(method: str, url: str, **kwargs) -> httpx.Response: |
| 129 | """Make HTTP request with retry on transient status codes.""" |
| 130 | return httpx.request(method, url, timeout=30, **kwargs) |
| 131 | |
| 132 | |
| 133 | ### Pattern 4: Combined Exception and Status Retry |
| 134 | |
| 135 | Handle both network exceptions and HTTP status codes. |
| 136 | |
| 137 | |
| 138 | from tenacity import ( |
| 139 | retry, |
| 140 | retry_if_exception_type, |
| 141 | retry_if_result, |
| 142 | stop_after_attempt, |
| 143 | wait_exponential_jitter, |
| 144 | before_sleep_log, |
| 145 | ) |
| 146 | import logging |
| 147 | import httpx |
| 148 | |
| 149 | logger = logging.getLogger(__name__) |
| 150 | |
| 151 | TRANSIENT_EXCEPTIONS = ( |
| 152 | ConnectionError, |
| 153 | TimeoutError, |
| 154 | httpx.ConnectError, |
| 155 | httpx.ReadTimeout, |
| 156 | ) |
| 157 | RETRY_STATUS_CODES = {429, 500, 502, 503, 504} |
| 158 | |
| 159 | def is_retryable_response(response: httpx.Response) -> bool: |
| 160 | return response.status_code in RETRY_STATUS_CODES |
| 161 | |
| 162 | @retry( |
| 163 | retry=( |
| 164 | retry_if_exception_type(TRANSIENT_EXCEPTIONS) | |
| 165 | retry_if_result(is_retryable_response) |
| 166 | ), |
| 167 | stop=stop_after_attempt(5), |
| 168 | wait=wait_exponential_jitter(initial=1, max=30), |
| 169 | before_sleep=before_sleep_log(logger, logging.WARNING), |
| 170 | ) |
| 171 | def robust_http_call( |
| 172 | method: str, |
| 173 | url: str, |
| 174 | **kwargs, |
| 175 | ) -> httpx.Response: |
| 176 | """HTTP call with comprehensive retry handling.""" |
| 177 | return httpx.request(method, url, timeout=30, **kwargs) |
| 178 | |
| 179 | |
| 180 | ## Detailed worked examples and patterns |
| 181 | |
| 182 | Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient. |
| 183 | |
| 184 | ## Best Practices Summary |
| 185 | |
| 186 | **Retry only transient errors** - Don't retry bugs or authentication failures |
| 187 | **Use exponential backoff** - Give services time to recover |
| 188 | **Add jitter** - Prevent thundering herd from synchronized retries |
| 189 | **Cap total duration** - `stop_after_attempt(5) | stop_after_delay(60)` |
| 190 | **Log every retry** - Silent retries hide systemic problems |
| 191 | **Use decorators** - Keep retry logic separate from business logic |
| 192 | **Inject dependencies** - Make infrastructure testable |
| 193 | **Set timeouts everywhere** - Every network call needs a timeout |
| 194 | **Fail gracefully** - Return cached/default values for non-critical paths |
| 195 | **Monitor retry rates** - High retry rates indicate underlying issues |
| 196 |
Details
- Updated
- Sep 21, 2026
- License
- MIT
- Stars on the repo
- ★ 39,857
- Checked
- Source
- wshobson/agents ↗
- Creator
- wshobson · 179 listings
Similar skills
See all →
SkillA task is too large for one model passAdvisor orchestrator worker
SkillRun the CCS Align seat's hourly breathing cycleCCS Align — Worker Watch seat (Phases 0–2 shipped; Phase 3 = verify / sign-off)
SkillSummarize and review what changed while you were awayCatchup — Async-Team Return Briefing
SkillMaster Python asyncio, concurrent programmingAsync python patterns
SkillMaster Go concurrency with goroutines, channelsGo concurrency patterns
SkillDesign microservices architectures with service boundariesMicroservices patternsMore from wshobson
SkillMaster C/.NET backend development patterns for building
SkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliance
SkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Design
SkillMigrate from AngularJS to Angular using hybrid modeAngular migration
SkillUnderstand anti-reversing, obfuscationAnti reversing techniques
SkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patterns