python
# Resilience Patterns in Python
# Libs: pip install tenacity pybreaker requests prometheus_client structlog opentelemetry-api opentelemetry-sdk opentelemetry-instrumentation-requests
import uuid
import time
import logging
import random
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import deque
from threading import Semaphore
from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_exception_type
from pybreaker import CircuitBreaker
import structlog # Structured logging
from prometheus_client import Counter, Histogram, start_http_server
import queue
# Observability Setup (Metrics + Tracing + Logging)
start_http_server(8000) # Prometheus metrics at :8000/metrics
logger = structlog.get_logger()
request_counter = Counter('http_requests_total', 'Total requests', ['method', 'status'])
request_latency = Histogram('http_request_duration_seconds', 'Request latency')
cb = CircuitBreaker(fail_max=5, reset_timeout=60) # Circuit Breaker
sem = Semaphore(10) # Bulkhead (max 10 concurrent)
q = queue.Queue(maxsize=100) # Request queue for backpressure
# Idempotency Key Generator
def idempotency_key():
return str(uuid.uuid4())
# External API Call (with timeout)
@request_latency.time()
def call_api(url, idempotency_key=None, timeout=5):
headers = {'Idempotency-Key': idempotency_key} if idempotency_key else {}
resp = requests.get(url, headers=headers, timeout=timeout)
request_counter.labels(method='GET', status=resp.status_code).inc()
resp.raise_for_status()
logger.info("api_call", url=url, status=resp.status_code)
return resp.json()
# 1. Timeouts: Built into requests (above)
# 2. Retries with Jittered Backoff
@retry(
stop=stop_after_attempt(5),
wait=wait_exponential_jitter(jitter=0.1, multiplier=1), # 1s ±10%, 2s ±10%, etc.
retry=retry_if_exception_type(requests.RequestException)
)
def resilient_call(url):
key = idempotency_key()
return call_api(url, key)
# 3. Circuit Breaker
@cb
def cb_call(url):
key = idempotency_key()
return call_api(url, key)
# 4. Bulkhead (Semaphore limits concurrency)
def bulkhead_call(url):
with sem: # Acquire slot or block
key = idempotency_key()
return call_api(url, key)
# 5. Idempotency Keys: Passed in headers (above examples)
# 6. Hedging (duplicate requests to replicas, take fastest)
def hedge_call(primary_url, replicas):
key = idempotency_key()
futures = []
with ThreadPoolExecutor(max_workers=len(replicas)) as executor:
futures.append(executor.submit(call_api, primary_url, key))
for replica in replicas[1:]: # Hedge on secondaries
futures.append(executor.submit(call_api, replica, key))
for future in as_completed(futures):
try:
return future.result() # Return first success
except:
pass
raise Exception("All hedges failed")
# 7. Queues (decouple producer/consumer)
def producer(urls):
for url in urls:
if q.full():
logger.warning("queue_full")
time.sleep(0.1)
else:
q.put(url)
def consumer():
while True:
url = q.get()
try:
resilient_call(url) # Resilient consumption
finally:
q.task_done()
# Usage Example
if __name__ == "__main__":
url = "https://httpbin.org/delay/1" # Test endpoint
print(resilient_call(url)) # Retries + timeout + idempotency
print(cb_call(url)) # + Circuit Breaker
print(bulkhead_call(url)) # + Bulkhead
print(hedge_call(url, [url, url.replace("httpbin", "httpbin.org")])) # Hedging
producer([url] * 50) # Queue producer
yaml
# Istio VirtualService (Timeouts + Retries + Circuit Breaker)
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: resilient-service
spec:
hosts:
- my-service
http:
- route:
- destination:
host: backend
timeout: 5s
retries:
attempts: 3
perTryTimeout: 2s
retryOn: gateway-error,connect-failure,refused,5xx
fault: # Circuit Breaker sim
abort:
percentage:
value: 1 # 1% abort for testing
---
# Kubernetes Deployment (Bulkhead via Resource Limits + HPA)
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: app
resources:
limits:
cpu: "2" # CPU bulkhead
memory: 2Gi
---
# Prometheus Config (Observability)
scrape_configs:
- job_name: app
static_configs:
- targets: ['app:8000']