The user wants a "backend resilience playbook."
This playbook needs to map specific resilience strategies (Fallbacks, Retries, Compensations) to backend dependencies.
1. Deconstruct the Request:
Goal: Create a backend resilience playbook.
Scope: Map strategies per dependency.
Key Strategies:
Fallbacks: What happens when the primary action fails? (Alternative logic, cached data, default values).
Retries: How to handle transient failures? (Exponential backoff, jitter, max attempts).
Compensations: How to undo side effects if a process fails partially? (Sagas, undo logic).
2. Target Audience/Context:
Backend Engineers / DevOps / SREs.
The context is likely a microservices architecture or a modular monolith with external integrations (DBs, APIs, Queues).
The tone should be professional, structured, and actionable (like a runbook or a design doc).
3. Structure of the Playbook:
A good playbook isn't just a list; it's a matrix. I should organize it by "Dependency Type" because generic rules often apply (e.g., all 3rd party APIs should have circuit breakers).
Introduction: Briefly define the pillars (Retry, Fallback, Compensation).
The Matrix/Table: This is the core deliverable. I need columns for:
Dependency Type
Failure Mode
Retry Strategy
Fallback Strategy
Compensation Strategy
Detailed Scenarios (The "Plays"): Pick specific, common dependencies (Database, Payment Gateway, Email Service, Internal Service) and flesh them out.
Implementation Guidance: Mention libraries (Resilience4j, Hystrix - though dated, Polly, etc.) or patterns (Saga).
4. Drafting the Content - Dependency by Dependency:
Scenario 1: Database (Primary Data Store)
Risk: Connection timeout, deadlock.
Retry: Yes (quick retry for deadlocks, backoff for connection issues).
Fallback: Read replica? Cache? Return error? (Usually, if DB is down, the app is down unless read-heavy).
Compensation: N/A (usually atomic transactions handle this, but for distributed, need Saga).
Scenario 2: External 3rd Party API (e.g., Payment Gateway, Maps)
Risk: Latency, 503, downtime.
Retry: Yes (exponential backoff with jitter).
Fallback: Use cached result (if GET)? Return default "unavailable" widget? Fail fast?
Compensation: If payment succeeds but the callback fails, need idempotency keys or manual reconciliation.
Fallback: Stale data from local cache? Circuit Breaker to prevent cascading failure.
Compensation: Critical. If "Order Service" calls "Inventory" and then "Shipping", and Shipping fails, we must compensate (release inventory).
Scenario 4: Message Queue/Event Bus
Risk: Broker down.
Retry: Native client retries.
Fallback: Persist locally (outbox pattern) to disk to process later.
Compensation: DLQ (Dead Letter Queue).
5. Refining the "Compensation" Aspect:
Compensation is often the hardest part. I need to ensure I distinguish between technical retries (network glitch) and business compensation (undoing a successful step because the next step failed).
Pattern: Saga Pattern (Choreography vs. Orchestration).
6. Formatting the Output:
I'll use a combination of Markdown tables for the high-level view and detailed lists for specific "Plays" to make it readable.
7. Self-Correction/Review during drafting:
Initial thought: Just list code snippets.
Correction: No, a "playbook" is architectural. It defines the rules. Code is implementation. Keep it language-agnostic but mention tools.
Clarification on Retries: Make sure to mention Idempotency. You can't blindly retry POST requests without idempotency keys.
8. Final Polish:
Add a section on "Global Resilience Config" (Timeouts, Circuit Breakers) because those apply to everything.
(Self-Correction during drafting the Matrix):
Instead of just generic "Database", let's split into "Read" vs "Write" because strategies differ (Cache fallback works for Read, not for Write).
This structure looks solid. Proceeding to generate.
This Backend Resilience Playbook provides a structured map for handling failures across common infrastructure dependencies.
Resilience Strategy Matrix
Dependency Type
Failure Scenario
Retry Strategy
Fallback Strategy
Compensation Strategy
Critical DB (Writes)
Connection Timeout / Deadlock
Retry: 3 times Backoff: Exponential (100ms base) Jitter: Full
Fail Fast: Return 503 Service Unavailable. Circuit Breaker: Open after 50% failure rate.
N/A (Transaction failed; state is unchanged).
Read Replica / Cache (Reads)
Connection Refused / Latency
Retry: 1 time (quick)
Stale Data: Serve stale data from Cache if available. Direct Master: Route read to Master DB (risk load).
N/A (Read-only operation).
External API (Idempotent)
5xx Server Error / Rate Limit (429)
Retry: 3 times Backoff: Exponential (1s base) + Jitter
Cached Response: Return last known good response (cached). Default Value: Return generic "Feature Unavailable" object.
N/A (Read-only or accepted eventual consistency).
External API (Non-Idempotent / Side Effects)
Network Timeout / 5xx
Do NOT Retry: Risk of double charge/duplicate action.
Fail Fatal: Return error to user.
State Reversal: Trigger a "Void" transaction if a timeout occurred during a financial commit.
Message Queue (Producer)
Broker Unavailable
Retry: Indefinite (with backoff cap) Pattern: Produce to local DB (Outbox Pattern).
Buffer: Store event in local "Outbox" table; retry via background process when connection restores.
Context: Handling transactions and schema stability.
Retry:
Policy:Retry(3, ExponentialBackoff(100ms)).
Scope: Only retry on ConnectionException, Deadlock, or 404 (Replica Lag). Do not retry on ConstraintViolation or SyntaxError.
Fallback:
Reads: If replica fails, attempt read on primary (accepting higher load).
Writes: None. The system must surface the error to maintain data integrity.
Compensation:
Saga Pattern: If a transaction spans multiple services, publish a TransactionFailed event so other services can undo their local changes.
Code Example:
python
try:
db.commit()
except ConnectionError:
# Manual compensation not needed here as commit failed,
# but alert monitoring is crucial.
raise ServiceUnavailable("Database unreachable")
2. Dependency: Payment Gateway (Stripe/PayPal)
Context: Network boundaries, money, and idempotency.
Retry:
Policy:Retry(2, ExponentialBackoff(500ms)).
Condition: ONLY retry on network timeouts or 503 Service Unavailable.
Idempotency: Every request must include an Idempotency-Key header to allow safe retries without double charging.
Fallback:
Failover: Route to a secondary payment provider (if configured). This usually requires a different API adapter.
Queue: If the provider is down entirely, queue the payment request in a "Pending" state and notify the user "Payment Processing."
Compensation:
The "Zombie" Transaction: If you receive a 200 OK but the network cuts out before you read the response (or a timeout occurs), do not retry immediately.
Action: Query the Payment Gateway API using the Idempotency Key or Transaction ID to check the status.
Refund: If you accidentally processed twice, trigger an automated refund workflow.
3. Dependency: Internal Microservice (Inventory)
Context: Eventual consistency and downstream logic.
Retry:
Policy:Retry(3, ExponentialBackoff(200ms)) wrapped in a CircuitBreaker.
Fallback:
Cached State: If Inventory service is down, rely on a locally cached version of inventory counts (accepting risk of oversell).
Degraded Mode: Disable "Add to Cart" functionality but allow browsing. Return a static "Inventory Check Unavailable" message.
Compensation:
Orchestration: If the Order service succeeds but Inventory fails:
Mark Order as "Pending Inventory".
Alternatively, publish an OrderCancelled event to trigger a refund in Payment service.
4. Dependency: Email Service (SendGrid/SES)
Context: Non-critical path, fire-and-forget.
Retry:
Policy:Retry(5, ExponentialBackoff(1s)).
Fallback:
Local Queue: If the provider is down, persist the email to a local "Email Outbox" table. A background cron job attempts to flush this table every 5 minutes.
User Impact: Do not block the HTTP request (e.g., User Registration) waiting for the email to send. Return success immediately, then send email asynchronously.
Compensation:
None: Generally, you do not "undo" an email sent. If you suspect duplicates were sent due to a bug, log it for customer support to handle.
Global Configuration Parameters
To implement this playbook effectively, apply these global settings to your HTTP clients and Database drivers.
Timeouts:
Connect Timeout: 500ms (Aggressive).
Read/Socket Timeout: 2s - 5s (Context dependent).
Max Lifecycle: 30s (Total request time).
Circuit Breakers:
Threshold: Open circuit after 5 consecutive failures or 50% error volume in 10 seconds.
Sleep Window: Allow 1 test request every 30 seconds to check recovery.
Bulkheads:
Isolate thread pools per dependency. If the Payment API is slow, it should not consume threads needed for the Cache or Database.
Dead Letter Queue (DLQ): If retries exhaust, move to DLQ for manual inspection.
Search Engine (e.g., Elasticsearch)
Cluster Red / Timeout
Retry: 2 times
Defer: Return results from DB without search facets. Circuit Break: Return search disabled UI state.
Re-index: If data corruption suspected, trigger async re-index job from source of truth.