xiaohongshu
xiaohongshu
error-recovery-patterns
Error recovery and failure handling patterns for distributed systems including rollback strategies, circuit breakers, retry logic with exponential backoff, graceful degradation, and compensating transactions. Activates when task execution fails, timeouts occur, external services fail, database tr...
Full skill instructions
When systems fail, how you recover determines the difference between a minor hiccup and a catastrophic outage. This skill provides systematic approaches to error recovery, failure handling, and resilience patterns.
When to use this skill:
Transient vs Permanent:
Recoverable vs Fatal:
Scope:
| Failure Type | Recovery Strategy | Pattern to Use |
|---|---|---|
| Transient + Recoverable | Retry with backoff | Exponential backoff, jitter |
| Transient + Service failure | Circuit breaker | Open/half-open/closed states |
| Permanent + Recoverable | Rollback or compensate | Transaction rollback, saga pattern |
| Permanent + Fatal | Fail gracefully | Graceful degradation, fallback |
| Distributed + Transient | Retry with timeout | Distributed timeout, bulkhead |
| Distributed + Permanent | Compensating transaction | Saga pattern, event sourcing |
| Cascading risk | Prevent cascade | Circuit breaker, rate limiting |
When to use:
Implementation approach:
# Exponential backoff with jitter
def retry_with_backoff(func, max_retries=5, base_delay=1, max_delay=60):
"""
Retry with exponential backoff and jitter.
Args:
func: Function to retry
max_retries: Maximum retry attempts (default 5)
base_delay: Initial delay in seconds (default 1)
max_delay: Maximum delay in seconds (default 60)
"""
for attempt in range(max_retries):
try:
return func()
except TransientError as e:
if attempt == max_retries - 1:
raise # Final attempt, re-raise
# Exponential backoff: 1s, 2s, 4s, 8s, 16s...
delay = min(base_delay * (2 ** attempt), max_delay)
# Add jitter (±25%) to prevent thundering herd
jitter = delay * 0.25 * (2 * random.random() - 1)
actual_delay = delay + jitter
logger.warning(f"Transient error on attempt {attempt + 1}, "
f"retrying in {actual_delay:.2f}s: {e}")
time.sleep(actual_delay)
Key principles:
When NOT to use:
When to use:
Implementation approach:
class CircuitBreaker:
"""
Circuit breaker pattern with three states:
- CLOSED: Normal operation, requests pass through
- OPEN: Failures exceeded threshold, requests fail fast
- HALF_OPEN: Testing if service recovered
"""
def __init__(self, failure_threshold=5, timeout=60, success_threshold=2):
self.failure_threshold = failure_threshold # Failures before opening
self.timeout = timeout # Seconds before trying again (half-open)
self.success_threshold = success_threshold # Successes to close
self.failure_count = 0
self.success_count = 0
self.state = "CLOSED"
self.opened_at = None
def call(self, func):
"""Execute function through circuit breaker."""
if self.state == "OPEN":
# Check if timeout elapsed
if time.time() - self.opened_at >= self.timeout:
self.state = "HALF_OPEN"
self.success_count = 0
logger.info("Circuit breaker entering HALF_OPEN state")
else:
raise CircuitBreakerOpenError("Circuit breaker is OPEN")
try:
result = func()
self._on_success()
return result
except Exception as e:
self._on_failure()
raise
def _on_success(self):
"""Handle successful call."""
self.failure_count = 0
if self.state == "HALF_OPEN":
self.success_count += 1
if self.success_count >= self.success_threshold:
self.state = "CLOSED"
logger.info("Circuit breaker CLOSED (service recovered)")
def _on_failure(self):
"""Handle failed call."""
self.failure_count += 1
if self.state == "HALF_OPEN":
# Failure in half-open state, reopen circuit
self.state = "OPEN"
self.opened_at = time.time()
logger.warning("Circuit breaker OPEN (half-open test failed)")
elif self.failure_count >= self.failure_threshold:
# Threshold exceeded, open circuit
self.state = "OPEN"
self.opened_at = time.time()
logger.error(f"Circuit breaker OPEN ({self.failure_count} failures)")
Key principles:
Monitoring:
When to use:
Implementation approach:
def transfer_funds(from_account, to_account, amount):
"""
Transfer funds with automatic rollback on failure.
Demonstrates transaction rollback pattern.
"""
with db.transaction(): # Automatically rolls back on exception
try:
# Step 1: Debit source account
from_balance = db.get_balance(from_account)
if from_balance < amount:
raise InsufficientFundsError(f"Balance {from_balance} < {amount}")
db.debit(from_account, amount)
logger.info(f"Debited {amount} from {from_account}")
# Step 2: Credit destination account
db.credit(to_account, amount)
logger.info(f"Credited {amount} to {to_account}")
# Step 3: Record transaction
db.record_transaction(from_account, to_account, amount, timestamp=now())
logger.info(f"Recorded transaction {from_account} → {to_account}")
# All steps succeeded, commit
return TransactionResult(success=True, transaction_id=...)
except Exception as e:
# Any failure triggers automatic rollback
logger.error(f"Transaction failed, rolling back: {e}")
# with statement handles rollback automatically
raise TransactionFailedError(f"Transfer failed: {e}") from e
Key principles:
When NOT to use:
When to use:
Implementation approach:
class BookingWorkflow:
"""
Hotel booking saga with compensating transactions.
Steps: Reserve hotel → Charge payment → Send confirmation
Compensations: Cancel reservation ← Refund payment ← Cancel email
"""
def execute(self, booking_request):
"""Execute saga with automatic compensation on failure."""
executed_steps = []
try:
# Step 1: Reserve hotel room
reservation = self.hotel_service.reserve_room(
booking_request.hotel_id,
booking_request.dates
)
executed_steps.append(("reserve_room", reservation.id))
logger.info(f"Reserved room {reservation.id}")
# Step 2: Charge payment
payment = self.payment_service.charge(
booking_request.card,
booking_request.amount
)
executed_steps.append(("charge_payment", payment.id))
logger.info(f"Charged payment {payment.id}")
# Step 3: Send confirmation email
email = self.email_service.send_confirmation(
booking_request.email,
reservation,
payment
)
executed_steps.append(("send_email", email.id))
logger.info(f"Sent confirmation {email.id}")
# All steps succeeded
return BookingResult(success=True, reservation_id=reservation.id)
except Exception as e:
# Failure occurred, compensate executed steps in reverse order
logger.error(f"Booking failed at step {len(executed_steps)}, "
f"compensating: {e}")
self._compensate(executed_steps)
raise BookingFailedError(f"Booking failed: {e}") from e
def _compensate(self, executed_steps):
"""Execute compensating transactions in reverse order."""
for step_name, step_id in reversed(executed_steps):
try:
if step_name == "reserve_room":
self.hotel_service.cancel_reservation(step_id)
logger.info(f"Compensated: cancelled reservation {step_id}")
elif step_name == "charge_payment":
self.payment_service.refund(step_id)
logger.info(f"Compensated: refunded payment {step_id}")
elif step_name == "send_email":
self.email_service.send_cancellation(step_id)
logger.info(f"Compensated: sent cancellation {step_id}")
except Exception as comp_error:
# Compensation failed - critical error requiring manual intervention
logger.critical(f"COMPENSATION FAILED for {step_name} {step_id}: "
f"{comp_error}")
# Alert operations team
self.alert_service.critical_alert(
f"Manual intervention required: compensation failed",
details={"step": step_name, "id": step_id, "error": comp_error}
)
Key principles:
Saga orchestration patterns:
When to use:
Implementation approach:
def get_user_recommendations(user_id):
"""
Get personalized recommendations with graceful degradation.
Fallback chain: ML model → collaborative filtering → popular items
"""
try:
# Primary: ML-based personalized recommendations
recommendations = ml_service.get_recommendations(user_id, timeout=2.0)
logger.info(f"Returned ML recommendations for user {user_id}")
return recommendations
except (TimeoutError, ServiceUnavailableError) as e:
logger.warning(f"ML service unavailable, falling back to collaborative: {e}")
try:
# Fallback 1: Collaborative filtering (faster, simpler)
recommendations = collab_filter_service.get_similar_users_items(
user_id,
timeout=1.0
)
logger.info(f"Returned collaborative filtering for user {user_id}")
return recommendations
except (TimeoutError, ServiceUnavailableError) as e2:
logger.warning(f"Collaborative filtering failed, falling back to popular: {e2}")
try:
# Fallback 2: Popular items (cached, always available)
recommendations = cache.get_popular_items(category=user.category)
logger.info(f"Returned popular items for user {user_id}")
return recommendations
except Exception as e3:
# Final fallback: Empty recommendations (degraded but functional)
logger.error(f"All recommendation sources failed, returning empty: {e3}")
return [] # Graceful degradation: site still works, just no recommendations
Key principles:
Fallback strategies:
Pattern: Use database transactions for ACID guarantees
When to use:
Implementation: Transaction rollback pattern (see Pattern 3 above)
Pattern: Accept temporary inconsistency, guarantee eventual convergence
When to use:
Implementation:
# Step 1: Write to primary database (source of truth)
db.create_order(order_id, user_id, items, total)
# Step 2: Publish event for eventual consistency
event_bus.publish(OrderCreatedEvent(
order_id=order_id,
user_id=user_id,
items=items,
total=total,
timestamp=now()
))
# Other services consume event asynchronously:
# - Inventory service decrements stock
# - Analytics service records purchase
# - Email service sends confirmation
# Each service eventually becomes consistent
Key principles:
Pattern: Preserve cause-effect relationships while allowing other operations to be reordered
When to use:
Implementation: Use vector clocks or logical timestamps to track causality
Purpose: Isolate failures to prevent cascade
Implementation:
Purpose: Prevent indefinite waiting
Implementation:
# Set aggressive timeouts
response = requests.get(
external_api_url,
timeout=(3.0, 10.0) # (connection timeout, read timeout)
)
# Async with timeout
async with asyncio.timeout(5.0):
result = await long_running_operation()
Guidelines:
Purpose: Prevent overload from excessive requests
Implementation:
Symptom-based alerts (what users experience):
Cause-based logging (for debugging):
Inject failures in test/staging:
Verify:
Is failure transient or permanent?
Is system distributed?
Is service external/unreliable?
Can I degrade gracefully?
What consistency guarantees needed?
Problem: Infinite retry loop exhausts resources Solution: Max retries (3-5), exponential backoff, circuit breaker
Problem: Thundering herd (all clients retry simultaneously) Solution: Add jitter (±25% randomness) to backoff
Problem: Duplicate charges, duplicate emails Solution: Use idempotency keys, check before retrying
Problem: Half-completed saga leaves inconsistent state Solution: Alert operations team, manual intervention required
Problem: Indefinite hangs consume resources Solution: Set timeouts on all external calls (3-10s)
Problem: Long-running saga blocks user Solution: Asynchronous saga (immediate response, poll for completion)
Scenario: Credit card charge fails during checkout
Recovery strategy:
Scenario: Recommendation service unavailable
Recovery strategy:
Scenario: Transfer between accounts fails mid-transaction
Recovery strategy:
When implementing error recovery:
Remember: The goal is to recover automatically when possible, fail gracefully when not, and always maintain data consistency.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience