# Resilience Patterns

Resilience patterns help systems survive and recover from failures — partial outages, network hiccups, overloaded dependencies, and cascading errors. They operate on the principle that failures are inevitable, and software must be designed to handle them gracefully.

## Pattern Comparison

| Pattern | Purpose | Scope | Complexity |
|---------|---------|-------|------------|
| **Circuit Breaker** | Stop calling a failing service; let it recover | Per-dependency | Medium |
| **Retry** | Reattempt transient failures with backoff | Per-call | Low |
| **Bulkhead** | Isolate failures so they don't cascade | Per-resource | Medium |
| **Saga** | Coordinate distributed transactions with compensation | Cross-service | High |
| **Rate Limiter** | Throttle request throughput | Per-client / global | Low–Medium |
| **Timeout** | Bound how long a call can block | Per-call | Low |
| **Fallback** | Provide degraded functionality on failure | Per-call | Low |

## Decision Guide

```
Is the remote service flaky?
├─ Yes → Circuit Breaker + Retry
│        Add Timeout to bound each attempt
│        Add Fallback for graceful degradation
└─ No  → Could it become overloaded?
         ├─ Yes → Rate Limiter + Bulkhead
         └─ No  → Is there a multi-step workflow?
                  ├─ Yes → Saga
                  └─ No  → Timeout + Fallback as baseline
```

## Combining Patterns

Resilience patterns compose well. A typical call stack:

```
Rate Limiter
  └─ Timeout
       └─ Circuit Breaker
            └─ Retry (with backoff)
                 └─ Bulkhead (isolated pool)
                      └─ Actual call
                           └─ Fallback (on any failure)
```

## Key Principles

1. **Fail fast** — Don't waste resources on calls that will likely fail.
2. **Fail gracefully** — Return something useful even when degraded.
3. **Isolate failures** — One bad dependency must not bring down everything.
4. **Recover automatically** — Systems should self-heal without manual intervention.
5. **Observe everything** — Metrics and logs are essential for tuning thresholds.
