Okay, the user wants a backend resilience playbook that maps fallback strategies, retry policies, and compensation mechanisms for different types of dependencies. This is a structured request for a production-grade system design document.
I should approach this as a template-driven framework rather than a prescriptive solution—every system’s dependencies differ. The core need is to provide a reusable methodology for classifying external/internal dependencies and assigning resilience patterns per category.
I recall Martin Fowler’s circuit breaker patterns and Netflix’s Hystrix legacy concepts, but modern systems often use libraries like resilience4j or Polly. The user probably needs actionable categories, not just theory. Let me break this into:
- Dependency classification (database, cache, external API, message broker, etc.)
- Per-category resilience strategies with concrete examples (e.g., database → retry with exponential backoff + fallback to read replicas)
- Implementation notes (timeouts, idempotency, monitoring)
- Trade-offs (latency vs. consistency)
Avoid over-engineering—focus on high-impact patterns. The user likely wants to avoid common pitfalls like unbounded retries or silent fallbacks. Should emphasize observability and testing too.
Structure will be:
- Principles first (idempotency, timeouts)
- Dependency matrix table for quick reference
- Detailed per-dependency sections with code-like pseudocode
- Monitoring/alerting guidelines
- Testing strategies (chaos engineering)
Need to warn against anti-patterns: e.g., “retry flood” from misconfigured backoffs. Also clarify that compensation (sagas) is for distributed transactions, not all failures.
The tone should be authoritative but adaptable—this is a playbook, not dogma. Include placeholders like [SERVICE_NAME] so the user can template it. Avoid language-specific idioms (keep it polyglot).
Backend Resilience Playbook
Mapping Fallbacks, Retries, and Compensations per Dependency Type
1. Guiding Principles
- Idempotency First: Design all retryable operations to be safe for multiple executions.
- Timeout Isolation: Never allow downstream latency to cascade (set strict, tiered timeouts).
- Fail Fast, Recover Gracefully: Prefer controlled degradation over total failure.
- Observability: Log every fallback/retry/compensation with context (trace ID, dependency, error type).
- Circuit Breaker Hygiene: Use stateful circuit breakers per dependency, not per endpoint.
2. Dependency Classification & Resilience Mapping
| Dependency Type | Retry Policy | Fallback Strategy | Compensation / Saga Pattern? | Key Risks & Mitigations |
|---|
| SQL Database | Exponential backoff (max 3 retries) | - Read: Serve stale cache (if TTL > 0) - Write: Queue async (with DLQ) | Saga (for cross-table transactions) | - Deadlocks → abort, retry with jitter - Connection leaks → validate pool health |
| NoSQL Database | Exponential backoff (max 2 retries) | - Read: Return default/empty set - Write: Local buffer + alert | Choreography-based saga | - Consistency trade-offs → use read-replica fallback - Quorum failures → fail open |
| External REST API | Retry only on 429/5xx (max 2) with jitter | - Cache (stale) - Mock response (predefined) - Degraded functionality | Not typical (avoid 2PC) | - Rate limits → bucket4j token bucket - Schema drift → schema validation on fallback |
| Message Queue (Kafka/Rabbit) | Immediate retry (max 1) → DLQ | - Dead-letter queue (DLQ) for manual/scheduled replay | Exactly-once processing patterns | - Poison pills → isolate DLQ processing - Backpressure → apply rate limiting |
| Cache (Redis/Memcached) | No retry (timeout ≤ 50ms) | - Cache miss → source-of-truth DB - Return stale (if versioned) | N/A | - Cache stampede → use mutex/fail-fast - Serialization errors → skip & log |
| 3rd-Party SaaS (Stripe, Twilio) | Retry only on 429/5xx (max 3) with jitter | - Queue async job - Alternate provider (if multi-provider) | Compensating transaction (refund, revert) | - Webhook verification → verify signature even on fallback - At-least-once delivery |
| Internal gRPC/HTTP | Retry on 429/5xx (max 2) with jitter | - Default value - Feature flag disable | Optional (if part of saga) | - Chain failures → circuit breaker per target service - Payload size → compress |
3. Pattern Details & Configuration
3.1 Retry Strategy Template
max_attempts: 3
backoff:
initial_interval_ms: 100
multiplier: 2.0
max_interval_ms: 2000
jitter: true # Add random ±20%
retry_on:
- 429 # Rate limit
- 500 # Server error
- 502 # Bad gateway
- 503 # Service unavailable
- 504 # Gateway timeout
ignore_retry_on:
- 400 # Client error (unless specified)
- 401 # Unauthorized (no retry)
- 403 # Forbidden
- 404 # Not found (unless transient)
Note: For payment-related APIs, zero retries on 4xx except 429.
3.2 Fallback Implementation Guide
| Fallback Type | Implementation | When to Use |
|---|
| Static Default | Return hardcoded value (e.g., 0, [], "N/A") | Non-critical metrics, feature flags, optional fields |
| Stale Cache | Return previous successful response (with X-Cache-Fallback: true header) | Read-heavy APIs where eventual consistency is acceptable (e.g., user profile) |
| Alternate Provider | Switch to backup service (e.g., AWS S3 → Google Cloud Storage via policy) | Multi-cloud, payment gateway redundancy |
| Queue & Defer | Persist to durable DB/queue, process later via worker | Write operations during dependency outage (e.g., audit logs, analytics) |
| Graceful Degradation | Disable non-essential features (e.g., hide recommendations) | Frontend-facing APIs where partial functionality is better than error |
3.3 Compensation (Saga) Patterns
Use only for distributed transactions spanning multiple services/databases.
| Saga Style | Use Case | Example |
|---|
| Choreography | Event-driven, no central coordinator | Order created → inventory reserved → payment processed → ship (if all succeed) |
| Orchestration | Central saga orchestrator (state machine) | Travel booking: flight → hotel → car (compensate car if flight fails) |
| Compensating Action | Idempotent reversal (refund, release lock, delete) | POST /compensate with transaction_id, reason, idempotency_key |
Compensation Rules:
- Must be idempotent (safe to retry).
- Should have timeout (compensation window).
- Log all compensations for audit.
- Never retry compensation automatically after final failure—alert human.
4. Dependency-Specific Playbooks
4.1 SQL Database (Primary)
- Retry: On deadlock (
40001) or timeout → exponential backoff (max 3).
- Fallback:
- Read: Query read-replica (if lag < 5s).
- Write: Buffer to local queue (if >100ms latency) → alert.
- Compensation: Use DB transaction rollback within service (avoid distributed saga for single DB).
4.2 External Payment API (e.g., Stripe)
- Retry: Only on
429 or 5xx (max 3, 1s apart). Never retry 402 (card declined).
- Fallback:
- Queue payment job with
payment_retry state.
- Show user: “Payment processing, check email shortly.”
- Compensation:
- If payment succeeded but fulfillment failed → trigger refund via
compensate_endpoint.
- Store
external_payment_id for traceability.
4.3 Third-Party Email Service (SendGrid)
- Retry: On
429/5xx (max 2, 2s apart).
- Fallback:
- Switch to SES (if configured).
- Buffer to
email_jobs table (process later via worker).
- No Compensation: Email is “fire-and-forget” (unless transactional with SLA).
4.4 Internal Microservice via gRPC
- Retry: Configurable per method (idempotent GET/PUT → retry; POST → no retry).
- Fallback:
- Return cached response (per
Cache-Control).
- Feature flag: disable dependent UI component.
- Circuit Breaker:
- Failure threshold: 50% errors over 20 requests.
- Half-open: allow 5 test requests after 10s wait.
5. Anti-Patterns to Avoid
- 🔴 Unbounded retries → always cap attempts.
- 🔴 Retrying on 4xx (non-429) → likely client error, won’t resolve.
- 🔴 Fallback to same dependency → “cache fallback” must be from a separate source (e.g., CDN, local cache).
- 🔴 Compensating without idempotency → risks double refunds/double sends.
- 🔴 Silent fallback → always log
X-Resilience: fallback header/metric.
6. Monitoring & Alerts
| Metric | Threshold (Example) | Alert |
|---|
fallback_rate{dependency="db"} | > 5% for 2 min | P1: Check DB health, replicas |
retry_count_total | Spike > 3σ from baseline | P2: Investigate downstream latency/errors |
circuit_breaker_state | OPEN for > 30s | P1: Critical outage |
compensation_triggered_total | Any non-zero | P2: Business impact (e.g., refunds, order cancellations) |
dlq_messages_unprocessed | > 100 | P2: Worker failure or persistent errors |
Dashboards:
- Resilience score =
(success_requests / total_requests) * (1 - fallback_rate)
- Top dependencies by retry/fallback volume.
7. Testing Strategy
- Chaos Testing:
- Inject latency (Toxiproxy:
latency(5000)).
- Kill dependencies (kill -9 on DB pod).
- Return error codes (500, 429).
- Contract Testing:
- Validate fallback schemas (e.g., stale cache response matches contract).
- Load Testing:
- Ramp to failure threshold → confirm circuit breaker trips.
8. Implementation Checklist
9. Sample Configuration Snippet (YAML)
dependencies:
stripe_api:
timeout_ms: 3000
retry:
max_attempts: 3
retry_on: [429, 500, 502, 503]
backoff: { initial: 100, multiplier: 2, max: 2000, jitter: true }
fallback:
strategy: queue_and_defer
queue: "payment_retry_queue"
response: "Payment queued for processing"
circuit_breaker:
failure_threshold: 5
wait_duration_sec: 60
redis_cache:
timeout_ms: 50
retry: { max_attempts: 0 } # Never retry
fallback:
strategy: stale_cache
max_stale_sec: 300
Owner: SRE Team
Last Updated: [DATE]
Review Cycle: Quarterly or after major incident.
This playbook is a template. Adapt timeouts, thresholds, and fallbacks based on your SLA, data criticality, and dependency benchmarks.