System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·125

Availability

Keeping systems serving through failures: availability defined and measured, the maths of serial and parallel components, redundancy at every layer and eliminating single points of failure, health checks done right, replicas and quorums (N, W, R), failover (active-passive, active-active, automatic vs manual, split brain and fencing), multi-AZ and multi-region deployment patterns with RTO/RPO, static stability and cell-based architecture, deployment safety as an availability tool, and the crucial distinctions between availability, durability and consistency.

31 topics · ~19 min read · 31-question quiz
Updated Suggest a correction

Start here: staying up when parts fail

Availability is the fraction of time (or of requests) a system serves correctly. Everything fails eventually, so availability doesn't come from components that never fail; it comes from redundancy (more than one of everything that matters) and fast, automatic failover.

The arithmetic of nines

Text
99%      down 3.65 days a year     7.2 hours a month
99.9%    down 8.8 hours a year     43.8 minutes a month
99.99%   down 52.6 minutes a year  4.4 minutes a month
99.999%  down 5.3 minutes a year   26 seconds a month

Components in series (a request needs all of them) multiply their availabilities, so the chain is weaker than its weakest link:

Text
load balancer 99.99% × app 99.9% × database 99.95%  =  99.84%   (≈14 hours down a year)

Redundant copies in parallel (any one is enough) multiply their unavailabilities:

Text
two independent app servers at 99.9%:  1 − (0.001 × 0.001)  =  99.9999%

That second line assumes failures are independent. Two servers on the same rack, sharing a deploy, a config file or a database, fail together, and the real figure is far worse. Much of availability engineering is removing those shared causes.

Failover takes time: measured

A program wrote a key to the etcd cluster about 45 times a second. Four seconds in, the leader (the member that orders all writes) was killed:

Text
writes: 451 succeeded, 3 failed
last success before the kill: 0.014 s earlier
first success after the kill: +1.551 s
new leader: m3, term 16 → 17

For about 1.5 seconds no write could succeed: the followers had to notice the leader was gone (no heartbeats for the election timeout, 1 s by default), hold an election, and the client had to find the new leader. Reads and writes then carried on with two members. A system that fails over automatically still has a short outage at every failover; your availability target must leave room for it.

Majorities: why three, and what happens with one

With two of the three members killed:

Text
write to the survivor:                    Error: context deadline exceeded
linearizable (normal) read:               Error: context deadline exceeded
serializable read (local, maybe stale):   dal,paneer
after restarting the other two:           write OK in 0.016 s

etcd needs a majority (2 of 3) to agree on anything, so one member alone refuses writes and even normal reads, because it can't be sure it has the latest data. It could still answer a serializable read from its local copy, accepting that the answer might be stale. That is the trade-off at the heart of availability: during a failure you can stay correct (refuse) or stay available (answer, perhaps wrongly), and the requirement decides which.

How deep to go in availability

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Convert nines to downtime and spot single points of failure
L2 Add redundancy and health-checked failover to a service and its dependencies
L3 Explain series/parallel maths, correlated failures, quorums (N, W, R) and failover mechanics
L4 Measure failover times and find hidden shared dependencies in a running system
L5 Design for an availability target across zones and regions, including degraded modes
L6 Set availability targets and resilience standards across an organisation

Availability defined

Availability is the proportion of time (or of requests) for which a system correctly serves its users. Two common measurement styles:

  • Time-based: uptime ÷ (uptime + downtime). Simple, but "down" is ambiguous for partial outages.
  • Request-based: successful requests ÷ valid requests (where "successful" can include a latency threshold). Better reflects user experience and partial degradation; the basis of most SLOs (Vol. 9 ch. 102).

Related measures: MTBF (mean time between failures) and MTTR (mean time to repair/recover). Steady-state availability ≈ MTBF ÷ (MTBF + MTTR). This formula carries a key insight: you can raise availability by failing less often or by recovering faster. In distributed systems, recovering fast (automatic failover, quick rollbacks, small blast radius) is usually the more achievable lever.

The maths of composition

Serial dependencies

If a request needs components A and B and C, all must work:

A_total = A₁ × A₂ × … × Aₙ

Five dependencies at 99.9% each give 0.999⁵ ≈ 99.5%: the system is less available than any of its parts. Deep synchronous call chains destroy availability; this is a core argument for fewer synchronous hops, asynchronous designs, caching and graceful degradation (a dependency's failure shouldn't fail the whole request).

Parallel redundancy

If any one of several independent replicas suffices:

A_total = 1 − (1 − A)ⁿ

Two independent replicas at 99% give 1 − 0.01² = 99.99%. Three give 99.9999%. The catch is independence: replicas sharing a power supply, a rack, a zone, a deployment, a configuration, a software bug or a dependency fail together. Correlated failures are why real-world availability falls far short of these formulas, and why diversity (zones, regions, staggered deploys) matters.

series: all must work A 99.9% B 99.9% C 99.9% D 99.9% E 99.9% = 99.5% parallel: any one suffices LB R1 99% (AZ a) R2 99% (AZ b) = 1 − 0.01² = 99.99% only if independent: shared zone, bug, config or dependency → they fail together
Availability of composed systems. Components in series multiply their availabilities, so a chain of five 99.9% services yields about 99.5%. Redundant components in parallel combine as one minus the product of their unavailabilities, so two independent 99% replicas yield 99.99%, but only if their failures are independent.

Availability budgets

Work backwards from the target. For a 99.95% checkout journey with four critical synchronous dependencies, each needs roughly 99.99% (since 0.9999⁴ ≈ 99.96%), or the journey must tolerate some dependencies failing (fallbacks, async, caching). This calculation often reveals that a target is unrealistic without architectural changes.

Redundancy and single points of failure

A single point of failure (SPOF) is any component whose failure takes the system down. Walk through every layer and ask "what if this disappears?":

Layer Redundancy technique
DNS Managed anycast DNS; optionally two providers
Edge/CDN Multi-PoP CDN; origin failover groups
Load balancers Managed multi-AZ LBs; VRRP pairs or anycast/ECMP if self-run
Application ≥ 2–3 instances per service spread across AZs; anti-affinity; PodDisruptionBudgets
Database Primary + synchronous standby in another AZ; replicas; tested backups
Cache Replicated cache cluster; application tolerates cache loss (falls back to DB with protection)
Queues/streams Replicated brokers across AZs (Kafka replication factor 3, min.insync.replicas=2)
Configuration/secrets/identity Highly available managed services; caching of config and keys so short outages don't matter
Network Multiple AZs, redundant NAT gateways per AZ, redundant on-prem links (two providers, diverse paths)
People and process More than one person who can operate each system; runbooks; access that doesn't depend on the failed system
Third parties Second provider (payments, SMS, email) or degraded modes

Hidden SPOFs to look for: a single NAT gateway, a shared cron host, the CI/CD system (you can't deploy fixes), the identity provider for your admin console, a license server, a single DNS zone, a certificate about to expire, an observability stack in the same failure domain as what it monitors.

Health checks

Load balancers, orchestrators and failover systems rely on health checks; bad health checks cause outages.

Check Question On failure
Liveness Is the process stuck or dead? Restart it
Readiness Should this instance receive traffic right now? Remove from load balancing (don't restart)
Startup Has it finished starting (slow JVM warm-up, migrations, cache loading)? Wait before applying liveness checks
Deep/dependency Can it reach its database, cache, downstream services? Use carefully (see below)

Rules learned the hard way:

  • Liveness must not depend on dependencies: if the database is down and liveness checks fail, the orchestrator restarts every instance, turning a database incident into a total outage with cold starts.
  • Readiness depending on a shared dependency can remove all instances at once; prefer to keep serving (degraded, with cached data or clear errors) and let fail-open logic apply: AWS's guidance is that if all targets fail health checks, ELB fails open and routes to all of them.
  • Make checks cheap and fast; don't let health checks themselves overload a struggling service.
  • Combine active checks with passive signals (outlier detection on real traffic errors).
Java
// Spring Boot: separate liveness and readiness groups; DB contributes to readiness only
// application.yml
// management.endpoint.health.probes.enabled: true
// management.endpoint.health.group.liveness.include: livenessState
// management.endpoint.health.group.readiness.include: readinessState,db
//
// Kubernetes probes then hit /actuator/health/liveness and /actuator/health/readiness
YAML
# Kubernetes: startup probe protects slow starts; liveness is shallow; readiness reflects ability to serve
startupProbe:   { httpGet: { path: /actuator/health/liveness, port: 8080 }, periodSeconds: 5, failureThreshold: 30 }
livenessProbe:  { httpGet: { path: /actuator/health/liveness, port: 8080 }, periodSeconds: 10, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 8080 }, periodSeconds: 5, failureThreshold: 2 }

Replicas and quorums

Replication for availability

Keeping copies of data on multiple nodes lets the system survive node failures (Vol. 5 ch. 71):

  • Single-leader: one primary accepts writes; followers replicate. Failover promotes a follower. Synchronous replication to at least one follower gives RPO ≈ 0 at the cost of write latency; asynchronous replication risks losing the latest writes on failover.
  • Multi-leader: several nodes accept writes (often one per region); conflicts must be resolved (chapter 129, 134).
  • Leaderless (Dynamo-style: Cassandra, ScyllaDB, Riak, DynamoDB internally): clients write to and read from several replicas; quorums decide.
  • Consensus-replicated (Raft/Paxos: etcd, Spanner, CockroachDB, Kafka KRaft metadata, ZooKeeper): a majority must agree; automatic, safe leader election.

Quorums: N, W, R

With N replicas, a write succeeds after W acknowledgements and a read queries R replicas:

  • If W + R > N, every read set overlaps every write set in at least one replica, so reads can see the latest acknowledged write (with caveats: sloppy quorums, concurrent writes, and failed partial writes can still produce anomalies; true linearizability needs more, such as read repair before returning or consensus).
  • Typical: N = 3, W = 2, R = 2 tolerates one replica failure for both reads and writes.
  • W = N maximises durability but any node failure blocks writes; R = 1 gives fast reads but may be stale unless W = N.
  • Majority quorums (⌊N/2⌋ + 1) are the basis of consensus: 3 nodes tolerate 1 failure, 5 tolerate 2. Even numbers add cost without tolerance (4 nodes still tolerate only 1).
writer replica 1: v2 replica 2: v2 replica 3: v1 W=2 acks reader R=2 returns v2; read-repairs replica 3 W + R = 4 > N = 3 → overlap
Quorum overlap with N = 3, W = 2, R = 2. A write is acknowledged by replicas 1 and 2; a later read contacts replicas 2 and 3. Because W + R > N, the read set and write set share at least replica 2, which has the new version; the reader picks the newest version (and can repair replica 3).
Text
# Cassandra-style consistency levels (per query)
CONSISTENCY QUORUM;      -- with RF=3: 2 replicas for reads and writes → overlapping
CONSISTENCY LOCAL_QUORUM;-- quorum within the local datacenter (multi-region latency)
CONSISTENCY ONE;         -- fastest, may read stale data

Failover

Failover switches traffic or leadership from a failed component to a healthy one.

Active-passive and active-active

Mode How Pros Cons
Active-passive (hot/warm/cold standby) Standby takes over when the primary fails Simple data consistency (one writer) Standby capacity idle; failover takes time; standby may be untested
Active-active All sites serve traffic simultaneously No idle capacity; failover = shifting load; continuously tested Concurrent writes need partitioning or conflict resolution; each site needs headroom to absorb others' load

Standby temperature: hot (running, data replicated synchronously or near-real-time, takes over in seconds/minutes), warm (running at reduced scale, data replicated, scale up on failover), cold/pilot light (infrastructure defined, data restored from backups or minimal replication, hours to recover).

Automatic vs manual

  • Automatic failover minimises MTTR for clear failures (a database primary crashes; Patroni, RDS Multi-AZ, Cloud SQL HA, Kafka controller election). Risk: false positives (a network blip triggers failover, losing in-flight writes or causing flapping).
  • Manual (or human-approved) failover for large-scope, risky actions such as regional evacuation, where the cost of a wrong decision is high, with automation that makes the executed steps fast and reliable ("one-button" runbooks).

Split brain and fencing

If a network partition makes the old primary appear dead while it's actually alive, failover can create two primaries accepting conflicting writes: split brain. Defences (Vol. 5 ch. 72, 77):

  • Consensus/quorum for leader election: a leader needs a majority; the minority side can't elect one.
  • Leases with expiry: the old leader stops accepting writes when its lease expires (needs bounded clock drift).
  • Fencing tokens: each new leader gets a higher epoch number; storage rejects writes with older tokens.
  • STONITH ("shoot the other node in the head"): forcibly power off or isolate the old primary before promoting.

Client-side aspects

Failover only helps if clients reconnect: connection pools must detect dead connections (TCP keepalives, validation), DNS TTLs must be short enough for endpoint changes, drivers should support multiple hosts (target_session_attrs=read-write in libpq), and retries must be safe (idempotency).

Multi-AZ

An availability zone (AZ) is one or more datacenters with independent power, cooling and networking, within a region, connected by low-latency links (typically < 2 ms). Zones fail independently far more often than whole regions.

Multi-AZ is the baseline for production:

  • Spread stateless instances evenly across ≥ 3 AZs (Kubernetes topology spread constraints, cloud auto scaling across subnets).
  • Databases with synchronous standby in another AZ (RDS/Aurora Multi-AZ, Cloud SQL HA, Azure zone-redundant), or consensus-based databases with replicas in 3 AZs.
  • Zone-redundant load balancers, caches, queues and storage (S3 standard stores across ≥ 3 AZs).
  • Capacity for zone loss: with 3 AZs, each must be able to carry 50% more load when one fails (N+1 at the zone level), or autoscaling must react fast enough; otherwise a zone failure becomes a capacity outage.
  • Costs: cross-AZ data transfer is billed on most clouds; zone-aware routing (prefer same-zone endpoints) reduces cost and latency while keeping failover.
YAML
# Kubernetes: spread replicas across zones and keep enough running during disruptions
spec:
  replicas: 6
  template:
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
          labelSelector: { matchLabels: { app: checkout } }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: checkout }
spec:
  minAvailable: 4
  selector: { matchLabels: { app: checkout } }

Multi-region

A region is a separate geographic area with its own set of AZs. Multi-region deployment protects against region-wide failures (rare but real: control-plane outages, large networking incidents, natural disasters), serves global users with lower latency, and satisfies data residency (chapter 134 covers global design in depth).

Disaster recovery strategies, from cheapest to most available:

Strategy Secondary region RTO RPO Cost
Backup and restore Backups copied cross-region Hours to days Hours (last backup) Lowest
Pilot light Core data replicated; minimal infra off or tiny Tens of minutes to hours Minutes Low
Warm standby Scaled-down full stack running, data replicated Minutes Seconds to minutes Medium
Active-active (multi-site) Full stack serving traffic in each region Seconds to minutes (traffic shift) ~0 to seconds (depends on replication) Highest

Hard parts: data replication across regions (asynchronous → possible data loss on failover; synchronous → high write latency), dependencies that exist in only one region (identity, payments, a SaaS vendor), failover automation and DNS/traffic shifting, keeping the secondary tested (regular failover drills: an untested DR plan is a hope, not a plan).

Static stability and cells

Static stability

A system is statically stable if it keeps working when a dependency fails without needing to change anything: no new instances to launch, no configuration to fetch, no control-plane calls during the failure. Examples:

  • Pre-provision capacity in every AZ to survive a zone loss without launching new instances (control planes are often impaired during the same event).
  • Cache credentials, configuration, feature flags and service discovery data locally with long expiry, so a config service outage doesn't break the data plane.
  • Separate control planes (provisioning, configuration) from data planes (serving requests): data planes should keep running if the control plane is down.

Cell-based architecture

A cell is a complete, independent copy of the service stack (load balancer, services, data stores) serving a subset of customers. A thin cell router maps each customer (or tenant, or key range) to a cell.

  • A failure (bad deployment, poison request, overload, data corruption) affects only the customers in one cell: blast radius = 1/number of cells.
  • Deploy changes cell by cell (progressive rollout, chapter 130 and Vol. 6 ch. 84).
  • Scale by adding cells, with a known maximum cell size that's load-tested.
  • Shuffle sharding: give each customer a random combination of resources (e.g. 2 of 8 workers); a "poison" customer that kills its workers only affects others who share both workers, a tiny fraction.
clients cell routercustomer → cell cell 1LB · services · database cell 2 ✗ bad deployonly its customers affected cell 3LB · services · database
Cell-based architecture. A thin, highly available routing layer maps each customer to one of several independent cells; each cell has its own services and data. A bad deploy or a poison request that breaks cell 2 affects only that cell's customers, while cells 1 and 3 keep serving.

Deployments and changes as availability risks

Most outages are triggered by changes: code deploys, configuration changes, infrastructure changes, certificate or DNS updates, schema migrations. Availability engineering is therefore largely change safety (Vol. 6 ch. 84, Vol. 8):

  • Progressive delivery: canaries, rolling deploys one AZ/cell at a time, automated rollback on SLO regression, bake times between stages.
  • Feature flags to decouple deploy from release and to switch off misbehaving features instantly.
  • Configuration changes treated like code (reviewed, validated, rolled out gradually), because global config pushes have caused some of the largest internet outages.
  • Backward-compatible schema changes (expand/contract) so rollbacks remain possible.
  • Change freezes around peak events, with clear exceptions.

Availability vs durability vs consistency

These three properties are often confused but are independent:

Property Question Failure looks like Mechanisms
Availability Can I use the system now? Errors, timeouts, maintenance pages Redundancy, failover, health checks, load shedding, cells
Durability Is data I was told was saved still there later? Lost orders, missing files after failure Replication with acknowledgements, fsync, backups, versioning, cross-region copies
Consistency Do reads reflect writes as promised? Stale or conflicting values, anomalies, oversold inventory Consensus, quorums, transactions, isolation levels, conflict resolution

They trade off with each other and with latency:

  • Availability vs consistency: during a network partition, a replica can either answer (possibly stale, available) or refuse until it can coordinate (consistent, unavailable): CAP (Vol. 5 ch. 70). PACELC adds that even without partitions, stronger consistency costs latency.
  • Availability vs durability: acknowledging a write before it's replicated is faster and stays available when replicas are down, but risks loss (Kafka acks=1 vs acks=all with min.insync.replicas=2; PostgreSQL synchronous_commit settings). Requiring synchronous replication to another zone means a replica outage can block writes.
  • Durability ≠ backups alone: replication protects against hardware failure but faithfully replicates mistakes (accidental deletes, corruption, ransomware); point-in-time recovery, versioning and immutable backups protect against those. Test restores regularly.

Choose per data type and operation: a payment ledger wants durability and consistency over availability (refuse rather than risk double-spend); a social feed wants availability over consistency (show something slightly stale rather than an error).

Lab: failover and quorum loss, measured

A three-member etcd 3.6.5 cluster on the lab machine (members on 127.0.0.1–3, default election timeout 1,000 ms and heartbeat 100 ms), and a shell writer calling etcdctl put with a 500 ms command timeout about 45 times a second. Each member is its own process; all share one machine, which removes network faults from the picture but not process failure.

Experiment 1: leader failure

Text
leader is m2
kill -9 m2 at t = 4 s
writes: 451 ok, 3 failed
last ok before kill: 0.014 s earlier; first ok after kill: +1.551 s
after: m3 leader, term 17

The 1.55 s gap breaks down into: up to 1 s for followers to time out (election timeout, randomised per member to avoid split votes), a few ms for the election, and the client's retry (the three failed puts each waited up to 500 ms before giving up and the next tried another endpoint). Tuning trades speed for stability: a shorter election timeout fails over faster but risks needless elections during GC pauses or network jitter; etcd recommends an election timeout of about 10× the round-trip time between members.

Experiment 2: losing the majority

Text
2 of 3 members killed
put   → Error: context deadline exceeded
get   → Error: context deadline exceeded          (linearizable: needs a quorum read)
get --consistency=s → dal,paneer                  (serializable: local copy)
both restarted → put OK in 0.016 s
Members Majority Failures tolerated
1 1 0
2 2 0
3 2 1
4 3 1
5 3 2

Even sizes add a member without adding tolerance, which is why clusters are 3 or 5. The same majority rule appears in replicated databases as N, W, R: with N replicas, writes acknowledged by W and reads consulting R, every read overlaps the latest write when W + R > N (for N = 3: W = 2, R = 2).

Experiment 3: the arithmetic, checked

Text
series:   0.9999 × 0.999 × 0.9995 = 0.99840  → 14.0 hours/year down
parallel: 1 − 0.001²              = 0.999999 → 32 seconds/year (if independent)
with a shared database at 99.95% behind both app servers:
          0.999999 × 0.9995       = 0.99950  → 4.4 hours/year down

Redundant app servers bought almost nothing while the database they both depend on stayed single. Availability work goes to the weakest serial component first.

Experiment 4: what failover needs from clients

The writer succeeded after the failover only because it was given all three endpoints and a short timeout. With --endpoints=127.0.0.2:2379 (the dead leader alone), every write would have failed until an operator intervened. Client requirements for surviving failover: know several endpoints or a load-balanced name; time out quickly; retry idempotent operations on another endpoint; and re-resolve DNS rather than caching an address forever.

Try it yourself

  1. Restart etcd with --election-timeout=300 --heartbeat-interval=30 and rerun Experiment 1. How short does the gap get, and do you see spurious elections under CPU load (stress-ng --cpu 2)?
  2. Kill a follower instead of the leader. Do any writes fail?
  3. Use part.sh on (from Volume 5's lab) to partition member 3 from its peers while clients can still reach it. What do clients connected only to member 3 see?
  4. Compute the availability of a system with two regions, each 99.9%, behind DNS failover that itself takes 5 minutes per incident and fires four times a year.

Revision sheet: availability

Key ideas

  • Availability = good time ÷ total time, or good requests ÷ total; define it per user-facing operation.
  • Series multiplies availabilities; parallel multiplies unavailabilities, only if failures are independent.
  • Eliminate single points of failure at every layer: instances, zones, load balancers, databases, DNS, credentials, deploys, people.
  • Correlated failures (shared rack, zone, deploy, config, dependency, bug) defeat redundancy; diversify and stagger.
  • Failover: detection (health checks, heartbeats) + decision (election, promotion) + redirection (clients, DNS); each takes time.
  • Quorums: majority-based systems tolerate ⌊(N−1)/2⌋ failures; W + R > N for overlapping reads and writes.
  • Degraded modes: stale reads, read-only operation, feature shedding keep partial service when full service isn't possible.
  • MTTR matters as much as MTBF: availability ≈ MTBF ÷ (MTBF + MTTR).

Numbers to remember

  • 99.9% ≈ 43.8 min/month; 99.99% ≈ 4.4 min/month; 99.999% ≈ 26 s/month.
  • Lab: etcd leader kill → 1.55 s without successful writes; quorum loss → no writes or linearizable reads.
  • 3 members tolerate 1 failure; 5 tolerate 2.

Pitfalls

  • Redundant stateless tiers in front of a single database.
  • Failover that has never been tested (or that needs a human at 3 a.m.).
  • Clients pinned to one endpoint or caching DNS forever.
  • Health checks that test dependencies, causing a whole fleet to restart when the database blips.
  • Even-sized quorums; two-node clusters with split-brain risk.
  • Counting availability by uptime of servers rather than success of user requests.

Glossary

  • SPOF: single point of failure.
  • MTBF / MTTR: mean time between failures / to recovery.
  • Leader election: choosing the member that orders writes.
  • Split brain: two members both acting as leader.
  • Linearizable vs serializable read (etcd): quorum-confirmed latest value vs local, possibly stale value.