Library

Volume 1 · System Architecture & Distributed Systems

Notebook
Sign in

Section 2

High Availability Patterns

1,768 words · about 8 min

2.1 Definition and the Nines

High Availability (HA) means the system continues operating, without unacceptable interruption, despite the failure of individual components.

Availability = MTTF / (MTTF + MTTR) (Mean Time To Failure / (MTTF + Mean Time To Repair))

Availability Downtime / Year Downtime / Month Typical Tier
99% (“two nines”) 3.65 days 7.3 hours Internal tools
99.9% (“three nines”) 8.7 hours 43.8 minutes Standard SaaS
99.95% 4.4 hours 21.9 minutes Enterprise SLA
99.99% (“four nines”) 52.6 minutes 4.4 minutes Critical business systems
99.999% (“five nines”) 5.3 minutes 26 seconds Telecom, payment rails

Interview Tip: Every extra “nine” costs disproportionately more (multi-region active-active, automated failover, chaos-tested runbooks). Always tie your HA design to the business-stated SLA — don’t over-engineer five-nines for a system that only needs three.

2.2 Active-Active Multi-AZ Architecture

flowchart TD
    DNS["DNS / Global Traffic Manager\n(Route 53 / Azure Front Door)"]
    LB["Layer 7 Cross-Zone Load Balancer\n(ALB / Application Gateway)"]

    subgraph AZ1["Availability Zone 1 (Active)"]
        App1["App Server 1\n(Stateless Container/VM)"]
    end

    subgraph AZ2["Availability Zone 2 (Active)"]
        App2["App Server 2\n(Stateless Container/VM)"]
    end

    subgraph DataTier["Data & State Layer"]
        DB_Primary[("Multi-AZ Database\nPrimary Node (Writes)")]
        DB_Standby[("Multi-AZ Database\nStandby Node (Replication)")]
        Redis[("Distributed Redis Cluster\n(Externalized Session State)")]
    end

    DNS -->|Health-checked Anycast/Geo| LB
    LB -->|Round Robin / Least Conn| App1
    LB -->|Round Robin / Least Conn| App2

    App1 -->|Read / Write| DB_Primary
    App2 -->|Read / Write| DB_Primary
    DB_Primary -.->|Synchronous Replication| DB_Standby

    App1 <-->|Token & Session Lookups| Redis
    App2 <-->|Token & Session Lookups| Redis

Key Architectural Takeaways:

  • RTO Floor: DNS and health-check failover typically completes in 30–60 seconds, which serves as your recovery time objective (RTO) floor unless employing global anycast routing (e.g., AWS Global Accelerator or Cloudflare).
  • Stateless Tier: App servers externalize all state to Redis or the database, enabling seamless instance termination and zero-downtime cross-AZ re-routing.
  • Synchronous DB Replication: Primary and standby nodes replicate synchronously across AZ boundaries, achieving Zero Recovery Point Objective (RPO = 0) at the expense of slight write latency overhead.
  • Avoiding Sticky Sessions: Sticky sessions undermine cross-zone balance during AZ degradation; use centralized distributed tokens (JWT or Redis sessions).

2.3 Circuit Breaker Pattern

Prevents a failing downstream service from cascading into cluster-wide failure by failing fast once error thresholds are met, sparing threads and connection pools.

stateDiagram-v2
    [*] --> Closed
    
    Closed --> Open : Failure threshold exceeded\n(e.g., >50% errors in 30s)
    Closed --> Closed : Requests succeed / Error rate normal
    
    Open --> HalfOpen : Reset timeout / Cooldown expires\n(e.g., after 30s)
    Open --> Open : Calls fail fast (Return fallback / immediate error)
    
    HalfOpen --> Closed : Canary probe requests succeed
    HalfOpen --> Open : Canary probe request fails

State Semantics:

  • Closed: System operates normally. Requests pass through to downstream dependencies. Call metrics and failure ratios are tracked.
  • Open: The failure threshold is breached. Calls immediately fail fast without making network requests, avoiding downstream saturation.
  • Half-Open: A trial period where a limited probe batch is sent downstream to verify whether the dependency has recovered.

Java (Resilience4j):

@CircuitBreaker(name = "paymentService", fallbackMethod = "fallbackPayment")
public PaymentResponse processPayment(PaymentRequest request) {
    return paymentServiceClient.process(request);
}

public PaymentResponse fallbackPayment(PaymentRequest request, Exception ex) {
    // Return cached response or queue for later processing
    return PaymentResponse.queued(request.getOrderId());
}

.NET (Microsoft.Extensions.Http.Resilience, Polly-based):

builder.Services.AddHttpClient<IOrderApiClient, OrderApiClient>(client =>
{
    client.BaseAddress = new Uri("https://orders-api.internal");
})
.AddStandardResilienceHandler(options =>
{
    options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30);
    options.CircuitBreaker.FailureRatio = 0.5;
    options.CircuitBreaker.MinimumThroughput = 5;
    options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
});

Production Impact Case Study:

  • In a high-throughput retail payment pipeline integrating with a third-party banking gateway, downstream latency spikes previously caused connection pool exhaustion across 100% of web worker threads.
  • Deploying a circuit breaker (tripping after 5 consecutive timeouts) reduced thread pool saturation from 100% down to under 5%.
  • Non-payment services (catalog browsing, shopping carts, recommendations) remained 100% available while degraded payment attempts immediately triggered asynchronous queued checkouts.

2.4 Bulkhead Pattern

Derived from the compartmentalized hulls of ships: isolates resource pools (threads, memory, TCP sockets) so that starvation in one downstream dependency cannot exhaust capacity for other critical features.

flowchart TD
    subgraph WithoutBulkhead["Without Bulkhead (Shared Pool Hazard)"]
        SharedPool["Shared Thread Pool (100 Threads)"]
        SlowService["Service B (Slow / Unresponsive)"]
        FastService["Service C (Healthy)"]
        SharedPool -->|100 Threads Blocked| SlowService
        SharedPool -.->|Starved / No Threads Left| FastService
    end

    subgraph WithBulkhead["With Bulkhead (Isolated Compartments)"]
        subgraph PoolB["Service B Pool (30 Threads)"]
            TB["30 Threads Max"]
        end
        subgraph PoolC["Service C Pool (30 Threads)"]
            TC["30 Threads Max"]
        end
        subgraph PoolD["Service D Pool (40 Threads)"]
            TD["40 Threads Max"]
        end
        TB --> SlowService2["Service B (Slow)"]
        TC --> FastService2["Service C (Healthy - Unaffected)"]
        TD --> OtherService["Service D (Healthy - Unaffected)"]
    end
// Isolate a critical payment call from a non-critical notification call
builder.Services.AddHttpClient("PaymentService")
    .AddResilienceHandler("payment-bulkhead", pipeline =>
    {
        pipeline.AddConcurrencyLimiter(new ConcurrencyLimiterOptions
        {
            PermitLimit = 20,   // Max 20 concurrent calls
            QueueLimit = 50
        });
    });

builder.Services.AddHttpClient("NotificationService")
    .AddResilienceHandler("notification-bulkhead", pipeline =>
    {
        pipeline.AddConcurrencyLimiter(new ConcurrencyLimiterOptions
        {
            PermitLimit = 5,   // Isolated — won't starve payment calls
            QueueLimit = 10
        });
    });

2.5 Retry with Exponential Backoff + Jitter

RetryConfig config = RetryConfig.custom()
    .maxAttempts(3)
    .waitDuration(Duration.ofMillis(100))
    .retryExceptions(IOException.class, TimeoutException.class)
    .build();

// Exponential backoff: 100ms → 200ms → 400ms
// Jitter: add a random offset to each wait to prevent a "thundering herd"
// where every client retries at exactly the same instant
public async Task ExecuteWithDeadlockRetryAsync(Func<Task> action, int maxRetries = 3)
{
    for (int i = 0; i < maxRetries; i++)
    {
        try { await action(); return; }
        catch (SqlException ex) when (ex.Number == 1205 && i < maxRetries - 1)
        {
            await Task.Delay(Random.Shared.Next(50, 200)); // Randomized backoff (jitter)
        }
    }
}

Rule of thumb: only retry idempotent operations, or operations protected by an idempotency key. Combine retry with a circuit breaker (retry inside CLOSED, stop retrying once OPEN) and always cap total retry time with an overall timeout budget.

2.6 Timeout, Fallback, and Health Checks

  • Timeout: Fail fast rather than wait indefinitely — an un-timed-out call is a silent resource leak (thread, connection) waiting on a dependency that may never respond.
  • Fallback: Provide degraded-but-useful functionality when a dependency is unavailable (cached data, a default recommendation list, a “queued for later” response) instead of a hard error.
  • Health Checks — two distinct kinds, often confused in interviews:
    • Liveness: “Is the process alive?” A failing liveness check causes the orchestrator (Kubernetes) to restart the container.
    • Readiness: “Can this instance currently serve traffic?” A failing readiness check causes the load balancer to stop routing to it, without restarting it (e.g., during startup, or while a downstream dependency it needs is unavailable).
readinessProbe:
  httpGet: { path: /health/ready, port: 8080 }
  initialDelaySeconds: 5
  periodSeconds: 10
livenessProbe:
  httpGet: { path: /health/live, port: 8080 }
  initialDelaySeconds: 15
  periodSeconds: 20

2.7 Section 2 — Interview Q&A

Q1: Walk me through the circuit breaker states and a real incident where it made a measurable difference.

A: Circuit breaker has three states: CLOSED (normal, all calls pass through while failures are tracked), OPEN (failure threshold exceeded — all calls fail immediately without hitting the network), and HALF-OPEN (after a cooldown, a small number of probe requests are allowed through to test recovery; success transitions back to CLOSED, failure returns to OPEN). In a payment system integrated with an unreliable third-party gateway, adding a circuit breaker with a five-failures-in-sixty-seconds threshold meant that during a gateway outage, instead of every incoming order request hanging for a full 30-second timeout and exhausting the thread pool, the breaker opened almost immediately and returned a “payment pending, will process shortly” response. Thread pool saturation dropped from near 100% to under 5%, and the rest of the order flow — browsing, cart, non-payment operations — remained fully responsive during the outage.

Q2: What’s the difference between a circuit breaker and a bulkhead, and when do you need both?

A: A circuit breaker is time-based — it tracks the failure rate of calls to a specific dependency over a sliding window and stops making those calls once a threshold is crossed. A bulkhead is resource-based — it caps the number of concurrent calls (threads, connections) allowed to a dependency, regardless of whether those calls are succeeding or failing. They solve different failure modes: a circuit breaker protects you from a dependency that’s returning errors quickly; a bulkhead protects you from a dependency that’s slow but not technically failing — without a bulkhead, a slow-but-“successful” dependency can still exhaust your thread pool one request at a time. In production I use both together: bulkhead caps concurrency per dependency, circuit breaker trips on top of that if the failure rate within the bulkhead’s capacity crosses a threshold.

Q3: Explain the difference between liveness and readiness probes and what happens when each fails.

A: A liveness probe answers “is this process alive and functioning, or is it deadlocked/hung?” — failing it causes Kubernetes to kill and restart the container. A readiness probe answers “can this specific instance currently serve traffic?” — failing it removes the pod from the load balancer’s target list without restarting it. The distinction matters a lot in practice: if I used liveness for “can I reach my database,” a transient database blip would cause Kubernetes to restart every pod simultaneously, making the outage worse. Instead, I use readiness for dependency checks (so the pod is pulled from traffic but stays alive and rejoins automatically once the dependency recovers) and reserve liveness for detecting the process itself being stuck — e.g., a deadlock or an unresponsive event loop.

Q4: How do you prevent a retry storm from making an outage worse?

A: Three layers: (1) exponential backoff with jitter, so retries spread out over time instead of synchronizing into repeated spikes; (2) a circuit breaker in front of the retry logic, so once a dependency is clearly down, we stop retrying altogether rather than hammering it; (3) an overall timeout budget per request chain, so retries don’t compound into unbounded latency for the calling user. I’ve also seen teams add a global “retry budget” — a percentage cap on how much of total traffic is allowed to be retries — so that even well-intentioned per-call retry logic across many services can’t collectively overwhelm a struggling dependency.