AlgoViz

Achieving high availability

medium 30 min

High availability is built from four pillars: spare copies of everything (redundancy), a way to switch to them (failover), a way to share work between them (load balancing), and a way to notice failures fast (monitoring).

Video lesson · Chapter 1 of 6

Find every indispensable owner

0:00 / 4:14

Four pillars in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 1 min.

What it is

A single point of failure is a part whose loss stops everything. Achieving high availability means finding every such part and giving it a spare.

A spare alone does nothing. Something must notice that the first copy is gone (monitoring), something must move the work (failover and load balancing), and the spare must have the data and the room to do the job (redundancy).

Why it exists

No single machine can be made good enough. A part that works 99% of the time is down 7 hours a month. Two of them, where one is enough and they fail independently, are down together only 0.01% of the time: 4 minutes.

That trade is the whole idea: instead of buying perfect parts, use ordinary parts in pairs and make the switch quick and automatic. Planned work benefits as well, because you can update one copy while the other serves.

A short history

  1. 1976

    The first Tandem/16 NonStop system ships: duplicated processors, buses and disks with software that takes over.

  2. 1988

    Patterson, Gibson and Katz publish the RAID paper: many ordinary disks with redundancy instead of one expensive disk.

  3. 1998

    VRRP becomes RFC 2338: a standby router takes over the address of a failed one.

  4. 2011

    Netflix describes the Simian Army, with Chaos Monkey switching off instances on purpose to prove that failover works.

Words to know

Redundancy
More copies than you need on a normal day.
Failover
Moving work from a failed copy to a healthy one.
Active-passive
One copy works, the other waits.
Active-active
All copies work at the same time.
Health check
A regular question to a server: can you serve?
Split brain
Two copies both believe they are the primary.
Fencing
Making sure the old primary can no longer write.
Failure domain
Things that fail together: a machine, a rack, a zone, a region.

How it works

Step through the idea, or press Play.

Step 1 of 3

Find what has no spare. Walk the request path and ask: what if this box dies now?

Understand it

Start here

The supermarket checkout

Imagine a supermarket. If there is one open lane, everybody waits for one cashier, and if that cashier goes home nobody can pay. With several lanes, a manager who sends people to the shortest line, somebody who asks the cashiers whether they are well, and a spare cashier, the shop never stops.

Three lanes, a manager and a spare
1OPEN2SHUT3SHUTManagerOne lane, six waiting

Four jobs: more lanes, someone who shares the work, someone who checks, and a way to switch.

The four pillars

What holds high availability up

  • Redundancy

    Several copies of every part. Like spare batteries for a favourite toy, or the spare tyre in a car.

  • Failover

    An automatic switch to a copy. Like a substitute teacher: the teacher is ill, the lesson goes on.

  • Load balancing

    Sharing the work. Like the manager who sends each customer to the shortest checkout lane.

  • Monitoring

    Noticing fast. Like a check-up at the doctor: temperature, heartbeat, does anything hurt?

With the four pillars

  • A server dies: another one takes over
  • The database crashes: the replica is promoted
  • A network path fails: traffic takes another one

Without them

  • A server dies: the whole site is down
  • The database crashes: down, and perhaps data is lost
  • A network path fails: users cannot connect

The standard shape: two zones

Users reach a managed load balancer, which sends requests to an app machine in zone A and an app machine in zone B. Both apps use the primary database in zone A, which copies every change to a standby in zone B.
Every tier exists twice, in places that do not fail together. The load balancer is itself a managed pair.

Pillar 1

Redundancy: active-passive or active-active

Active-passiveActive-active
Normal dayOne handles 100%, one waitsBoth handle 50%
On failureThe standby is promoted, then takes overThe other already serves; it gets the rest
GoodSimple to reason about, one place for writesUses all machines, tests them all the time, more capacity
CostThe standby earns nothing while it waits; a short break during failoverData must be kept in sync; two places that write need conflict rules
Typical forDatabases, schedulers, licences per machineStateless web and API servers, read replicas
A standby still needs the data: an active-passive database copies every change. It avoids write conflicts, not copying.

Two copies, one is enough

An=1−(1−a)na=99%:  A2=1−0.012=99.99%,A3=99.9999%A_n = 1 - (1 - a)^n \qquad a = 99\%:\; A_2 = 1 - 0.01^2 = 99.99\%,\quad A_3 = 99.9999\%
True only if the copies fail independently and the switch works. A shared rack, a shared bug or a bad release takes both, so real numbers are lower.

How many spares? Example: N = 3 machines carry the peak

SchemeMachinesSurvivesNote
N3NothingEnough on a good day only
N+14Any oneThe usual choice for app servers
2N6A complete halfTwo zones, each big enough alone
2N+17A half, plus one moreCan lose a zone during maintenance

Leave room for the failure

Umax⁡=n−1n×Usafen=2: 40%,n=3: 53%,n=5: 64%(Usafe=80%)U_{\max} = \frac{n - 1}{n} \times U_{\text{safe}} \qquad n = 2:\ 40\%,\quad n = 3:\ 53\%,\quad n = 5:\ 64\% \quad (U_{\text{safe}} = 80\%)
If one of nn machines dies, the rest take its load. Two machines at 70% are not redundant: one would need 140%.

Where to put spares

Failure domains

Two copies on one machine fail together. Spread copies over the largest domain you want to survive.

DomainTypical causeSpread overPrice
ProcessA bug, out of memorySeveral processesNearly free
MachineHardware, host maintenanceSeveral machinesLow
ZonePower, cooling, network of one buildingTwo or three zonesExtra machines, about a millisecond between zones
RegionA large network or control-plane failure, a disasterTwo regionsHigh: double the system, slow replication, hard data questions
SoftwareThe same bad release everywhereStaged releasesPatience
The last row has no machines in it, and it is a very common cause: redundancy does not help when every copy runs the same mistake.

Is this part a single point of failure?

Ask it for DNS, certificates, secrets, the payment provider and the deployment system too.

Pillar 2

Failover: noticing, deciding, switching

Automatic failover

Detection is most of the time: three checks at 5 seconds are about 15 seconds before anything happens.

How long do users notice?

T=interval×threshold+decide+switch5×3+2+10=27 sT = \text{interval} \times \text{threshold} + \text{decide} + \text{switch} \qquad 5 \times 3 + 2 + 10 = 27\ \text{s}
Four nines allow 259 seconds a month: nine such failovers. Shorter checks detect sooner, and raise more false alarms.

Three ways to switch

WayHowTypical timeGoodBad
AutomaticSoftware detects and switchesSeconds to a minute or twoWorks at night without peopleFalse alarms, harder to build
DNSThe name points to another addressDetection plus TTL: often 2 to 5 minutes, longer for clients that ignore the TTLWorks between regions, no change in the clientCached answers
ManualA person decidesAbout 10 to 60 minutesFull control, no false alarmsSlow, needs people on call
Example for DNS: 3 failed checks at 30 s, plus a 60 s TTL, is about 150 seconds. Amazon RDS Multi-AZ instances document 60 to 120 seconds for an automatic failover.

Database failover without two primaries

The fence comes first. Otherwise a primary that was only slow wakes up and keeps writing.

Pillar 3

Load balancing: sharing the work

A load balancer sits between the internet and the servers, picks one for every request, and skips the unhealthy ones. The full topic is Load balancing. Here is what matters for availability.

AlgorithmHow it picksGoodBadUse when
Round robinNext in turn: R1 to S1, R2 to S2, R3 to S3, R4 to S1Simple and fairIgnores capacity and slow requestsStateless APIs, similar servers, quick requests
Least connectionsFewest open: of 5, 2 and 4 it takes the one with 2Adapts to slow requestsMust track connectionsWebSockets, long or uneven requests
WeightedBy weight: 5, 3, 2 give 50%, 30%, 20%Respects sizeWeights are tuned by handMixed sizes, canary releases
IP hashSame client address, same serverKeeps a session in placeUneven; many users behind one address; a change of servers moves peopleSession state or a local cache you cannot move
RandomAny healthy serverNo shared stateUneven for few requestsMany balancers that cannot coordinate

Pillar 4

Monitoring: health checks

One health check

Four kinds of check

KindAsksExampleUse it for
TCPIs the port open?Connect to :8080Fast and basic. A hung app can still accept connections
HTTPDoes the app answer?GET /health returns 200The default for a load balancer
DeepDo its dependencies work?GET /health/deep returns db, cache, queue: okDashboards and alerts, not for removing servers
DatabaseCan it run a query?SELECT 1, or pg_isreadyDatabase failover tools

What to do when checks fail

Failures in a rowMeaningAction
1Perhaps a network blipNothing, keep watching
2Something may be wrongRecord it, warn
3UnhealthyRemove it from the pool
2 successes after thatProbably backReturn it, with little traffic first
Different thresholds for leaving and returning stop a server from flapping in and out.

Four metrics on the dashboard

MetricStarting pointWhy
Latencyp99 under your target, for example 100 ms for an APISlow is down for users
Error rateUnder 0.1% of requests (5xx)That is 99.9%
CPUUnder 70%, or lower if it must absorb a failed neighbourRoom for failover
MemoryUnder 80%Before swapping or a kill
Starting points, not laws. Alert people on what users feel (latency, errors), and let causes (CPU, memory) explain it.

Planned failure

Releases are failovers too

  1. 1

    Drain

    Mark the server as leaving. It finishes open requests and gets no new ones.

  2. 2

    Update

    Install the new version on this copy only.

  3. 3

    Check

    Health check, then a little traffic. Compare errors and latency with the old copies.

  4. 4

    Continue or roll back

    One copy, then 10%, then all. Roll back if the numbers get worse.

Proof

Test the spare

You know it works

  • Kill one server every week, in working hours
  • Promote the standby on a fixed date
  • Restore a backup and read it
  • Write down how many seconds users noticed

You hope it works

  • The standby was never promoted
  • Its disk has been full since spring
  • The switch needs a password of a person on holiday
  • Nobody knows how to switch back

Summary

The whole topic in one minute.

Give every part a spare in a different failure domain, keep enough room that the rest can carry the load, check health from outside, and switch automatically. Active-passive is simpler, active-active uses the machines better but needs the data story solved.

Failover time is detection plus decision plus switch, so checks and thresholds matter more than the switch itself. Protect against false alarms, against split brain, and against deep checks that remove every server at once. Then test it, because an untested spare is a hope.

  • Redundancy, failover, load balancing, monitoring: a spare without the other three is useless.
  • n copies: 1 - (1 - a)^n, if they fail independently. Put them in different failure domains.
  • Failover time is detection + decision + switch. Detection usually dominates.
  • Act with a majority and fence the old primary, or you get split brain.
  • Keep room for a failed neighbour, and test the switch on purpose.

Sources