Building Fault Tolerance and Resilience

1. Implementing Circuit Breaker Pattern

                  failures >= threshold
   ┌─────────┐  ─────────────────────▶  ┌──────┐
   │ CLOSED  │                          │ OPEN │
   │ (pass)  │  ◀─────────────────────  │ (fail│
   └─────────┘   success in HALF-OPEN   │ fast)│
        ▲                               └──────┘
        │  success                          │
   ┌────┴─────┐                             │ after timeout
   │HALF-OPEN │  ◀──────────────────────────┘
   │(probe)   │
   └──────────┘
        
StateBehavior
CLOSEDRequests pass; count failures
OPENReject immediately
HALF-OPENAllow test requests; success → CLOSED
LibrariesResilience4j, Hystrix (deprecated), Polly, sentinel

Example: Resilience4j circuit breaker

CircuitBreakerConfig config = CircuitBreakerConfig.custom()
    .failureRateThreshold(50)
    .slowCallDurationThreshold(Duration.ofSeconds(2))
    .waitDurationInOpenState(Duration.ofSeconds(30))
    .slidingWindowSize(20)
    .build();

CircuitBreaker cb = CircuitBreaker.of("paymentService", config);
Supplier<Payment> safe = CircuitBreaker.decorateSupplier(cb, () -> client.charge());
Payment result = Try.ofSupplier(safe).recover(t -> fallback()).get();

2. Implementing Retry Strategies

StrategyFormulaUse
Fixed delaydelay = cPredictable
Lineardelay = c × nMild backoff
Exponentialdelay = base × 2^nStandard
Exponential + jitterrandom(0, base × 2^n)Avoids thundering herd
Decorrelated jitterrandom(base, prev × 3)AWS recommendation
Warning: Only retry idempotent or retry-safe operations; do not retry 4xx errors.

3. Implementing Timeout Strategies

TypeDetail
Connect timeoutTime to establish TCP/TLS
Request timeoutBound total call
Read/idle timeoutInter-byte gap
Deadline propagationgRPC deadline header — passed downstream
Budget-basedRemaining budget split among hops

4. Implementing Bulkhead Pattern

VariantDetail
Thread pool isolationPer-dependency pool prevents pool exhaustion spreading
SemaphoreCap concurrent calls per dependency
Process / container isolationSeparate deployments
Network bulkheadPer-tenant queues / rate limits

5. Implementing Failover Mechanisms

TypeTrigger
Active-passiveStandby promoted on health loss
Active-activeTraffic redistributed
DNS failoverTTL-bounded; Route 53 health checks
AnycastBGP withdraws unhealthy region

6. Implementing Graceful Degradation

TacticDetail
Fallback valuesStale cache, default config
Feature toggle offDisable non-essential features
Read-only modeReject writes; serve reads
Reduced fidelityLower-res images, skip recommendations

7. Implementing Chaos Engineering Practices

ToolCapability
Chaos MonkeyRandom instance termination
Chaos MeshK8s-native; pod, network, IO faults
LitmusK8s chaos workflows
GremlinCommercial, broad fault injection
AWS FISManaged fault injection

8. Understanding Failure Detection Mechanisms

MechanismDetail
Heartbeat / pushPeriodic alive signal
Probe / pullHealth check ping
Phi accrualAdaptive suspicion level
SWIMIndirect probe via peers
Outlier detectionStatistical (Envoy)

9. Implementing Self-Healing Systems

ComponentAction
Liveness probeRestart container on failure
Auto-scalingReplace unhealthy instances (ASG)
Operator patternReconcile desired vs actual state
Rolling restartPeriodic restart to mitigate leaks

10. Handling Cascading Failures

CauseMitigation
Retry stormLimit retries; jittered backoff
Synchronous couplingAsync messaging; circuit breaker
Resource exhaustionBulkhead; admission control
Saturated dependencyLoad shedding; degrade gracefully
DNS / config flapTTL caching; gradual rollout

11. Implementing Rate Limiting and Throttling

AlgorithmBehavior
Token bucketBursts allowed up to bucket size; refills at rate
Leaky bucketSmooths to constant outflow
Fixed windowN reqs per minute; boundary spikes
Sliding window logPrecise; memory per request
Sliding window counterApproximation; common in practice
Distributed (Redis)INCR + EXPIRE; Lua scripts