Skip to main content

Scenario: Netflix Cascading Failure

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"A downstream authentication service slows from 50ms to 8 seconds. Your API tier starts failing health checks. Walk through what happens and how you contain it."

2. Real-World Context​

DimensionDetail
Company / systemNetflix — microservices at massive scale; pioneered Hystrix circuit breakers
ScaleThousands of services; correlated failures during dependency degradation; edge + origin tiers
Why architects careRoot cause is often small (one dependency); blast radius is large due to thread pool exhaustion and retry amplification
Public referencesNetflix tech blog on resilience; Nygard Release It!; Chaos Monkey

AWS deployment context​

Typical Netflix-style streaming API on AWS: ECS Fargate or EKS microservices behind ALB; Amazon ElastiCache Redis for session/token cache; Amazon DynamoDB or Aurora for entitlements; AWS App Mesh or Envoy sidecars for timeouts/retries; CloudWatch + X-Ray for SLO burn detection; AWS FIS for chaos experiments.

Step-by-step flow:

StepActionExplanation
1User requestClient opens home screen; BFF must validate session via Auth.
2DNS routeRoute 53 latency-based routing to nearest region.
3ALB routeALB forwards to healthy API task (initially all appear healthy).
4BFF calls authSynchronous GET /auth/validate on critical path — no timeout configured.
5Thread blocks 8sAuth p99 latency spikes; API worker thread held for full 8s per request.
6Cache missRedis session cache cold or TTL expired — every request hits Auth.
7DB lookupAuth itself slow on DynamoDB — compounds latency.
8Health failThread pool saturated → health endpoint times out → ALB marks instance unhealthy.

3. Step-by-Step Interview Answer​

Minutes 0–5: Scope​

  1. Symptom: Auth p99 goes 50ms → 8s; API error rate climbs over 5–10 minutes.
  2. Constraint: Users must still browse catalog (degrade auth-heavy features).
  3. Non-goal: Fix auth root cause in this answer (focus containment).
  4. Assumption: Clients retry on 5xx; upstream services use default HTTP client (no retry budget).

Minutes 5–15: Failure propagation​

Step-by-step flow:

StepActionExplanation
1RequestClient loads home screen; BFF requires auth validation.
2ForwardALB routes to API instance with available capacity.
3Acquire threadServlet/worker thread assigned from fixed pool (e.g. 200).
4Sync auth callBlocking HTTP call to Auth — no timeout or timeout > 8s.
5Pool exhaustAll 200 threads blocked waiting on Auth; queue backs up.
6Health fail/health cannot get a thread → ALB marks instance unhealthy.
7Drain instanceALB stops sending traffic to API-1; load shifts to survivors.
8Retry stormClients + upstream services retry failed requests — amplifies Auth load.
9Survivors saturateRemaining instances exhaust → metastable failure — won't self-heal when Auth recovers.

Cascade summary (say aloud):

PhaseStepWhat happens
T+01Auth latency spikes (DB hotspot, GC pause, deploy bug)
T+2 min2–3API threads block; latency climbs; error rate still low
T+5 min4–5Thread pools full; new requests queue or timeout
T+7 min6–7Health checks fail; ALB removes instances
T+10 min8–9Retry storm; survivors fail; total API outage despite Auth still serving (slowly)

Step-by-step flow:

StepActionExplanation
1–2Route trafficALB distributes across API fleet.
3Concentrate loadAs instances fail health checks, survivors get more traffic.
4–6Blocked callEvery API thread waits on slow Auth — fan-in bottleneck.
7–8Health failSaturated instances removed from rotation — negative feedback loop.
9Retry stormRetries add ~30–300% extra load on already-failing tier.

Minutes 15–30: Containment layers​

LayerMechanismEffect
1. TimeoutAuth call timeout 200msFail fast; free threads immediately
2. Circuit breakerOpen after 50% errors in 10s windowStop calling sick dependency
3. BulkheadSeparate thread pool for auth vs. catalogCatalog survives auth saturation
4. Retry budgetMax 1% of traffic retriesPrevent retry storm
5. Load shedReturn 503 for non-critical pathsProtect core tier
6. DegradeAllow cached session / read-only modePartial UX vs. total outage

Step-by-step flow:

StepActionExplanation
1Single pool (before)Auth slowness consumes all threads — catalog dies too.
2Bulkhead splitCatalog pool isolated — home/browse keeps working.
3Circuit breakerAfter error threshold, fail fast without calling Auth.
4Cache fallbackServe stale session from Redis — degraded but available.
5Fast failReturn 401/503 in <5ms instead of blocking 8s.

Minutes 30–45: Operations​

  • Detect: SLO burn rate on API; thread_pool_active / thread_pool_max > 0.9; auth latency histogram shift; circuit breaker state = OPEN.
  • Respond: Manually trip circuit breaker fleet-wide; scale Auth horizontally; reduce retry limits in platform SDK; enable read-only degradation mode.
  • Prevent: Chaos experiments (latency injection on auth); default timeouts in service mesh; retry budgets in platform SDK; bulkhead enforcement in golden-path library.
  • Org: Platform team owns resilience libraries (Hystrix → Resilience4j / Envoy); exceptions via ADR.

Step-by-step flow:

StepActionExplanation
1Normal operationCircuit CLOSED — all auth calls pass through.
2Trip openSliding window detects sustained failures → OPEN.
3Cooldown30s pause — let dependency recover; no calls sent.
4Probe successSingle canary request succeeds → CLOSED.
5Probe failsRe-open immediately — dependency still sick.
6Fast-failOPEN state returns fallback in <1ms — threads freed.

4. Whiteboard Guide​

Draw left-to-right:

  1. Client → ALB → API tier (shade thread pool filling red)
  2. API → Auth (label arrow "8s blocking, no timeout")
  3. Show negative feedback loop: health fail → drain → concentrate → exhaust
  4. Add circuit breaker on Auth arrow — label "OPEN"
  5. Show bulkhead as separate pool: "catalog reads" vs "auth calls"
  6. Add Redis cache bypass path for degraded mode

AWS whiteboard layout​

Step-by-step flow:

StepActionExplanation
1Sync pathClient → CloudFront → ALB → BFF — auth on critical path.
2Auth dependencyBlocking call — FAILURE zone when Auth slows.
3BulkheadCatalog reads use separate thread pool.
4Circuit breakerTrip open when error rate exceeds threshold.
5DegradeRedis cached session or anonymous browse mode.

5. Principal-Level Signals​

  • Names metastable failure and why recovery isn't automatic when Auth heals
  • Quantifies retry amplification (1% retry × 10K RPS = +100 RPS; × 3 retries = +300 RPS on Auth)
  • Separates root cause fix (Auth DB hotspot) from containment (circuit breaker)
  • Mentions chaos engineering as validation, not heroics
  • Explains bulkhead vs circuit breaker — bulkhead limits resource sharing; breaker stops calls entirely
  • Discusses health check design — deep health checks that call dependencies cause cascading unhealthiness

6. Red Flags​

  • "Scale API horizontally" without fixing blocking — adds more threads that also block on Auth
  • Infinite retries with exponential backoff only — backoff helps but doesn't cap total retry budget
  • No bulkhead between critical and optional dependencies
  • Health check calls Auth synchronously — unhealthy Auth makes entire API fleet unhealthy
  • Circuit breaker per-instance only — need fleet-wide coordination or low threshold to trip quickly

7. Follow-Up Questions​

QuestionStrong answer
Why doesn't Auth recovering fix the API tier?Metastable state — queues full, clients still retrying, cold thread pools need drain + circuit half-open probes
Half-open vs closed?Half-open sends probe traffic (1–3 requests) before fully closing circuit
Where to put timeout — client or mesh?Both — mesh enforces platform default (200ms); client can be stricter for UX
How do you test this?Chaos: inject 8s latency on Auth in staging; verify catalog still loads with bulkhead
gRPC vs HTTP blocking?gRPC async doesn't eliminate cascade — semaphore/concurrency limits still required

9. Practice Drill​

Draw the cascade on paper in 5 minutes. Label steps 1–9. Explain containment in 10 minutes without notes. Then whiteboard the circuit breaker state machine from memory.


10. Production High-Level Design​

This section is a build guide for implementing Netflix-style cascading-failure containment in production on AWS.

10.1 Architecture diagram index​

SectionTopic
§2End-to-end AWS deployment context
§3Failure propagation sequence
§10.2C4 logical context
§10.3Full VPC production stack
§10.4Containment layer stack
§11.4BFF request path sequence
§11.5Circuit breaker state machine + config
§12Multi-AZ, regional failover
§13AWS FIS chaos experiments
§14Security + observability
§156-week rollout
§16Load + chaos testing
§17Production readiness gates

10.2 System context (C4 Level 1)​

Logical view — technology-agnostic component boundaries.

Step-by-step flow:

StepActionExplanation
1IngressClients fetch static UI from CDN.
2API callsDynamic requests hit API Gateway / BFF.
3AggregateBFF composes home screen from multiple services.
4Auth checkSession validation on critical path — cascade risk.
5CatalogCatalog reads can be bulkheaded separately from auth.
6CacheRedis holds hot session tokens — reduces Auth fan-in.
7EntitlementsDynamoDB stores subscription state — Auth dependency.

10.3 AWS production architecture (full stack)​

Step-by-step flow:

StepActionExplanation
1EdgeCloudFront terminates TLS; caches static responses.
2WAF filterBot control, geo block, rate limiting.
3DNS healthRoute 53 fails over if regional ALB unhealthy.
4ALB routeCross-AZ load balance to BFF tasks.
5BFF invokeBFF aggregates home screen; calls Auth synchronously.
6Auth callCritical dependency — must have timeout + circuit breaker.
7Session cacheRedis GET session — miss falls through to Auth DB.
8User lookupDynamoDB GetItem for entitlements.
9CatalogParallel bulkheaded call — survives Auth degradation.
10Policy enforceApp Mesh enforces 200ms timeout, retry budget, circuit breaker.
AWS componentResilience responsibility
ALBHealth checks on shallow /health (not Auth); connection draining on deregister
ECS FargateTask-level thread pools; circuit breaker in app or sidecar
App MeshPlatform-enforced timeouts, outlier detection, retry policies
ElastiCache RedisSession cache for degraded-mode fallback
DynamoDBAuth backing store — on-demand scales; DAX optional for hot keys
CloudWatchThreadPoolActive, CircuitBreakerState, SLO burn alarms
AWS FISInject Auth latency in staging/prod game days

10.4 Containment architecture (layers)​

Step-by-step flow:

StepActionExplanation
1EnterRequest hits BFF; passes through containment stack in order.
2Trip checkCircuit breaker — fast-fail if OPEN.
3Pool selectBulkhead routes to catalog or auth pool.
4Retry gateRetry only if budget allows (≤1% of RPS).
5Shed checkNon-critical paths return 503 immediately under pressure.
6FallbackServe degraded UX from Redis cache or anonymous mode.

10.5 Service sizing at 10K RPS peak​

MetricValueReasoning
Peak BFF RPS10KMid-size streaming API
Auth calls per home load1Session validate on critical path
Auth p99 (healthy)50msBaseline
Auth p99 (degraded)8sIncident scenario
BFF thread pool200 / instanceTomcat / Netty worker threads
BFF instances2010K RPS ÷ 500 RPS/instance
Time to exhaust (no timeout)~2 min200 threads × 8s = 25 RPS capacity vs 500 RPS demand

Step-by-step flow:

StepActionExplanation
1Demand10K RPS hits BFF during peak evening traffic.
2CapacityWith 8s Auth latency, each thread handles 0.125 RPS.
3Deficit95% of requests queue or timeout — cascade in minutes.

11. Production Low-Level Design​

11.1 API contract — BFF home endpoint​

Endpoint: GET /v1/home

Required headers:

HeaderRule
AuthorizationBearer <session_token>
X-Request-IDUUID for distributed tracing
X-Client-VersionApp version for degradation routing

Response semantics (degradation modes):

HTTPMeaningClient action
200Full home screen (auth + catalog + recommendations)Render normally
200 + X-Degraded: authCatalog only; recommendations omittedShow banner "personalization unavailable"
401Session invalid (circuit OPEN, cache miss)Redirect to login
503 + Retry-After: 30Load shed — system under pressureBackoff; do not retry more than 2×
504BFF timeout (auth + catalog > 500ms budget)Show cached home if available

11.2 Thread pool and bulkhead configuration​

application.yml (Spring Boot + Resilience4j example):

resilience4j:
thread-pool-bulkhead:
instances:
catalogBulkhead:
max-thread-pool-size: 150
core-thread-pool-size: 50
queue-capacity: 100
authBulkhead:
max-thread-pool-size: 50
core-thread-pool-size: 20
queue-capacity: 25

circuitbreaker:
instances:
authService:
sliding-window-size: 100
failure-rate-threshold: 50
wait-duration-in-open-state: 30s
permitted-number-of-calls-in-half-open-state: 3
slow-call-rate-threshold: 80
slow-call-duration-threshold: 200ms

timelimiter:
instances:
authService:
timeout-duration: 200ms

retry:
instances:
authService:
max-attempts: 2
wait-duration: 50ms
retry-exceptions:
- java.net.SocketTimeoutException
ParameterValueWhy
authBulkhead.max-thread-pool-size50Caps auth fan-in — catalog pool unaffected
failure-rate-threshold50%Trip after half of sliding window fails
slow-call-duration-threshold200msTreat slow calls as failures — trip before 8s
wait-duration-in-open-state30sCooldown before half-open probes
max-attempts2One retry max — prevents retry storm

11.3 HTTP client configuration​

// OkHttp client for Auth service calls
OkHttpClient authClient = new OkHttpClient.Builder()
.connectTimeout(Duration.ofMillis(100))
.readTimeout(Duration.ofMillis(200))
.writeTimeout(Duration.ofMillis(100))
.connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
.addInterceptor(new RetryBudgetInterceptor(maxRetryPercent = 0.01))
.build();
SettingValueFailure prevented
readTimeout200msThread blocked 8s on slow Auth
connectionPool max50Connection exhaustion to Auth
RetryBudgetInterceptor1% fleet capRetry storm amplification

11.4 BFF request handler — step-by-step (low level)​

AWS request path — end to end:

Step-by-step flow:

StepActionExplanation
1GET /v1/homeClient requests home screen composition.
2Cache missCloudFront forwards dynamic API to ALB.
3Route to taskALB picks healthy BFF task with capacity.
4GET sessionCheck Redis for cached session validation.
5aCache hitSkip Auth entirely — fast path during incident.
5bCache missMust validate; check circuit breaker state first.
6Auth validateCLOSED: call Auth with 200ms timeout.
6bFast-failOPEN: skip Auth; degrade to catalog-only mode.
7ResponseAuth returns entitlements or times out → counts as failure.
8Cache writeOn success, cache session for 300s — reduces Auth fan-in.
9Catalog fetchParallel call on separate bulkhead pool.
10Catalog rowsHome metadata from Catalog service.
11Home JSONBFF composes and returns response to client.

11.5 Circuit breaker implementation​

Handler pseudocode:

def validate_session(token: str) -> SessionResult:
# Step 1: Check circuit breaker state
if auth_circuit.state == OPEN:
cached = redis.get(f"session:{token}")
if cached:
return SessionResult(degraded=True, data=cached)
raise AuthUnavailableError() # fast-fail < 1ms

# Step 2: Attempt auth with timeout (bulkhead pool)
try:
with auth_bulkhead.acquire(timeout=0.05):
response = auth_client.get(
"/validate",
headers={"Authorization": f"Bearer {token}"},
timeout=0.2,
)
except (Timeout, CircuitOpen, BulkheadFull):
auth_circuit.record_failure()
return fallback_session(token)

# Step 3: Cache success + record metrics
auth_circuit.record_success()
redis.setex(f"session:{token}", 300, response.json())
return SessionResult(degraded=False, data=response.json())

Step-by-step flow (code path):

StepActionExplanation
1Check CB stateOPEN → skip Auth call entirely.
2Bulkhead acquireWait max 50ms for auth pool slot; reject if full.
3HTTP call200ms read timeout — fail fast, free thread.
4Record failureTimeout/error increments sliding window toward OPEN.
5FallbackReturn cached session or degraded catalog-only mode.
6Cache successWrite-through to Redis — reduce future Auth load.

11.6 Health check design​

Anti-pattern (causes cascade):

GET /health
→ calls Auth /validate synchronously
→ Auth slow → all BFF instances unhealthy → total outage

Correct pattern — shallow liveness:

GET /health/live → 200 if process up + thread pool < 95%
GET /health/ready → 200 if can accept traffic (bulkhead has capacity)
GET /health/deep → calls Auth — for monitoring only, NOT used by ALB
CheckALB uses?Calls Auth?Purpose
/health/liveYesNoProcess alive; thread pool not saturated
/health/readyOptionalNoBulkhead has queue capacity
/health/deepNoYesDashboard / synthetic monitoring only

11.7 Retry budget (fleet-wide)​

Step-by-step flow:

StepActionExplanation
1Client retryMobile app retries on 503 — must be capped.
2Upstream retryOther services retry BFF calls — compounds load.
3Check budgetToken bucket: max 100 retry RPS fleet-wide.
4AllowRetry proceeds if budget has tokens.
5RejectReturn 429 — forces client backoff.

Retry amplification math:

SourceRPSRetry rateExtra load
Clients10,0003% × 2 retries+600 RPS
Upstream services2,0005% × 1 retry+100 RPS
Total amplification+700 RPS on Auth

11.8 App Mesh policy (Envoy sidecar)​

# AWS App Mesh virtual node — auth dependency
spec:
listeners:
- portMapping:
port: 8080
protocol: http
timeout:
perRequest:
value: 0.2 # 200ms
backends:
- virtualService:
virtualServiceName: auth-service
connectionPool:
http:
maxConnections: 50
maxPendingRequests: 25
outlierDetection:
maxServerErrors: 5
interval: 10s
baseEjectionTime: 30s
maxEjectionPercent: 50
PolicyValueEffect
perRequest.timeout200msPlatform-enforced — apps can't override without ADR
maxConnections50Connection bulkhead to Auth per task
outlierDetection5 errors / 10sEnvoy-level circuit breaker

12. HA/DR and Failover​

12.1 Single-region multi-AZ (baseline)​

Step-by-step flow:

StepActionExplanation
1–3RouteALB distributes across 3 AZs — survives single AZ loss.
4Auth callPrefer same-AZ Auth via locality routing (optional).
5–6ReplicateRedis cluster mode — automatic failover on node loss.

Cascading failure interaction: Multi-AZ does not prevent cascade — it only survives AZ hardware failure. Auth slowness affects all AZs simultaneously.

12.2 Regional failover​

Step-by-step flow:

StepActionExplanation
1Health check failRegional ALB health degrades as BFF fleet exhausts.
2Failover DNSRoute 53 shifts traffic to healthy region.
3West healthyWest region Auth + BFF operating normally.
4Regional recoveryUsers in failover region get full service.

Caution: Failover does not fix metastable East — drain connections, reset circuit breakers, clear retry queues before re-admitting traffic.

12.3 Recovery runbook (metastable failure)​

StepActionOwnerDuration
1Confirm Auth root cause identified (or still investigating)Auth team—
2Manually OPEN circuit breaker fleet-wide on BFFPlatform SRE2 min
3Enable degraded mode (X-Degraded: auth catalog-only)BFF team1 min
4Reduce client retry rate via feature flag (SSM Parameter)Client platform5 min
5Scale Auth horizontally (if CPU-bound)Auth team10 min
6Wait for BFF thread pools to drain (no new Auth calls)—5–15 min
7HALF_OPEN probe — 3 canary requests to AuthSRE1 min
8CLOSE circuit breaker; re-enable full home screenSRE2 min
9Post-incident: verify retry budget metrics returned to baselineSRE30 min

13. Chaos Engineering and Validation​

13.1 AWS FIS experiment — Auth latency injection​

Step-by-step flow:

StepActionExplanation
1Start experimentFIS adds 8s latency to Auth tasks in staging.
2ObserveCatalog latency must stay < 500ms — bulkhead proof.
3Trip CBCircuit opens within 30s of slow-call threshold.
4Bulkhead holdsBFF /health/live stays 200 — shallow health check.
5Degrade worksClients receive catalog-only home with X-Degraded: auth.

13.2 Chaos experiment catalog​

ExperimentInjectionPass criteria
Auth latency 8sFIS network latencyCatalog unaffected; CB opens
Auth 100% errorFIS HTTP 500Fast-fail < 5ms; no thread exhaustion
Auth complete downScale Auth to 0Degraded mode; no cascade
Retry stormLoad test 3% retry rateRetry budget caps at 1%
AZ failureFIS terminate AZ-aALB reroutes; no user impact
Metastable recoveryLatency injection → heal → verifyManual CB reset required

14. Security, Observability, and Operations​

14.1 Security architecture​

TopicImplementation
Session tokensShort-lived JWT; Redis encrypted at rest (KMS)
Degraded modeNever bypass entitlements for paid content — catalog-only is safe
Rate limitWAF + per-client token bucket on BFF
Circuit breaker adminManual trip requires break-glass IAM role + CloudTrail audit

14.2 Observability architecture​

Required metrics:

MetricAlert thresholdWhy
bff_thread_pool_active_ratio> 0.9 for 2 minCascade imminent
auth_circuit_breaker_stateOPEN for > 5 minSustained Auth degradation
auth_client_latency_p99> 200ms for 1 minSlow-call threshold breach
retry_budget_utilization> 80%Retry storm building
degraded_response_rate> 10%User-visible degradation
catalog_bulkhead_rejected> 0Catalog pool saturated — escalate

Structured log (every auth call):

{
"request_id": "req_8f3a",
"auth_outcome": "success|timeout|circuit_open|bulkhead_rejected",
"auth_latency_ms": 45,
"circuit_state": "CLOSED",
"degraded": false,
"bulkhead_pool": "auth"
}

15. Implementation Roadmap (6-Week Rollout)​

WeekDeliverableAWS services
1Timeouts + shallow healthALB, ECS, CloudWatch
2Circuit breaker + bulkheadECS, Resilience4j library
3Session cache + degraded modeElastiCache Redis
4Mesh policies + retry budgetApp Mesh, SSM Parameter Store
5Chaos experimentsAWS FIS, staging VPC
6Game day + production gatesCloudWatch dashboards, PagerDuty

16. Testing Strategy​

Test typeToolScenario
UnitJUnit / pytestCircuit breaker state transitions
IntegrationTestcontainersAuth timeout → fallback path
Loadk6 / Gatling10K RPS with 3% client retry
ChaosAWS FIS8s Auth latency injection
Game dayManual + FISFull metastable recovery runbook

Load test pass criteria:

MetricThreshold
Catalog p99 during Auth degradation< 500ms
BFF error rate< 0.1% (excluding degraded 200s)
Thread pool saturation< 80% on catalog bulkhead
Circuit breaker trip time< 30s from injection start

17. Architecture Review Checklist​

#GateStatus
1Every outbound HTTP call has explicit timeout ≤ 200ms☐
2Circuit breaker on all synchronous dependencies☐
3Bulkhead separates critical vs optional dependency pools☐
4ALB health check does NOT call downstream dependencies☐
5Retry budget caps fleet-wide retry rate ≤ 1%☐
6Degraded mode defined and tested for each critical dependency☐
7Redis session cache with TTL + encryption at rest☐
8FIS chaos experiment passes in staging☐
9Metastable recovery runbook documented and drilled☐
10Dashboards: thread pool, CB state, retry budget, degraded rate☐
11App Mesh / sidecar enforces platform timeout defaults☐
12Post-incident: Auth latency injection in CI pipeline (weekly)☐