Availability Zones
An availability zone is a separate data centre inside a region. If one zone stops working, your app can keep running in the others. In a test we switch off a zone and see that spreading servers over zones - with a load balancer that skips dead servers - keeps every request working.
What you will be able to do
- Explain what an availability zone is and why regions have several
- Tell zone names from zone IDs
- Place servers in chosen zones
- Measure what a zone failure does to one-zone and multi-zone setups
- Explain why health checks matter as much as spreading
The idea, in plain English
Inside each region, AWS builds several availability zones (AZs). Each zone is one or more data centres with its own power supply, cooling and network, kilometres away from the other zones - far enough that a fire, flood or power cut usually hits only one. The zones of a region are joined by fast private fibre, so servers in different zones can still talk quickly.
AWS does not promise that a zone never fails - it promises that zones fail separately. So the rule is simple: never put all of something important in one zone. Run servers in two or more zones, keep copies of data in more than one zone, and put a load balancer in front that sends traffic only to healthy servers.
We look at zones in moto (the fake AWS from Lesson 1), then run a real outage test on this laptop: three small web servers as real processes, each labelled with a zone, a small Python load balancer in front, and one zone switched off in the middle. It is a stand-in for AWS - but the failures are real requests that really failed. boto3 1.44.4, moto 5.2.5, Python 3.13.12.
Worked example: The shop’s web servers when zone ap-south-1a loses power - all in one zone, spread over three zones with a naive load balancer, and spread with health checks.
Words you will see in this lesson
A few resilience words.
Availability zone (AZ)One or more data centres in a region, with separate power, cooling and network.Zone nameWhat you type: ap-south-1a. Each account has its own mapping of names to buildings.Zone IDThe real place, the same for every account: aps1-az1.ResilienceStill working when a part fails.Single point of failureOne part whose failure stops everything.Load balancerSends each request to one of several servers (Lesson 75).Health checkA regular test of each server, so traffic goes only to healthy ones.An everyday example: a hospital with backup power
- A city has three hospitals in different neighbourhoods, each with its own power line.
- If a storm cuts the power in one neighbourhood, ambulances go to the other two.
- If all three hospitals were in one building, one fire would close them all.
- And the ambulance control room must KNOW which hospital is closed - otherwise it keeps sending patients there.
- Zones are the hospitals, the load balancer is the control room, and the health check is the phone call that says "we are closed".
Example 1 - zones and servers in moto
zones.py lists the zones of the Mumbai region and puts one server in each:
- describe_availability_zones() lists the zones: name, ID and state.
- run_instances(..., Placement={"AvailabilityZone": ...}) chooses the zone for a server. Without it, AWS picks one for you.
- Each server lands in a subnet - a slice of the network that lives in exactly ONE zone (networking: Module 5).
- As always, this is moto: nothing is created on a real account.
import os
import boto3
from moto import mock_aws
os.environ.update(AWS_ACCESS_KEY_ID="testing", AWS_SECRET_ACCESS_KEY="testing") # moto only
@mock_aws
def main():
ec2 = boto3.client("ec2", region_name="ap-south-1")
zones = ec2.describe_availability_zones()["AvailabilityZones"]
print("zones in ap-south-1:")
for zone in zones:
print(f" {zone['ZoneName']:<14} id {zone['ZoneId']:<11} {zone['State']}")
# One server in each zone: choose the zone with Placement
image = ec2.describe_images(Owners=["amazon"])["Images"][0]["ImageId"]
for zone in zones:
ec2.run_instances(ImageId=image, InstanceType="t3.medium", MinCount=1, MaxCount=1,
Placement={"AvailabilityZone": zone["ZoneName"]})
servers = [i for r in ec2.describe_instances()["Reservations"] for i in r["Instances"]]
print("servers:")
for server in servers:
print(f" {server['InstanceId']} in {server['Placement']['AvailabilityZone']} subnet {server['SubnetId']}")
main()zones in ap-south-1:
ap-south-1a id aps1-az1 available
ap-south-1b id aps1-az3 available
ap-south-1c id aps1-az2 available
servers:
i-8453691a2639808ef in ap-south-1a subnet subnet-ad2415bb03f468a60
i-436ac72293f1b972f in ap-south-1b subnet subnet-9cf46a6aea650b6c8
i-e2def673e23c0215a in ap-south-1c subnet subnet-2932e342c1fc06bc7Zone names are not the same for everyone
Look at the IDs: ap-south-1b is aps1-az3, and ap-south-1c is aps1-az2. Names and IDs are different things:
- The zone NAME (ap-south-1a) is a label for your account. AWS maps names to physical zones differently for different accounts, so that not everyone piles into "1a".
- The zone ID (aps1-az1) is the real place, the same for every account.
- So "my server is in ap-south-1a" and "your server is in ap-south-1a" may be different buildings.
- When two accounts must use the same zone - or must avoid it - compare zone IDs, not names.
Example 2 - switching off a zone
server.py is a tiny web server that answers with its zone. survive.py starts real copies of it and sends 600 requests through a small load balancer; at request 200, every server in ap-south-1a is killed - our zone losing power:
- start() launches one real process per server, each on its own port, labelled with a zone.
- send() is the load balancer: it takes the next server in turn (round robin) and asks it.
- A naive load balancer (skip_dead=False) tries one server and gives up if it does not answer.
- A better one (skip_dead=True) tries the next server and removes the dead one from its list - which is what a health check does in AWS (Lesson 75).
- Three layouts: A - 3 servers all in ap-south-1a; B - one per zone, naive; C - one per zone, skipping dead servers.
# One tiny web server that says which zone it runs in. python server.py <port> <zone>
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
PORT, ZONE = int(sys.argv[1]), sys.argv[2]
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(ZONE.encode())
def log_message(self, *args): # keep the terminal quiet
pass
HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()import itertools
import subprocess
import sys
import time
import urllib.request
from collections import Counter
REQUESTS, OUTAGE_AT = 600, 200 # zone ap-south-1a goes dark at request 200
turns = itertools.count() # round robin: 0, 1, 2, 3, ...
def start(layout):
"""layout: the zone of each server. Starts one real process per server."""
servers = []
for n, zone in enumerate(layout):
port = 9100 + n
servers.append((port, zone, subprocess.Popen([sys.executable, "server.py", str(port), zone])))
time.sleep(1.0) # give them a moment to start
return servers
def ask(port):
with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=1) as r:
return r.read().decode() # the zone that answered
def send(alive, skip_dead):
"""The load balancer: pick the next server; return the zone that answered, or None."""
tries = len(alive) if skip_dead else 1 # a naive balancer tries one server only
for _ in range(tries):
port = alive[next(turns) % len(alive)]
try:
return ask(port)
except OSError: # connection refused: the server is gone
if skip_dead:
alive.remove(port) # like a health check: stop sending it traffic
return None
def run(name, layout, skip_dead):
servers = start(layout)
alive = [port for port, _, _ in servers]
served, failed = Counter(), 0
for i in range(REQUESTS):
if i == OUTAGE_AT: # the whole zone ap-south-1a loses power
for port, zone, process in servers:
if zone == "ap-south-1a":
process.kill()
time.sleep(0.2)
zone = send(alive, skip_dead)
if zone:
served[zone] += 1
else:
failed += 1
for _, _, process in servers:
process.kill()
print(f"{name:<34} served {sum(served.values()):>3} failed {failed:>3} by zone: {dict(sorted(served.items()))}")
run("A. 3 servers, all in one zone", ["ap-south-1a"] * 3, skip_dead=True)
run("B. 1 server per zone, naive", ["ap-south-1a", "ap-south-1b", "ap-south-1c"], skip_dead=False)
run("C. 1 server per zone, skip dead", ["ap-south-1a", "ap-south-1b", "ap-south-1c"], skip_dead=True)A. 3 servers, all in one zone served 200 failed 400 by zone: {'ap-south-1a': 200}
B. 1 server per zone, naive served 467 failed 133 by zone: {'ap-south-1a': 67, 'ap-south-1b': 200, 'ap-south-1c': 200}
C. 1 server per zone, skip dead served 600 failed 0 by zone: {'ap-south-1a': 67, 'ap-south-1b': 266, 'ap-south-1c': 267}Reading the result
- A - all in one zone: the first 200 requests worked, then all 400 failed. Three servers did not help, because they shared one point of failure: the zone.
- B - spread, naive: 467 served, 133 failed. Zones 1b and 1c were fine, but every third request still went to the dead zone.
- C - spread, dead servers skipped: all 600 served, 0 failed. After the outage, 1b and 1c shared the work.
- A and C use the SAME three servers - the same bill. Only the placement and the load balancer changed.
- So resilience needs two things together: servers in more than one zone, AND a load balancer that checks which ones are alive.
Trap: spread out, but still one point of failure
Layout B looks right on a diagram - one server per zone - and still lost a third of the requests after the outage. Other ways to be "spread but not really":
- Web servers in three zones, but the database in one zone. When that zone fails, every server fails with it.
- Three zones, but each zone sized for exactly a third of the traffic. After one zone fails, the other two are overloaded. Size each zone so the rest can carry the full load.
- A health check that only asks "is the process running?" while the app inside is broken. Check something that really works, like a /health page that touches the database.
- Fix: look for every part that exists only once, and give it a partner in another zone.
Tip: In AWS you rarely write this load balancer yourself: an Application Load Balancer (Lesson 76) runs health checks and spreads traffic across zones, and Auto Scaling (Lesson 40) can start replacement servers in the healthy zones.
What runs in more than one zone
Some AWS services spread across zones for you; for others, you choose:
- Zonal - you choose one zone: an EC2 server, an EBS disk. Spreading them is your job.
- Regional - spread across zones by AWS: S3, DynamoDB, SQS, Lambda. A single zone failure does not stop them.
- Your choice - RDS databases have a Multi-AZ option that keeps a standby copy in another zone (Lesson 78 onwards).
- Cost: traffic between zones is charged per gigabyte, and a standby copy costs like a second server. Resilience is not free - but it is cheap compared with an outage.
Availability zones at a glance
List zonesNames, IDs, state.
ec2.describe_availability_zones()
Choose a zoneFor one server.
run_instances(..., Placement={"AvailabilityZone": "ap-south-1b"})Name vs IDPer account vs real place.
ap-south-1b -> aps1-az3
Resilient layoutBoth are needed.
servers in 2+ zones + load balancer with health checks
Size for failureLose one zone, still enough.
3 zones -> each can carry half the load
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Change layout C to two servers in ap-south-1a and one in ap-south-1b. How many requests does each zone serve after the outage?”
“Set OUTAGE_AT = 500. How many requests fail in each layout now?”
“In run(), kill the servers of both 1a and 1b. Which layout still serves requests?”
“In zones.py, print the zones of ap-south-2 (Hyderabad). How many are there in moto?”
What usually goes wrong
Three servers in ap-south-1a: 400 of 600 requests failed when the zone went dark.
One server per zone with a naive load balancer still failed 133 requests.
The web servers survive the zone failure; the app does not.
ap-south-1a can be a different building in another account - compare zone IDs.
After one zone fails, the others must carry everything.
Best practices
- Run every important part in at least two zones.
- Put a load balancer with real health checks in front of your servers.
- Prefer regional services (S3, DynamoDB, SQS) or Multi-AZ options for data.
- Size the remaining zones to carry the full load when one fails.
- Test failure on purpose - as survive.py does - before it happens for real.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add a "zone comes back" step to survive.py: at request 400, restart the ap-south-1a server, and make the load balancer try dead servers again every 50 requests (a real health check keeps checking). Print how many requests each zone served before the outage, during it, and after it came back.
Show hintHide hint
Keep a list of all ports next to the alive list; every 50 requests, try ask() on the dead ones and add back those that answer.
Find the single points of failure
Draw (or list) a small web app on AWS and mark every part that would stop the whole app if one zone failed.
- Include at least: a load balancer, web servers, a database, and file storage.
- For each part, write whether it is zonal, regional, or your choice (Multi-AZ).
- Mark every single point of failure and give a fix for each.
- Say how many servers each zone needs so the app survives losing one zone.
Key points
- An availability zone is a group of data centres with its own power and network; zones fail separately.
- Zone names (ap-south-1a) are per account; zone IDs (aps1-az1) are the real place.
- One zone, 3 servers: 400 of 600 requests failed in the outage.
- Three zones with a naive load balancer: 133 failed; with dead servers skipped: 0 failed.
- Same servers, same cost - placement and health checks made the difference.
Quick check before you move on
Interview questions
What is an availability zone and why do you use multiple?
One or more data centres in a region with independent power, cooling and networking, connected by low-latency links; deploying across several zones lets an application survive the failure of one.
How do you make a web application highly available within a region?
Run instances in at least two AZs behind a load balancer with health checks, use Auto Scaling to replace capacity, use Multi-AZ or regional data services, and size for the loss of one zone.
What is the difference between an AZ name and an AZ ID?
Names like us-east-1a are mapped per account to physical zones; AZ IDs like use1-az1 are consistent across accounts and are used to align or separate resources between accounts.
Quiz
- 1.
Why did layout B still fail requests?
- 2.
Why did layouts A and C cost the same?
- 3.
Why do zone names differ between accounts?
- 4.
Name one service that spreads across zones for you and one that does not.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...