Summary#
High availability (HA) design is how you turn the availability maths into a running system. You remove every single point of failure, layer by layer. You spread replicas across failure domains: zones, then regions. Failover must be fast and safe, and broken parts must be detected and replaced automatically. When capacity is lost, the product degrades gracefully instead of failing completely. Cells cap how much one failure can hurt, and you inject failures on purpose to prove all of this works. The trade-off is cost and complexity. Each extra nine roughly multiplies the redundancy, automation and testing you must pay for, so HA is designed to a target, never maximised blindly.
Why It Exists#
Everything fails eventually. Disks wear out, servers lose power, kernels panic, and a zone loses cooling. Deploys ship bugs, certificates expire, and configuration pushes go wrong. A cloud provider's control plane has a bad day. At small scale these events are rare. At large scale they are constant. A fleet of 10,000 servers, each failing about once every three years, loses roughly nine servers a day. A design that treats failure as exceptional is down most of the time it matters.
Availability, Reliability and Fault Tolerance gives the vocabulary and the maths:
- Nines: 99.9% availability allows about 43 minutes of downtime a month; 99.99% allows about 4.3 minutes.
- Series and parallel: components in series multiply their availabilities, so the whole is worse than any part. Redundant components in parallel multiply their unavailabilities, so the whole is better than any part.
- MTBF and MTTR: mean time between failures and mean time to repair. Availability ≈ MTBF / (MTBF + MTTR).
This page is about the engineering that achieves a target. Three observations shape all of it.
-
Most outages are not hardware failures. Jim Gray's study of Tandem systems, "Why Do Computers Stop and What Can Be Done About It?" (1985), found that operations and software caused far more outages than hardware. Industry postmortems keep confirming this. Bad deploys, configuration changes, expired certificates, capacity exhaustion and dependency failures dominate. HA design therefore has to cover change (deploys and config) and overload, not just dead machines.
-
Redundancy only helps if failures are independent. Two servers in the same rack share a power feed and a top-of-rack switch. Two regions running the same bad config push share the bug. Redundancy across a shared fate is an illusion. A large part of HA design is finding the hidden shared fates and breaking them up.
-
Recovery speed matters as much as failure rarity. Halving MTTR improves availability as much as doubling MTBF. Usually it is much cheaper to do, through faster detection, automated failover, fast rollback and practised runbooks.
How It Works#
HA design has six moving parts, and they build on one another.
- Redundancy at every layer, so no single component's failure takes the service down.
- Placement across failure domains, such as availability zones and regions, so that redundant parts don't fail together.
- Failover, to move traffic or leadership from a failed component to a healthy one, quickly and without corrupting data.
- Health checks and self-healing, to detect failures and replace broken parts without a human in the loop.
- Graceful degradation, so that when capacity or dependencies are lost, the most important functions keep working.
- Blast-radius limits and verification: cells to contain failures, and chaos engineering to prove the other five actually work.
The diagram shows a typical highly available web service, with redundancy at each layer from the user's DNS lookup down to the database.
Redundancy at every layer#
Redundancy means having more than one of something, so that losing one leaves the service running. The question to ask of every box in the architecture is: if this one thing disappears right now, what happens? If the answer is "the service goes down", you have found a single point of failure (SPOF).
Go through the stack from the outside in.
- DNS. If your authoritative name servers fail, nobody can find you, however healthy your servers are. Managed DNS providers run many name servers on anycast, where the same IP address is announced from many locations and the network routes each query to the nearest one. Some organisations also use two DNS providers, so that one provider's outage doesn't take them offline. The DNS page covers the mechanics.
- Edge and CDN. A CDN has hundreds of points of presence (PoPs). If one PoP fails, its traffic shifts to the next nearest. The CDN can also keep serving cached content when the origin is down, if you configure stale-if-error behaviour.
- Load balancers. A single load balancer box is a SPOF. Managed cloud load balancers are themselves distributed across zones. Self-run ones are deployed as pairs, sharing a virtual IP (VIP) that moves to the standby if the active one dies (VRRP, keepalived). The Load Balancing page covers how the balancers spread traffic.
- Application servers. Make them stateless: no session or user data kept only in local memory or disk. Then any server can serve any request, losing one loses nothing, and you run N+1 or more copies behind the balancer.
- Caches. A cache cluster needs replicas, or a design that survives losing a node. Usually that is consistent hashing plus the database absorbing a temporary miss spike. The Cache Failure Modes page covers stampedes and cold starts after a cache loss.
- Queues and logs. Kafka topics use a replication factor of 3 with
min.insync.replicas=2. Managed queues (SQS, Pub/Sub) replicate across zones internally. - Databases. Run a primary with one or more standbys, ideally a synchronous one in another zone, plus automated failover. Alternatively, use a natively replicated database (consensus-based, or leaderless with quorums). See Replication.
- Object storage. Managed object stores already replicate or erasure-code across zones. S3 Standard is designed for 11 nines of durability, with data stored across at least three zones.
- Configuration, secrets and service discovery. These are often forgotten. If every service reads its config from one store at startup, that store is a SPOF for every restart. If service discovery is down, nobody can find anybody.
- The control plane. This is the system that creates, scales and configures resources: the cloud API, the Kubernetes API server, your deploy system. Running systems should keep running when the control plane is down. This property is called static stability, and it's covered below.
- People and processes. If one engineer is the only person who can perform a failover, they are a SPOF. So is a runbook nobody has tried.
Redundancy, in depth: N+1, N+2 and zone-loss capacity#
Redundancy is measured in spare capacity. N is the number of units you need to carry peak load.
- N+1 means one spare, so you survive one failure at peak.
- N+2 means you survive one failure during a planned maintenance or deploy that has already taken a unit out.
- 2N means a full duplicate, typical of active-passive pairs.
The subtle case is capacity spread across zones. Suppose you need 12 servers at peak, spread over 3 zones. If one zone fails, you lose a third of your servers. To keep carrying peak load on the remaining two zones, each of those must hold half of the peak, 6 servers. So you deploy 6 per zone, 18 in total, 150% of the need. With 2 zones you would need 12 per zone, 200%. With 4 zones it is 4 per zone, 16 in total, about 133%. The formula is: with z zones, provision z / (z − 1) times peak to survive one zone loss. This is one reason clouds have at least three zones per region, and why most designs use three.
Autoscaling can't be counted on to replace this headroom. When a zone fails, everybody in that region tries to launch replacement capacity at the same moment, and the control plane may itself be impaired. Systems that need to stay up during a zone loss are pre-provisioned for it. This is the essence of AWS's "static stability" guidance in the Amazon Builders' Library: the data plane should keep working, with the capacity it already has, without needing to make control-plane calls during the event.
The same logic applies to stateful tiers. A Kafka cluster with replication factor 3 spread over 3 zones, and min.insync.replicas=2, can lose one zone and keep accepting writes. But the surviving brokers then carry the leadership and fetch load of the lost ones, so they need headroom too.
Redundancy also has a hidden cost: the failure of the redundancy mechanism itself. Failover logic, health checkers and replication are code, and code has bugs. Gray found that fault-tolerant systems often failed in their recovery paths, which run rarely and are therefore poorly tested. The remedy is to exercise recovery paths constantly. Routine failovers and chaos experiments turn rare code paths into common ones.
Multi-AZ and multi-region#
An availability zone (AZ) is one or more data centres with independent power, cooling and networking. A zone sits a few kilometres to tens of kilometres from the other zones in its region, and is connected to them by low-latency links, typically around 1–2 ms round trip. A region is a geographic area, such as Northern Virginia or Frankfurt, containing several zones. Regions are hundreds to thousands of kilometres apart. Round trips between them take tens of milliseconds: roughly 60–80 ms across the US, and roughly 70–100 ms between the US East Coast and Western Europe.
These two failure domains differ in what they protect against and what they cost.
- Multi-AZ protects against a data-centre-level failure: power, cooling, a fibre cut, a flood in one building. Because zones are close, you can replicate synchronously between them at a cost of a millisecond or two per write. That gives zero data loss on failover and lets you treat the region as one system. Multi-AZ is the default for anything production-grade. Managed services make it nearly a checkbox: RDS Multi-AZ, Aurora, ElastiCache replicas, multi-AZ Kubernetes node groups, zonal load-balancer nodes.
- Multi-region protects against a whole-region failure. That might be a natural disaster, a regional control-plane outage, or a bad change rolled out region-wide. It also protects against regulatory problems, and it brings users closer. But synchronous replication across regions costs tens of milliseconds per write. Most multi-region designs therefore replicate asynchronously, which means accepting some data loss (a non-zero RPO) or conflicts. Or they use consensus-based databases (Spanner, CockroachDB) that pay the cross-region latency on every write.
In the diagram, the primary in zone A replicates synchronously to zone B (about 1 ms per commit) and asynchronously to zone C. Each zone runs the same stateless servers, so any one zone can disappear.
Real failures are rarely as clean as "a zone vanished". The December 2021 AWS us-east-1 event was an impairment of AWS's internal network. It degraded many control-plane services in the region, and the effects spread beyond any one zone. The February 2017 S3 outage in the same region began when a command, entered to remove a small number of servers, removed far more than intended. Both were regional, which is why multi-AZ alone doesn't make a system immune to regional events.
Multi-AZ and multi-region, in depth: topologies and their costs#
Four topologies cover most designs, in increasing order of cost and capability.
1. Single region, multi-AZ (the default). Run stateless tiers in 3 zones with zone-loss headroom. Run the database with a synchronous standby in another zone, and automated failover in 30–120 s. Cross-zone data transfer is billed per GB on most clouds, so keep chatty traffic zone-local where possible. Covers: server, rack and zone failures. Doesn't cover: regional events, or a bad global change.
2. Multi-region active-passive (warm standby or pilot light). A secondary region holds asynchronously replicated data and either a scaled-down stack or just the data. Failover is a decision, often a human one, followed by promoting the replica database, scaling up compute and moving DNS. The RTO (time to recover) is minutes to an hour. The RPO (data lost) is the replication lag at the moment of failure, typically seconds. Disaster Recovery and Backups covers these tiers in detail. Cost: extra storage and idle capacity. Risk: the standby rots unless it is exercised.
3. Multi-region active-active with partitioned ownership. Every region serves traffic. Each user, tenant or entity has a home region that owns its writes, and reads may be served locally from replicas. When a region fails, ownership of its users moves to the survivors. This avoids write conflicts, because there is one writer per entity at any time. It is common for consumer apps, where users are naturally geographic. The hard part is moving ownership safely, without two regions both believing they own a user.
4. Multi-region active-active with multi-writer data. Any region accepts any write. This needs either:
- conflict resolution: last-writer-wins (DynamoDB global tables, Cassandra multi-DC), CRDTs, or application merge logic;
- or global consensus: Spanner, CockroachDB, with writes paying a cross-region quorum round trip.
Global consensus offers strong consistency and survives a region loss with no data loss. Google states a 99.999% availability SLA for multi-region Spanner configurations. The cost is write latency, typically tens of milliseconds or more.
The Multi-Region Data page treats the data side in depth. For HA, the key questions are:
- What is the RPO, and what is the RTO? Zero RPO across regions requires synchronous or consensus writes.
- Who decides to fail over? Automatic regional failover is dangerous, because a network partition can look like a region failure. Many organisations keep a human in the decision but automate everything after it.
- Is there capacity in the survivors? Two regions each running at 70% can't absorb each other. Active-active at r regions needs about r / (r − 1) headroom per region, the same formula as for zones.
- Has it been practised? A failover path that is exercised only during a disaster will fail during the disaster.
Failover patterns#
Failover is the act of switching work from a failed component to a healthy one. Every failover has three phases:
- detect that the active component has failed;
- decide what takes over, and make sure only one thing does;
- redirect clients to the new active component.
The patterns differ in what is redundant and how traffic is redirected.
Active-passive (hot, warm, cold standby). One component serves, and a standby waits. The standby sends or receives heartbeats, periodic "I'm alive" messages. When the heartbeats stop, the standby takes over the active's address and starts serving. The standby's temperature determines the downtime:
- a hot standby is running and fully synchronised, so it takes over in seconds;
- a warm standby is running but must catch up or scale up, which takes minutes;
- a cold standby must be started from scratch, which takes many minutes to hours.
Only the active component handles traffic, so half the hardware sits idle. The risk is data loss if the active fails before its latest writes reach the standby, which is why synchronous replication matters for databases.
Active-active. All components serve traffic, and load is spread across them. Losing one means the others absorb its share, so failover is mostly a matter of no longer sending traffic to the dead one. For public-facing servers, DNS or an anycast address points to all of them. For internal ones, a load balancer or a client-side discovery list does. Active-active uses all the hardware, and its failover path is exercised constantly, because the paths are the same as for normal operation. But it requires that the work be shareable. That is easy for stateless servers. For stateful writes it is hard, because two active writers to the same data can conflict.
Redirect mechanisms, from slowest to fastest:
| Mechanism | How traffic moves | Typical switch time | Notes |
|---|---|---|---|
| DNS failover | Health-checked DNS stops returning the failed endpoint | Health-check interval plus TTL plus client caching: tens of seconds to minutes | Some clients and resolvers ignore low TTLs |
| Anycast / BGP | Failed site withdraws its route announcement | Seconds to tens of seconds | Used by CDNs and DNS providers |
| Load balancer health checks | Balancer stops routing to failed targets | Interval × unhealthy threshold, often 10–60 s | The workhorse for stateless tiers |
| Virtual IP takeover (VRRP, keepalived) | Standby claims the IP via gratuitous ARP | 1–3 s | Within one network segment only |
| Client-side retry to another replica | Client library tries the next endpoint | Milliseconds (one timeout) | Fastest; needs idempotent requests |
| Leader election | Consensus elects a new leader; clients rediscover it | Election timeout plus rediscovery, often 1–30 s | For databases, brokers and coordinators |
Stateful failover is where the danger lies. Failing over a stateless web tier is easy: stop sending traffic to the dead server. Failing over a database primary raises three hard problems.
- Was it really dead? A primary that is merely slow, or cut off from the monitor but not from clients, may still be accepting writes.
- Is the standby up to date? If replication was asynchronous, promoting the standby loses the writes it hadn't received.
- Will the old primary come back and think it is still in charge?
Getting any of these wrong produces split brain: two primaries accepting conflicting writes, which is far worse than a short outage.
Failover, in depth: the anatomy of a safe database failover#
Here is how a well-built system, for example PostgreSQL with Patroni and etcd, or MySQL with Orchestrator and semi-synchronous replication, fails over its primary.
The steps encode the lessons:
- Leadership is a lease in a consensus store. The primary holds a key with a time-to-live in etcd, ZooKeeper or Consul, and it renews the key regularly. Patroni's defaults are a 30 s TTL and a 10 s loop. Only the holder of the key may act as primary. If the primary can't renew the key, because it crashed or is partitioned from the store, it must demote itself before the TTL expires. This lease-based self-demotion is what prevents a partitioned old primary from continuing to accept writes. Leader Election and Coordination covers leases and their clock assumptions.
- The promotion is an atomic compare-and-set. Several standbys may race to take over. The consensus store's compare-and-set guarantees that exactly one wins.
- Pick the most up-to-date standby, or only standbys that were synchronous. Patroni can be configured so that only a synchronous standby is eligible, guaranteeing zero data loss at the cost of write latency.
- Fence the old primary. Self-demotion is the first line. Stronger fencing includes:
- revoking its storage access ("STONITH", shoot the other node in the head);
- removing it from the load balancer;
- having storage reject writes with an old fencing token (epoch number).
- Redirect clients through service discovery, a DNS update, a proxy (PgBouncer, ProxySQL, HAProxy) or a VIP. Clients must reconnect and retry. That is only safe if writes are idempotent. See Idempotency.
- Rejoin the old primary as a replica. It may have local writes that were never replicated. Those must be discarded (PostgreSQL's
pg_rewind) before it can follow the new primary.
The timing budget. Total failover time is roughly:
detection (lease TTL, or missed heartbeats) + election (one consensus round trip) + promotion (replaying the remaining log, often seconds) + client rediscovery (DNS TTL, connection-pool timeouts).
With a 30 s TTL and well-behaved clients, that comes to 30–45 s. Managed services publish typical figures. AWS describes RDS Multi-AZ failovers as typically taking 60–120 s. Aurora usually fails over faster, often in under 30 s, because its storage is shared and replicas don't need to catch up.
Making detection faster shortens outages, but increases false failovers. A garbage-collection pause, or a brief network blip, triggers an unnecessary failover, and each failover has a cost: dropped connections, a cold cache on the new primary, and risk. The usual practice is to pick a TTL or heartbeat timeout of several times the worst normal pause. Failure Detection and Gossip covers phi-accrual detectors, which adapt to observed heartbeat variance.
Who watches the watcher? The failover controller (Patroni, Orchestrator, Redis Sentinel) must itself be redundant, and must make decisions by majority. Redis Sentinel, for example, needs a quorum of sentinels to agree that the primary is down, and a majority to authorise the failover. A single monitor that loses its network link to the primary would otherwise "detect" a failure that hasn't happened, and promote a second primary.
Consensus-replicated databases fold all of this into the protocol. Raft- or Paxos-based systems (etcd, CockroachDB, Spanner, TiDB, YugabyteDB) elect leaders per range or group. Writes need a majority, so a minority partition cannot accept writes, and split brain is impossible by construction. Leader failover takes an election timeout, typically hundreds of milliseconds to a few seconds. The cost is that every write waits for a majority. That is cheap within a region, and tens of milliseconds across regions. Consensus covers the protocols.
Health checks and self-healing#
A health check is a probe that a load balancer, orchestrator or monitor sends to an instance, to decide whether it should receive traffic or be replaced. Self-healing is the automation that acts on the result: restarting a crashed process, replacing a failed VM, rescheduling a container, or taking a node out of rotation.
Health checks come in three depths:
- Liveness: "Is the process alive at all?" A TCP connect, or an HTTP endpoint that returns 200 without touching anything else. If it fails, the instance is restarted.
- Readiness: "Can this instance serve traffic right now?" It has loaded its config, warmed its caches, connected to its database pool, and isn't overloaded. If it fails, traffic is withheld, but the instance is not killed. A server that is starting up, or draining for shutdown, reports not-ready.
- Deep (dependency) checks: "Can this instance do real work?" The probe exercises dependencies: a test query against the database, or a read from the cache. These are useful for monitoring, and dangerous as routing or restart signals (see below).
Kubernetes makes the split explicit with livenessProbe, readinessProbe and startupProbe. Cloud load balancers use one health check per target group, with a configurable interval, timeout, and healthy and unhealthy thresholds. An instance must fail several consecutive checks before it is removed, and pass several before it is restored. This hysteresis prevents flapping.
The self-healing layers stack on top of each other:
- a process supervisor (systemd, a container runtime) restarts a crashed process within seconds;
- an orchestrator (Kubernetes, ECS, Nomad) reschedules failed containers onto healthy nodes, and keeps the desired replica count;
- an instance group (AWS Auto Scaling groups, GCP managed instance groups) replaces VMs that fail health checks;
- a database or cluster manager (Patroni, Redis Cluster, Kafka controller) re-elects leaders and re-replicates data.
These loops are reconcilers. They continuously compare the desired state ("6 healthy replicas spread over 3 zones") to the actual state, and act to close the gap. This control-loop design is why Kubernetes heals itself without anyone writing failover code for each application.
Health checks, in depth: how health checks cause outages#
Health checks are among the most common causes of self-inflicted outages. The failure modes are worth knowing by name.
Deep checks cause cascading removal. Suppose every app server's health check queries the database, and the database has a slow minute. Every app server fails its check at once. The load balancer removes all of them, and a degraded service becomes a total outage. Worse, when the database recovers, the servers come back one by one, and each is crushed by the full load. The rule from AWS's Builders' Library article on health checks is:
- route on local health: process up, not overloaded, config loaded;
- report dependency health to monitoring, not to the router;
- if you do use dependency checks for routing, fail open. When all targets look unhealthy, keep sending traffic to all of them. A single bad instance is far more likely than every instance failing at once. AWS's load balancers and Route 53 behave this way when every target is unhealthy.
Liveness checks that restart overloaded servers. An overloaded server responds slowly, its liveness probe times out, and the orchestrator restarts it. Its load moves to the remaining servers, which become overloaded in turn and are also restarted. This is a restart cascade. The fixes:
- make liveness trivially cheap, and served on a separate thread or port that isn't stuck behind the request queue;
- use generous liveness timeouts and failure thresholds;
- signal overload through readiness (stop sending me traffic), never through liveness (kill me).
Gray failures. An instance passes its health check but fails real requests. Perhaps one disk is slow, or one dependency path is broken, or it returns errors only for some request types. Huang et al. named this pattern in "Gray Failure: The Achilles' Heel of Cloud-Scale Systems" (HotOS 2017): the failure detector's view differs from the clients' view. The remedies:
- outlier detection on real traffic: Envoy and Istio eject hosts whose 5xx rate or latency is much worse than their peers';
- health checks that exercise the real request path;
- clients that report failures. Observability covers detecting these failures from user-facing signals.
Crash loops and restart storms. A bad config makes every instance crash on start. The orchestrator restarts them forever, and each start may hammer a dependency: loading a large dataset, or opening thousands of connections. Exponential backoff on restarts (Kubernetes' CrashLoopBackOff) limits the damage. The real fix is catching the bad config before it rolls out everywhere, as the deployment section below explains.
Self-healing needs limits. Automation that replaces "failed" capacity must stop when it is clearly wrong. For example, it should refuse to remove more than a fixed fraction of a fleet at once. A rule like "never take more than 10% of hosts out of service automatically" turns a detector bug into a minor event instead of a fleet-wide outage. Kubernetes' PodDisruptionBudget expresses the same idea for voluntary disruptions.
Crash-only design makes healing safe. Candea and Fox's "Crash-Only Software" (HotOS 2003) argued that if components can only be stopped by crashing, and always recover through the same startup path, then recovery is exercised on every restart and is well tested. Restart becomes a cheap, safe healing action. Stateless servers, write-ahead logs and idempotent message processing are all crash-only friendly.
Graceful degradation#
Graceful degradation means that when part of the system fails, or capacity runs short, the service keeps its most important functions working, and gives up the less important ones. The alternative is all-or-nothing behaviour: a product page that returns 500 because the recommendations service timed out, when the page could simply have been shown without recommendations.
Degradation is designed ahead of time, by classifying each feature and dependency.
- Critical path: without it, the core action fails. For checkout, that means the cart, pricing, the payment authorisation and order creation.
- Important, but degradable: it can be replaced with something simpler. Personalised recommendations become a static best-seller list. A real-time inventory count becomes "in stock" or "low stock" from a cache. Shipping estimates are computed from a default.
- Optional: it can be dropped entirely, such as reviews, "people also bought", animations and analytics beacons.
For each degradable dependency, decide on the fallback in advance.
| Fallback | Example | Watch out for |
|---|---|---|
| Cached or stale data | Serve the last known price list or profile | Staleness limits, and whether a decision depends on it |
| Static default | Generic recommendations; default avatar | Must be prebuilt and tested |
| Reduced functionality | Search without spelling correction; feed without ranking | Users notice; communicate if it lasts |
| Queue for later | Accept the order, send the confirmation email later | Needs durable buffering and idempotent replay |
| Read-only mode | Browsing works; posting is paused | Clear UX message |
| Hide the feature | Remove the widget from the page | The page layout must tolerate it |
The same principle drives the fail-open versus fail-closed decision for protective components. Take a rate limiter, an authorisation check or a fraud screen. When it can't reach its backing store, should the request be allowed or rejected?
- Fail open (allow) keeps the product available, but removes the protection.
- Fail closed (reject) keeps the protection, but turns a limiter outage into an API outage.
The choice depends on what the component protects. Authentication and payment fraud checks usually fail closed, because letting unauthenticated or fraudulent traffic through is worse than being down. Recommendations and analytics fail open. Rate limiters are the hard case. A limiter outage often coincides with a traffic spike, because the spike is what overloaded its store. Failing open at that moment sends the whole spike to the backends, and can turn a limiter outage into a platform outage. Some designs therefore fail closed, or fail to a crude local limit (each gateway enforcing a per-instance share of the global limit), which keeps most of the protection without the shared store. Either way, the better investment is making the limiter's store highly available: Redis replicas with automatic failover, and alerts when the fallback mode engages. Rate Limiting and Throttling covers the limiter itself.
Graceful degradation, in depth: load shedding, brownouts and the trouble with fallbacks#
Degradation under overload. A system past its capacity doesn't just slow down. Queues grow and latency climbs, and clients time out and retry, which adds load. Throughput can collapse: the servers spend their time on requests whose clients have already given up. The defences belong to Resilience Patterns: timeouts, retry budgets, circuit breakers and back pressure. From an HA point of view, the key idea is prioritised load shedding. Reject the least important work first, and reject it early and cheaply, so that the important work still gets served.
- Tag requests with a criticality. Google's SRE book (Beyer et al., 2016) describes classes such as CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS and SHEDDABLE.
- Shed from the bottom as utilisation rises. Background prefetches and analytics go first, then bulk operations. User-facing reads and checkout go last.
- Shed at the edge (gateway or load balancer) when possible, before work is wasted deep in the stack.
- Prefer rejecting quickly with 503 and a
Retry-Afterheader over queueing indefinitely. A fast "no" is better for everyone than a slow "no".
Brownouts. A brownout deliberately turns off optional features when load or errors cross a threshold, and turns them back on when things recover. Examples are disabling recommendations, lowering video bitrates, or skipping expensive ranking. Klein et al. formalised this as "brownout" for cloud applications (ICSE 2014): each response has an optional part, served with a probability that a controller adjusts to keep latency within a target. Video streaming services do the same thing through adaptive bitrate. Under congestion, the stream steps down in quality instead of stopping.
The trouble with fallbacks. Fallback code is code that rarely runs, so it is rarely tested. When it finally runs, during an outage, it often behaves differently than expected. The fallback may itself be overloaded, because everyone falls back at once. It may never have been load-tested. It may change behaviour in ways nobody anticipated. Amazon's Builders' Library article "Avoiding fallback in distributed systems" argues for a different approach. Rather than switching to a separate, rarely used fallback path, make the primary path more robust: retries, pre-provisioned capacity, and pushing data to where it's needed instead of pulling it at request time. When a fallback is needed, prefer one that is exercised all the time. A cache that is always consulted first, for example, rather than one consulted only when the database fails.
Static fallbacks prepared in advance. Some systems prebuild a degraded product. A static version of the home page is regenerated every few minutes and stored on the CDN, ready to be served if the origin fails. A "lite" checkout skips non-essential calls. These fallbacks are cheap to serve, independent of the failing systems, and can be tested continuously by serving them to a small slice of traffic.
Degradation is a product decision. Engineers can't decide alone whether "checkout without coupon validation" is acceptable. That is a business risk. HA design includes a degradation plan agreed with product owners: which features degrade, how, which switches control them, and who may flip them during an incident. Feature flags implement the switches. CI/CD and Deployment Strategies covers flag systems.
Cell-based architecture and blast radius#
The blast radius of a failure is the set of users, requests or functions it affects. Redundancy reduces the probability of failure. Blast-radius reduction limits the damage when failure happens anyway, which matters most for the failures redundancy can't stop: a poison request, a bad deploy, a noisy tenant, a data-corruption bug.
A cell-based architecture splits a service into many independent, identical copies, called cells. Each cell is a complete stack, with its own load balancers, servers, caches and databases, and serves a subset of customers. A thin cell router (also called a partition mapper) maps each request's partition key, usually the customer or tenant ID, to that customer's cell. Cells share nothing, so a failure inside one cell affects only that cell's customers. Whatever the failure, whether a bug triggered by one customer's data, an overload, or a bad deploy, if a service has 20 cells, it hurts at most about 5% of customers.
The ideas behind cells:
- Cells are sized and capped. Each cell has a maximum size, tested by load tests. You grow by adding cells, not by growing cells. So a cell is never bigger than the size you've proven, and scale limits are known in advance.
- The router must be the simplest, most reliable component. It does little more than look up a mapping, usually cached aggressively, and forward. Its failure affects everyone, so it gets the most redundancy and the fewest changes.
- Deploys go cell by cell. A bad release breaks one cell, and is caught by monitoring and rolled back before reaching the rest. Cells give staged deployment a natural unit.
- Cells can align with zones. A zonal cell is confined to one AZ. When a zone has problems, you drain it by shifting traffic away from that zone's cells, rather than diagnosing a partial failure in place.
AWS has published guidance on cell-based architecture, the Well-Architected whitepaper "Reducing the Scope of Impact with Cell-Based Architecture", and describes using cells in many of its own services. Slack wrote in 2023 about moving to a cellular architecture. The motivation was gray failures in a single zone. With per-zone cells, Slack could drain an affected zone in minutes instead of debugging it under pressure.
Cell-based architecture, in depth: sizing cells and shuffle sharding#
How big should a cell be? Smaller cells mean a smaller blast radius: with n cells, one cell's failure affects 1/n of customers. But smaller cells also mean:
- more operational units to deploy and monitor;
- less statistical multiplexing, so each cell needs more headroom for spikes;
- a harder time placing very large customers, because one customer must fit in one cell, or that customer must be split.
Common practice is to pick a cell size by the largest customer you must host, plus headroom. You then add cells as you grow, and keep the count large enough that one cell is a small percentage, often 1–5% of the fleet.
Moving customers between cells is the hard operational problem. It is a live data migration: copy the data, catch up via change data capture, flip the router entry, and verify. It must be possible in order to rebalance hot cells and to evacuate failing ones. The cell router's mapping is therefore a strongly consistent, versioned record. The control plane changes it carefully, and the data plane caches it.
Shuffle sharding improves on cells for multi-tenant systems, where one tenant can cause trouble for others. Instead of assigning each customer to one cell or shard, assign each customer to a random combination of k workers out of n.
- Consider a plain sharded system with 8 workers in 4 shards of 2. A poison-pill customer that crashes its workers takes out its whole shard, so a quarter of all customers go down with it.
- With shuffle sharding, each customer gets its own random pair out of the 8 workers. There are C(8, 2) = 28 possible pairs. A different customer shares both workers with the bad customer, and is therefore fully down, only if it drew the same pair: a probability of 1/28, about 3.6%.
- Scale this up. With n = 100 workers and k = 5 per customer, there are C(100, 5) ≈ 75 million combinations. Almost no other customer shares the full set of 5 with a bad actor.
- Clients retry across their k workers. A customer sharing one or two workers with a bad tenant stays available on the rest.
AWS has described using shuffle sharding in Route 53, where each hosted zone is served by its own combination of name servers. A DDoS attack on one domain therefore degrades only the servers in its combination, and almost no other domain depends on all of them. Colm MacCárthaigh's Builders' Library article "Workload isolation using shuffle-sharding" explains the technique.
Blast radius applies to change, not just to load. Most large outages come from a change that was applied everywhere at once. Cloudflare's July 2019 outage began with a single WAF rule containing a regular expression that backtracked catastrophically. The rule was deployed globally in one step, and CPU was exhausted on every machine handling HTTP. In July 2024, a faulty CrowdStrike content update crashed millions of Windows machines worldwide, because it reached all of them at roughly the same time. The defence is to treat configuration and data pushes exactly like code deploys:
- stage them through canaries, then one cell, one zone and one region at a time;
- check health signals automatically between stages;
- roll back automatically.
Facebook's October 2021 outage shows another shared fate. A command issued during routine backbone maintenance disconnected Facebook's data centres from each other and the internet. Its DNS servers, designed to withdraw their routes when they couldn't reach the data centres, then made the company unreachable. Internal tools that depended on the same network were also unavailable, which slowed recovery. Out-of-band access paths, meaning recovery tools that don't depend on the failing system, are part of the HA checklist for this reason.
Chaos engineering (Netflix)#
Chaos engineering is the discipline of experimenting on a production system, to build confidence that it can withstand turbulent conditions. Instead of waiting for a zone to fail to find out whether failover works, you fail it yourself, in a controlled way, at a time when engineers are watching.
Netflix popularised the practice after moving to AWS. In 2011 it described Chaos Monkey, a tool that randomly terminates virtual machine instances in production during business hours. Every service had to tolerate losing instances at any moment, because it would happen, every day. Netflix open-sourced Chaos Monkey in 2012. The wider "Simian Army" added:
- Chaos Gorilla, to simulate the loss of a whole availability zone;
- Chaos Kong, to simulate the loss of a whole region, by evacuating traffic from it;
- Latency Monkey, to inject delays.
Netflix later moved to more targeted, safer tooling. FIT (Failure Injection Testing) injects failures into specific requests, and ChAP (Chaos Automation Platform) runs experiments against a small slice of traffic and compares it with a control group.
The method, as described in "Chaos Engineering" (Basiri et al., IEEE Software, 2016) and on principlesofchaos.org, is the scientific method applied to resilience:
- Define steady state as a measurable business output, not a system metric. Netflix used stream starts per second.
- Form a hypothesis: "Steady state will continue in both the control and the experimental group when we fail X."
- Introduce real-world events: instance termination, a zone or region loss, latency, errors from a dependency, clock skew, full disks.
- Try to disprove the hypothesis by comparing the experimental group with the control group.
- Minimise the blast radius: start small, with automated abort conditions.
- Run in production, because staging differs in traffic, data and configuration, and automate experiments to run continuously.
Game days are the manual, scheduled cousin of chaos experiments. A team picks a failure scenario, announces a window, injects the failure (or simulates it), and runs the incident response as if it were real. Amazon has used game days for many years, and the practice is widespread. Game days test the people and the processes as well as the software: runbooks, paging, dashboards, access and decision-making.
Chaos engineering, in depth: doing it safely and usefully#
Start without chaos. Before injecting failures in production, a team needs:
- monitoring that would show the impact (dashboards on the steady-state metric);
- the ability to abort quickly;
- a basic level of redundancy, because there is no point killing instances of a service that runs on one instance.
The first experiments run in staging, or in production with tiny scope: one instance, in off-peak hours, with the team watching.
Choose experiments from your failure history. Good candidates are past incidents, known weak dependencies, and the failure modes in your HA design document. Typical experiments, roughly in order of maturity:
- Terminate a random instance of a stateless service.
- Add 200 ms of latency to calls to one dependency. Do timeouts and fallbacks work?
- Make a dependency return errors. Does the circuit breaker open? Does the page degrade?
- Fail over the database primary. How long are writes unavailable? Do clients reconnect?
- Drain a zone: shift all traffic out of one AZ. Does the remaining capacity hold at peak?
- Exhaust a resource: fill a disk, exhaust a connection pool, expire a certificate in a test environment.
- Evacuate a region: shift its traffic to the others. This needs the multi-region capacity described earlier.
Measure in business terms. "Error rate on the checkout API stayed below 0.1%, and orders per minute stayed within 2% of the control group" is a meaningful result. "CPU went up" isn't.
Automate abort conditions. The experiment stops automatically if the steady-state metric deviates beyond a threshold. Tools such as Gremlin, AWS Fault Injection Service (with CloudWatch-alarm stop conditions), Chaos Mesh and LitmusChaos (for Kubernetes) support this.
What chaos finds. In practice, chaos experiments most often uncover:
- timeouts that are missing or too long;
- retry storms;
- hard dependencies that were believed to be soft ("the page fails if recommendations are down");
- capacity that's insufficient after a zone loss;
- alerts that don't fire;
- runbooks that are wrong;
- failover that works but takes ten times longer than assumed.
Each finding is a real outage that didn't happen.
Load testing is a partner practice. Facebook's Kraken system (Veeraraghavan et al., OSDI 2016) shifted live traffic to concentrate it on a subset of servers, clusters or regions. That measured their real capacity limits under production traffic. Facebook's Maelstrom (OSDI 2018) automated draining whole data centres of traffic, so it could handle data-centre-level disasters by shifting load in a controlled, dependency-aware order, and it was exercised regularly. Drains and evacuations practised regularly turn a region failure into a routine traffic shift.
The HA checklist#
Use this checklist to review any design or production service. Each line is a question that has caused a real outage when the answer was "no".
| Area | Question |
|---|---|
| SPOFs | Have we listed every component and asked "what if this disappears now"? Includes DNS, LBs, config, secrets, discovery and the deploy system |
| Failure domains | Are replicas spread across zones (and regions, if required)? Are any "redundant" parts sharing power, network, a rack, a config or a code path? |
| Capacity | Can we lose one zone (or region) at peak without autoscaling? Is N+1 / N+2 headroom pre-provisioned? |
| State | Is every stateful component replicated, with tested automated failover and fencing? What are the RPO and RTO per data store? |
| Health | Are liveness and readiness separate? Do routing checks avoid deep dependencies, and fail open if all targets are unhealthy? |
| Self-healing | Do supervisors, orchestrators and instance groups replace failures automatically, with limits on how much they remove at once? |
| Dependencies | Does every remote call have a timeout, bounded retries with jitter, and a circuit breaker? Which dependencies are hard, which soft? |
| Degradation | Is there a documented fallback for each soft dependency? Are load-shedding priorities defined? Are kill switches in place? |
| Overload | Do we shed load early with 429/503? Do clients back off? Is there admission control at the edge? |
| Change | Are code, config and data pushes staged (canary, cell, zone, region) with automatic health checks and rollback? |
| Blast radius | Is the service cellular or sharded so one failure affects a bounded fraction of users? Are noisy tenants isolated? |
| Static stability | Does the data plane keep working if the control plane (cloud APIs, Kubernetes API, deploy system) is down? |
| Observability | Do SLOs and alerts measure user-facing symptoms? Would we detect a gray failure? See Observability |
| Recovery | Are runbooks written and rehearsed? Are backups restored regularly? Is out-of-band access available if the main network or auth is down? |
| Verification | Do we run chaos experiments, zone drains and failover drills on a schedule? |
| Dependencies' SLAs | Is our target consistent with the availability of what we depend on, given the series maths? |
When to Use It#
HA design is a matter of degree. Every production system needs some of it, and the question is how far to go. Signals that justify each step:
- Any production service: multi-AZ stateless tiers behind a load balancer, a replicated database with automated failover, health checks, backups, timeouts. This baseline is cheap on any cloud, and covers the most common failures.
- Target of 99.95% or better (about 22 minutes of downtime a month), or revenue or safety directly tied to uptime: zone-loss headroom, staged deployments, documented degradation, chaos testing of zone failures and database failover.
- Target of 99.99% or better (about 4 minutes a month), or a contractual SLA with penalties: this is beyond what human-driven recovery can achieve. Every failover must be automatic. Add cells or blast-radius isolation, and consider multi-region (active-passive at minimum).
- Regional failure must not cause an outage, because of regulators (financial services), life safety, or a global user base expecting continuity: multi-region active-active or warm standby, with practised evacuations.
- Large multi-tenant platforms, where one tenant's behaviour can affect others: cells and shuffle sharding.
- Systems that other systems depend on (identity, payments, configuration, DNS, messaging) need a higher target than their dependants, because of series availability. Identity at 99.9% caps every service that needs a login at 99.9%.
When NOT to Use It#
- When the target doesn't need it. An internal batch reporting tool that can be down for an hour costs a lot to build to 99.99%, and buys nothing. Agree the target first. See Non-Functional Requirements.
- Multi-region for a single-region user base without a regulatory need. It typically doubles infrastructure and multiplies complexity. A well-run multi-AZ deployment is enough for most businesses, provided backups are restorable in another region.
- Active-active multi-writer data without a conflict story. If you can't say how conflicting writes are resolved, run active-passive, or use partitioned ownership.
- Over-engineering early. A start-up with 1,000 users needs multi-AZ and backups, not cells and chaos platforms. A single well-provisioned database server handles thousands of writes per second. Over-engineering for write throughput that doesn't exist yet adds failure modes without adding availability.
- Chaos experiments without the basics. Injecting failures into a system with no monitoring, no redundancy or no rollback just causes outages.
How to Implement It#
- Set the target per user journey, not per system. For example: "Checkout: 99.95% of requests succeed in under 1 s, measured monthly. Browsing: 99.9%." Derive the downtime budget, and compare it with the series availability of the journey's dependencies. If a hard dependency is below the target, it must be made redundant or turned into a soft dependency.
- Draw the dependency graph of each critical journey, and mark each dependency as hard (failure fails the journey) or soft (failure degrades it). Convert hard dependencies into soft ones wherever the product allows.
- Remove SPOFs layer by layer: DNS, edge, load balancers, stateless compute, caches, queues, databases, configuration and secrets, service discovery, and the deploy pipeline.
- Spread across zones with zone-loss headroom. Use three zones, provisioned at about 150% of peak, with topology spread rules so the scheduler can't put all replicas in one zone.
- Make state highly available. Use managed multi-AZ databases, or a consensus-based failover manager with fencing. Define the RPO and RTO for each data store, and choose synchronous or asynchronous replication accordingly.
- Wire up health checks and self-healing. Use separate liveness and readiness checks, keep them cheap and local, set thresholds with hysteresis, and limit how much capacity automation may remove at once.
- Harden dependencies. Every call gets a timeout, retries with jitter inside a retry budget, and a circuit breaker. Define and test a fallback for each soft dependency. See Resilience Patterns.
- Contain the blast radius. Use staged rollouts for code and config, and add cells or shuffle sharding when the platform is multi-tenant, or the target requires it.
- Observe user-facing symptoms. Define SLOs, alert on burn rate, and build dashboards per zone and per cell, so that partial failures are visible.
- Verify continuously. Run routine failovers, zone drains, game days and automated chaos experiments, and restore backups on a schedule.
- Write and rehearse runbooks for the failures that automation doesn't cover. Make sure the people on call have the access they need, including out-of-band access.
The Kubernetes configuration below expresses several of these steps for a stateless service:
- three or more replicas, spread evenly across zones;
- separate startup, readiness and liveness probes;
- a disruption budget, so that voluntary actions (node drains, upgrades) never take more than one replica down at a time;
- a graceful-shutdown hook, so the pod stops receiving traffic before it exits.
apiVersion: apps/v1
kind: Deployment
metadata: { name: checkout }
spec:
replicas: 6 # 2 per zone; survives a zone loss at peak
strategy: { rollingUpdate: { maxUnavailable: 0, maxSurge: 2 } }
template:
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
terminationGracePeriodSeconds: 30
containers:
- name: app
image: registry.example.com/checkout:1.42.0
startupProbe: { httpGet: { path: /healthz, port: 8081 }, failureThreshold: 30, periodSeconds: 2 }
readinessProbe: { httpGet: { path: /ready, port: 8080 }, periodSeconds: 5, failureThreshold: 2 }
livenessProbe: { httpGet: { path: /healthz, port: 8081 }, periodSeconds: 10, failureThreshold: 6 }
lifecycle:
preStop: { exec: { command: ["sleep", "10"] } } # let LBs deregister first
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: checkout }
spec:
maxUnavailable: 1
selector: { matchLabels: { app: checkout } }A few details are worth calling out:
- The liveness check runs on a separate admin port (8081), so it isn't blocked behind a saturated request queue.
- Liveness tolerates a minute of failures (6 × 10 s) before restarting the container. Readiness reacts within about 10 s.
maxUnavailable: 0in the rollout keeps full capacity during deploys.
| Technology | Fits when |
|---|---|
| Cloud load balancers (AWS ALB/NLB, GCP Cloud Load Balancing, Azure Load Balancer / Front Door) | Default multi-AZ entry point with health checks; global variants for multi-region |
| Route 53 / Cloud DNS / NS1 health-checked DNS | DNS-level failover and latency- or geo-based routing between regions |
| Anycast edge (Cloudflare, Akamai, CloudFront, Google's global LB) | Global entry with fast failover between PoPs, DDoS absorption, stale-if-error |
| Kubernetes (probes, PodDisruptionBudgets, topology spread, HPA) | Self-healing and zone-aware scheduling for containerised services |
| Auto Scaling groups / managed instance groups | Self-healing VMs; replace instances failing health checks |
| RDS / Aurora Multi-AZ, Cloud SQL HA, Azure SQL zone-redundant | Managed relational failover in a region without building it yourself |
| Patroni + etcd (PostgreSQL), Orchestrator (MySQL), Redis Sentinel / Cluster | Self-managed database or cache failover with consensus-backed leadership |
| Spanner, CockroachDB, YugabyteDB, DynamoDB global tables | Natively multi-zone or multi-region data with built-in failover |
| Envoy / Istio (outlier detection, retries, circuit breaking) | Service-to-service resilience and ejection of gray-failing hosts |
| Feature-flag systems (LaunchDarkly, Unleash, homegrown) | Kill switches and degradation modes during incidents |
| Gremlin, AWS Fault Injection Service, Chaos Mesh, LitmusChaos | Controlled chaos experiments with stop conditions |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Single AZ | Cheapest; lowest latency; simplest | One data-centre event takes you down | Dev, test, or non-critical internal tools |
| Multi-AZ in one region | Survives server, rack and zone failures; synchronous replication possible; modest cost | Regional events and bad global changes still cause outages; cross-AZ data charges | The default for production |
| Multi-region active-passive | Survives region loss; simpler data model (one writer) | Standby cost; RTO of minutes; RPO greater than zero with async replication; failover rarely exercised | Regulatory or business need to survive a region loss, without needing zero RTO |
| Multi-region active-active (partitioned ownership) | All capacity used; low latency for users; fast evacuation | Ownership migration is hard; capacity headroom in every region | Global user base; strict availability targets |
| Multi-region multi-writer | Any region serves any write; no failover step | Conflicts (LWW, CRDTs) or cross-region consensus latency; hardest to reason about | Truly global data with consensus databases, or conflict-tolerant data |
| Cells / shuffle sharding | Bounded blast radius; safe staged deploys; known scale limits | More units to operate; router and migration tooling; larger minimum footprint | Large multi-tenant services; targets of 99.99% and above |
| Aggressive failure detection | Short outages | False failovers, flapping, more risk per event | Consensus-based systems built for frequent leader changes |
| Conservative failure detection | Fewer false failovers | Longer outages per real failure | Systems where failover is expensive (large caches, primary databases) |
Common Pitfalls#
- Redundancy with shared fate: two replicas in one zone, two "independent" services reading the same config store, or every region running the same bad config at once.
- No headroom for the failure you planned for: three zones each running at 80% can't absorb a zone loss. Neither can two regions each at 70%.
- Relying on autoscaling or the control plane during an incident: it is often impaired by the same event, and everyone is competing for the same capacity.
- Deep health checks used for routing, which remove every instance when a shared dependency hiccups.
- Liveness probes that restart overloaded servers, causing a restart cascade.
- Failover without fencing, which allows split brain, with two primaries accepting writes.
- Untested failover and fallback paths, which work in the design document but fail on the day.
- Global, instant config pushes that bypass the staged rollout used for code.
- Ignoring the series maths: a 99.99% target on top of six hard dependencies at 99.95% each is impossible.
- Recovery that depends on the failed system: runbooks stored in the wiki that is down, or access via SSO that is down.
Real-World Examples#
- Netflix built Chaos Monkey (described in 2011, open-sourced in 2012) to make instance loss routine. Later, Chaos Kong exercised whole-region evacuations. Netflix has written that its practice of designing for failure helped it ride out the April 2011 AWS us-east-1 outage, which took down many other well-known sites.
- Amazon / AWS publishes extensive HA guidance in the Amazon Builders' Library. Topics include static stability using availability zones, avoiding fallback in distributed systems, workload isolation using shuffle sharding, and implementing health checks. Its cell-based architecture guidance describes running services as many isolated cells.
- Google documents its SRE practices in "Site Reliability Engineering" (Beyer, Jones, Petoff and Murphy, 2016), including load shedding by criticality, error budgets and avoiding cascading failures. Spanner's multi-region configurations replicate across regions with Paxos.
- Slack described in 2023 its migration to a cellular architecture aligned with availability zones, so that it could drain an impaired zone quickly instead of suffering gray failures.
- Facebook (Meta) described Kraken (2016), for load testing with live traffic, and Maelstrom (2018), for draining data centres safely. Its October 2021 outage, caused by a backbone configuration change, showed how DNS and internal tooling can share fate with the network.
- Cloudflare's July 2019 outage (a WAF regex deployed globally) and CrowdStrike's July 2024 incident (a content update that crashed Windows hosts worldwide) are standard examples of why configuration and content pushes need staged rollouts.
Case studies that use this pattern#
- Design a Payment System: multi-AZ ledger with zero RPO, idempotent retries, and fail-closed fraud checks.
- Design a Distributed Rate Limiter: Redis replicas with automatic failover, and the fail-open versus fail-closed choice.
- Design a Metrics and Monitoring System: staying available during spikes and failures, and buffering ingestion.
- Design a Notification System: priority isolation, so that urgent notifications get through during campaign blasts.
- Design a Distributed Key-Value Store: leaderless replication, hinted handoff and quorum availability.
In the Interview#
Deep Dive: An availability budget for a real designShow
Availability targets become engineering decisions only when you spend them like a budget. Take a checkout journey with a target of 99.95% monthly. That is about 21.9 minutes of allowed unavailability in a 30-day month (43,200 minutes × 0.0005).
Step 1: dependency ceilings. The journey's hard dependencies are the edge or CDN, a regional load balancer, the checkout service, the payment provider's API and the orders database. In series, availabilities multiply:
- edge 99.99% × LB 99.99% × service 99.98% × payments 99.95% × DB 99.97% ≈ 99.88%.
That is below the target, before any of our own bugs. Each hard dependency must move up, or stop being hard.
- Payments at 99.95% are the weakest link. Add a second payment provider and route to whichever is healthy. In parallel, two independent providers at 99.95% give 1 − (0.0005)² ≈ 99.99998%, if failures are independent and routing is fast. Or accept the order and authorise asynchronously, retrying for minutes. That makes payments soft for the user-facing step, at the cost of a small fraud and decline risk.
- The database at 99.97% reflects about 13 minutes of failover and maintenance downtime a month. With consensus-based failover at about 30 s, and zero-downtime maintenance (replica-first upgrades and switchover), it can get closer to 99.99%.
Recomputed: 99.99 × 99.99 × 99.98 × ~100 × 99.99 ≈ 99.95%. That is just meeting the target, with nothing left for our own changes.
Step 2: where minutes actually go. Look at the last year's incidents for a service like this. They typically show that most lost minutes come from changes (deploys, config, feature flags) and overload, not hardware. Suppose deploys cause two incidents a month, each detected in 5 minutes and rolled back in 5. That is 20 minutes a month, nearly the whole budget. The levers are:
- Detection time: alert on burn rate within 1–2 minutes, and verify canaries automatically before widening a rollout.
- Mitigation time: one-click or automatic rollback, flags to disable new code paths, and practised zone drains.
- Blast radius: a canary at 1% of traffic that causes errors for 5 minutes costs 0.05 "full-outage minutes", not 5.
The last point is the most powerful. Unavailability is usually measured as the fraction of failed requests, so a failure that affects 1% of traffic for 10 minutes costs only 0.1 minutes of budget. Cells and staged rollouts reduce cost multiplicatively. That's why mature organisations invest in them before they invest in multi-region.
Step 3: MTTR decomposed. MTTR is not one number. Recovery-oriented thinking, as in Patterson et al.'s "Recovery-Oriented Computing" (2002) and the SRE literature, splits it into:
- Time to detect (TTD): from the start of impact to an alert. Symptom-based, burn-rate alerts are key.
- Time to engage: from the alert to a human, or automation, acting. On-call paging and runbooks matter here.
- Time to mitigate: from engagement to the end of impact. Rollback, failover, drain or a kill switch.
- Time to repair: fixing the root cause, which can happen after user impact ends.
The single most effective habit is mitigate first, diagnose later. Roll back the deploy, drain the zone, or flip the flag, and investigate once users are no longer affected.
Step 4: correlated failures break parallel maths. The parallel formula assumes independence. If the two payment providers both use the same cloud region, or the same card network, their failures are correlated. Model this with a common-cause term. If a fraction β of failures hit both, the pair's unavailability is roughly β × U + (1 − β) × U², where U is one provider's unavailability. Even β = 5% dominates: 0.05 × 0.0005 = 2.5 × 10⁻⁵, compared with 2.5 × 10⁻⁷ for the independent term. Diversity of provider, region and code path is what makes redundancy pay.
Deep Dive: Quorums and stateful clusters across zonesShow
Stateless tiers spread across zones trivially. Stateful clusters (consensus stores, databases, brokers) have to be placed with care, because their availability depends on keeping a majority alive.
Why two zones aren't enough for consensus. A Raft or Paxos cluster of n members stays available while a majority, ⌊n/2⌋ + 1, can communicate.
- 5 members across 2 zones are split 3 + 2. Losing the zone with 3 leaves 2 of 5, which is not a majority, so the cluster stops accepting writes. Losing the zone with 2 is fine. So you survive only one of the two possible zone failures.
- Even splits are worse. With 4 members split 2 + 2, losing either zone leaves 2 of 4, which is not a majority.
The fix is a third failure domain. With 3 members, one per zone, the cluster survives any one zone loss. With 5 members split 2 + 2 + 1, it survives any one zone loss, and one more member failure in most cases. If you only have two "real" sites, place a lightweight witness or tie-breaker member in a third location. It can be a small VM in another region or zone that votes but holds little or no data. Many database HA products support such witnesses (for example, SQL Server's file-share or cloud witness, and MongoDB arbiters).
Cross-region consensus. Three regions with one or two replicas each survive a region loss. But every write waits for a majority, so its latency is the round trip to the nearest other region in the quorum. Placing two regions close together, for example two in the US East and one in the US West, keeps the common-case write latency low. Spanner's and CockroachDB's multi-region configurations expose exactly these placement choices.
Leaderless quorums. Dynamo-style stores (Cassandra, Riak, DynamoDB internally) use N replicas with read and write quorums R and W, where R + W > N for overlap.
- With N = 3, one replica per zone, and W = R = 2 (QUORUM), any one zone can be lost.
LOCAL_QUORUMin Cassandra keeps quorums within a data centre, so cross-region latency stays off the request path, and the other region catches up asynchronously.- Hinted handoff and sloppy quorums, from DeCandia et al.'s "Dynamo: Amazon's Highly Available Key-value Store" (SOSP 2007), trade consistency for write availability during failures. Writes for a down replica go to a stand-in, which hands them over later.
Quorums and Leaderless Replication covers the theory.
Kafka. A replication factor of 3, one replica per zone (with rack-awareness configured), plus min.insync.replicas=2 and producers using acks=all, survives a zone loss without losing acknowledged data. Two settings decide the trade-off.
unclean.leader.election.enable=false(the default) means that if all in-sync replicas are lost, the partition stays offline rather than electing an out-of-date replica that would silently lose data. That is a deliberate choice of consistency over availability.- Kafka's newer KRaft mode replaces ZooKeeper with an internal Raft quorum of controllers, which should also be spread across three zones.
Caches. A cache's availability problem is less about losing data and more about the cold-start stampede after losing it. If one of three cache nodes dies, a third of the keys miss at once and hit the database. Remedies:
- replicas, as in Redis Cluster or ElastiCache with replicas in other zones, so a replica is promoted with a warm dataset;
- headroom in the database for the miss spike;
- request coalescing, so concurrent misses for the same key cause one database read.
Redis Cluster's failover depends on cluster-node-timeout (15 s by default) plus an election among the primaries. Expect several to tens of seconds of errors for the affected slots. During that time clients should fall back to the database, with rate limits.
Object and block storage. Managed object stores handle zone placement internally. Zonal block volumes (EBS, Persistent Disk) live in one zone. A database on a zonal volume therefore needs replication to another zone's volume. Regional persistent disks, which replicate synchronously across two zones, are one alternative on GCP.
Deep Dive: Constant work and avoiding modal behaviourShow
Many outages share a hidden cause: the system behaves differently when something fails than when everything is fine. Failure triggers a mode change. Caches start missing, clients switch to a fallback path, a control loop starts pushing large updates, or a service starts making calls it normally doesn't make. The new mode has never run at full scale. It overloads something, and the failure spreads. Designing without modes, so that the system does the same work in failure as in success, is one of the most powerful HA techniques.
The constant-work pattern. Colm MacCárthaigh's Builders' Library article "Reliability, constant work, and a good cup of coffee" describes systems that do the same amount of work regardless of what changed. Instead of pushing only changed configuration entries, which is small normally and enormous when everything changes at once, the system pushes the entire configuration on a fixed schedule. Whether one entry changed or all of them did, the load is identical. The article describes AWS services that use this approach. Route 53's health-checking system, for instance, reports the status of all checks continuously, rather than only reporting changes. The cost is some wasted work in the common case. The benefit is that the worst case is the common case, so it is always tested and always provisioned.
Push rather than pull at request time. A service that fetches its configuration or credentials on demand turns a configuration-store outage into its own outage. A service that receives pushed configuration, and keeps the last good copy, rides out the outage on cached state. That is static stability applied to data. The same principle applies to service discovery (cache endpoint lists locally), feature flags (evaluate locally from a synced ruleset), and authorisation policies (sync policies, evaluate locally).
Retries are a mode. When a dependency fails, every client retrying multiplies the load at exactly the wrong moment. Suppose each of three layers retries three times. A failure at the bottom becomes 3 × 3 × 3 = 27 attempts per original request. Retry budgets (for example, at most 10% extra load from retries), retrying at only one layer, and exponential backoff with jitter keep the failure mode close to the normal mode. Resilience Patterns covers these mechanisms.
Caches create a hidden mode. A cache with a 95% hit rate means the database is sized for 5% of reads. If the cache empties, after a restart, a failover or a mass invalidation, the database sees 20× its normal load. Either size the database for cache-less operation (expensive), or make cache loss non-modal:
- warm replicas;
- gradual warm-up, with admission control on the database;
- serving stale data rather than missing.
Metastable failures. Bronson et al. ("Metastable Failures in Distributed Systems", HotOS 2021) describe systems that enter a bad state, such as retry storms or cache-miss storms, triggered by a temporary event, and then stay in it after the trigger is gone. The work-amplifying feedback loop sustains itself. Recovery usually requires shedding load sharply to break the loop. Modal behaviour is a common source of these feedback loops. The Availability, Reliability and Fault Tolerance page covers metastability in more depth.
Practical heuristics:
- Prefer designs where failure reduces work. Failing a dependency means skipping it, not retrying it harder.
- Make recovery paths the normal paths. Restarts use the same startup code, failovers happen routinely, and evacuations are practised.
- Bound every amplifier: retries, fan-out, queue sizes, the number of hosts automation may remove, and the amount of configuration a single push may change.
- Watch for "it only does this when" in design reviews. Every such phrase names a mode that needs a test and a capacity plan.
Deep Dive: Multi-region active-active, ownership and evacuationShow
Running in several regions at once is the top rung of HA. Most of its difficulty lies in routing, data ownership and practised evacuation, not in the servers.
Routing users to regions. There are two main approaches.
- Latency- or geo-based DNS, such as Route 53 latency routing or NS1 filter chains, returns the nearest healthy region. It is simple, but failover is bounded by TTLs and client caching. Some clients cache DNS for much longer than the TTL.
- Anycast global load balancers (Google's global LB, AWS Global Accelerator, Cloudflare) give users one stable IP address. The provider's edge routes each connection to a healthy region, and failover takes seconds without DNS changes.
Either way, the router needs to know region health. Probes alone can't capture "region up but degraded". Mature systems combine probes with an operator-controlled weight per region, so that a human, or automation acting on SLO burn, can drain a region deliberately.
Data ownership. With partitioned ownership, each user, tenant or entity has a home region, recorded in a strongly consistent placement directory. The directory is replicated globally, and changed only by a careful control-plane workflow. Requests that land in the wrong region are proxied to, or redirected to, the home region for writes. Reads may be served locally from async replicas, if the product tolerates staleness.
The ownership handover protocol must avoid two regions writing for the same entity at once. A safe sequence:
- Mark the entity moving. The old region stops accepting writes for it, and clients get "retry shortly".
- Wait until the replication stream to the new region has applied all writes up to the stop point. This is the RPO boundary.
- Update the directory atomically, with an incremented epoch.
- The new region starts accepting writes, and rejects any writes stamped with the old epoch.
For a planned move, this takes seconds of write unavailability per entity. In an emergency evacuation, when the old region is unreachable, step 2 can't complete. You either wait (availability loss) or proceed and accept losing the unreplicated tail (the RPO). That is a business decision, made in advance, and often taken per data class. Payments wait for reconciliation. Social posts accept the loss.
Capacity for evacuation. Each region must absorb its share of a failed region's load. With three regions at equal load, each must run at no more than about 66% of capacity at peak. With two regions, the limit is 50%. Holding this headroom is the largest cost of active-active, so many organisations accept a slower evacuation, scaling up the survivors over minutes, for a lower standing cost. That only works if the scale-up doesn't depend on a control plane impaired by the same event.
Partitions look like failures. Suppose region A can't reach region B. Is B down, or is the link down? If both regions decide the other is dead and take ownership of its users, you get global split brain. Defences:
- a third region, or an external witness, acts as tie-breaker for ownership decisions (majority rule);
- regional failover decisions are kept with humans, using automation for the execution;
- leases on ownership expire if not renewed, so a region cut off from the directory majority stops accepting writes for entities it can't prove it owns.
Evacuation as routine. The evacuation path must be exercised regularly, or it will fail on the day. Netflix has described evacuating AWS regions as a routine exercise (Chaos Kong), shifting all traffic out of one region and verifying that the others carry it. Facebook's Maelstrom drained data centres in production regularly. Practised evacuations also serve maintenance, since you can drain a region to upgrade it, which keeps the path in daily use.
Do you need it? The honest analysis compares the expected cost of regional outages with the standing cost of active-active. The expected cost is probability × duration × the cost per minute, plus reputation and regulatory risk. The standing cost is roughly 1.5–2× infrastructure, plus engineering time and slower feature development. Many companies conclude that multi-AZ, plus a tested warm standby or pilot light in a second region, gives most of the benefit at a fraction of the cost. Disaster Recovery and Backups covers those options.
Key Takeaways#
- High availability is designed to a target. Set it per user journey, check it against the series maths of the journey's hard dependencies, and spend it like a budget.
- Remove single points of failure at every layer, including DNS, configuration, secrets, service discovery, the deploy system and people, not just servers.
- Redundancy only helps across independent failure domains. Spread across three zones, and provision z / (z − 1) of peak capacity (150% for three zones) so you can lose one zone without autoscaling.
- Stateful failover is the hard part. Use leases in a consensus store, a majority quorum, fencing of the old primary, and idempotent client retries, to fail over in tens of seconds without split brain.
- Separate liveness from readiness, keep routing health checks local and cheap, fail open when every target looks unhealthy, and limit how much capacity automation may remove.
- Degrade gracefully. Classify features as critical, degradable or optional, prepare tested fallbacks, shed the least important load first, and decide fail-open or fail-closed per component.
- Limit blast radius with cells, shuffle sharding and staged rollouts of code and configuration. Most large outages are changes applied everywhere at once.
- Verify continuously with chaos experiments, zone drains, failover drills and backup restores, because recovery paths that rarely run rarely work.
- Prefer designs without modes. Constant work, pushed configuration and bounded amplifiers make the failure path the same as the normal path.