AWS Mini Project
In this project you design a highly available web application on AWS (an online shop) and build a small Python design checker that reviews the architecture the way an experienced cloud architect would: network layout, security, resilience to an Availability Zone failure, and monthly cost.
The target architecture:
Route 53 (shop.example.com)
|
CloudFront ---- S3 bucket (static assets, private, OAC)
|
+-------------------+-------------------+ VPC 10.0.0.0/16
| public subnets: Application Load Balancer, NAT gateways
|-------------------+-------------------|
| eu-west-1a | eu-west-1b | eu-west-1c
| app instances | app instances | app instances <- Auto Scaling group
|-------------------+-------------------|
| RDS primary | RDS standby | (data subnets)
+---------------------------------------+Each step below is a complete program. The design is plain Python data, so you can change it and re-run the checks.
Step 1: Describe the design as data
Infrastructure-as-code tools describe resources declaratively; we do the same with a dictionary. The first check validates the network plan: every subnet must be inside the VPC, subnets must not overlap, and each tier must span at least two AZs.
import ipaddress
from itertools import combinations
design = {
"vpc": "10.0.0.0/16",
"subnets": {
"public-a": ("10.0.0.0/24", "eu-west-1a", "public"),
"public-b": ("10.0.1.0/24", "eu-west-1b", "public"),
"public-c": ("10.0.2.0/24", "eu-west-1c", "public"),
"app-a": ("10.0.10.0/23", "eu-west-1a", "app"),
"app-b": ("10.0.12.0/23", "eu-west-1b", "app"),
"app-c": ("10.0.14.0/23", "eu-west-1c", "app"),
"data-a": ("10.0.20.0/24", "eu-west-1a", "data"),
"data-b": ("10.0.21.0/24", "eu-west-1b", "data"),
},
}
def check_network(d):
problems = []
vpc = ipaddress.ip_network(d["vpc"])
nets = {name: ipaddress.ip_network(c) for name, (c, _, _) in d["subnets"].items()}
for name, net in nets.items():
if not net.subnet_of(vpc):
problems.append(f"{name} {net} is outside the VPC {vpc}")
for a, b in combinations(nets, 2):
if nets[a].overlaps(nets[b]):
problems.append(f"{a} and {b} overlap")
tiers = {}
for name, (_, az, tier) in d["subnets"].items():
tiers.setdefault(tier, set()).add(az)
for tier, azs in sorted(tiers.items()):
status = "ok" if len(azs) >= 2 else "SINGLE AZ"
print(f"tier {tier:<7} AZs {sorted(azs)} {status}")
if len(azs) < 2:
problems.append(f"tier {tier} is in one AZ only")
return problems
problems = check_network(design)
print("network problems:", problems or "none")tier app AZs ['eu-west-1a', 'eu-west-1b', 'eu-west-1c'] ok
tier data AZs ['eu-west-1a', 'eu-west-1b'] ok
tier public AZs ['eu-west-1a', 'eu-west-1b', 'eu-west-1c'] ok
network problems: none
The data tier uses only two AZs, which is fine: an RDS Multi-AZ instance has exactly one primary and one standby.
Step 2: Check the security groups
The rule for a three-tier design: only the load balancer is reachable from the internet; the app tier accepts traffic only from the load balancer; the database only from the app tier. The checker also flags SSH open to the world and any public database.
security_groups = {
"alb-sg": [{"port": 443, "source": "0.0.0.0/0"}, {"port": 80, "source": "0.0.0.0/0"}],
"app-sg": [{"port": 8080, "source": "sg:alb-sg"}],
"db-sg": [{"port": 5432, "source": "sg:app-sg"}],
}
resources = {
"alb": {"sg": "alb-sg", "public": True},
"app": {"sg": "app-sg", "public": False},
"db": {"sg": "db-sg", "public": False, "encrypted": True},
}
EXPECTED_SOURCE = {"app-sg": "sg:alb-sg", "db-sg": "sg:app-sg"}
def check_security(groups, res):
problems = []
for name, rules in groups.items():
for rule in rules:
if rule["port"] == 22 and rule["source"] == "0.0.0.0/0":
problems.append(f"{name}: SSH open to the internet")
if name in EXPECTED_SOURCE and rule["source"] != EXPECTED_SOURCE[name]:
problems.append(f"{name}: port {rule['port']} allowed from {rule['source']}, "
f"expected only {EXPECTED_SOURCE[name]}")
if res["db"]["public"]:
problems.append("database is publicly accessible")
if not res["db"].get("encrypted"):
problems.append("database storage is not encrypted")
return problems
print("security problems:", check_security(security_groups, resources) or "none")
# What if someone "temporarily" opens the database for debugging?
security_groups["db-sg"].append({"port": 5432, "source": "0.0.0.0/0"})
security_groups["app-sg"].append({"port": 22, "source": "0.0.0.0/0"})
for p in check_security(security_groups, resources):
print(" -", p)security problems: none
- app-sg: SSH open to the internet
- app-sg: port 22 allowed from 0.0.0.0/0, expected only sg:alb-sg
- db-sg: port 5432 allowed from 0.0.0.0/0, expected only sg:app-sg
Step 3: Survive the loss of an Availability Zone
Peak traffic needs 6 running app instances (the result of load testing). The question is not "do we have 6 instances?" but "do we still have 6 after losing any one AZ?". The checker removes each AZ in turn:
import math
PEAK_INSTANCES_NEEDED = 6
def check_az_failure(instances_per_az, needed, asg_max=None):
report = []
for failed in instances_per_az:
remaining = sum(n for az, n in instances_per_az.items() if az != failed)
ok = remaining >= needed
note = "ok" if ok else f"SHORT by {needed - remaining}"
if not ok and asg_max is not None:
note += f" until Auto Scaling replaces them (max {asg_max})"
report.append(f"lose {failed}: {remaining} instances left -> {note}")
return report
print("Design A: 2 AZs x 3 instances")
for line in check_az_failure({"eu-west-1a": 3, "eu-west-1b": 3}, PEAK_INSTANCES_NEEDED, asg_max=12):
print(" " + line)
print("Design B: 3 AZs x 3 instances")
for line in check_az_failure({"eu-west-1a": 3, "eu-west-1b": 3, "eu-west-1c": 3}, PEAK_INSTANCES_NEEDED, asg_max=12):
print(" " + line)
# How many instances per AZ are needed to stay at capacity during an AZ outage?
for azs in (2, 3, 4):
per_az = math.ceil(PEAK_INSTANCES_NEEDED / (azs - 1))
print(f"{azs} AZs: {per_az} per AZ = {per_az * azs} total ({per_az * azs / PEAK_INSTANCES_NEEDED:.0%} of peak need)")Design A: 2 AZs x 3 instances
lose eu-west-1a: 3 instances left -> SHORT by 3 until Auto Scaling replaces them (max 12)
lose eu-west-1b: 3 instances left -> SHORT by 3 until Auto Scaling replaces them (max 12)
Design B: 3 AZs x 3 instances
lose eu-west-1a: 6 instances left -> ok
lose eu-west-1b: 6 instances left -> ok
lose eu-west-1c: 6 instances left -> ok
2 AZs: 6 per AZ = 12 total (200% of peak need)
3 AZs: 3 per AZ = 9 total (150% of peak need)
4 AZs: 2 per AZ = 8 total (133% of peak need)
This is why three AZs are popular: to tolerate one AZ failure with two AZs you must run double the capacity, with three AZs only 150%. Auto Scaling would eventually launch replacements, but during a large outage capacity in the remaining AZs may be in high demand, so static stability (being ready before the failure) is safer.
Step 4: Estimate the monthly cost
A simple cost model with example prices (not real AWS prices; use the AWS Pricing Calculator for a real estimate):
EXAMPLE_PRICES = {
"app_instance_hour": 0.0416, # e.g. a small general-purpose instance
"alb_hour": 0.0252,
"alb_lcu_hour": 0.008,
"nat_hour": 0.045,
"nat_gb": 0.045,
"rds_multi_az_hour": 0.272, # primary + standby
"rds_storage_gb": 0.23, # Multi-AZ storage, $/GB-month
"s3_gb": 0.023,
"cloudfront_gb": 0.085,
}
HOURS = 730
def monthly_cost(app_instances, nat_gateways, lcu, nat_gb, db_storage_gb, s3_gb, cdn_gb):
p = EXAMPLE_PRICES
items = {
"EC2 app tier": app_instances * p["app_instance_hour"] * HOURS,
"Load balancer": (p["alb_hour"] + lcu * p["alb_lcu_hour"]) * HOURS,
"NAT gateways": nat_gateways * p["nat_hour"] * HOURS + nat_gb * p["nat_gb"],
"RDS Multi-AZ": p["rds_multi_az_hour"] * HOURS + db_storage_gb * p["rds_storage_gb"],
"S3 assets": s3_gb * p["s3_gb"],
"CloudFront": cdn_gb * p["cloudfront_gb"],
}
return items
items = monthly_cost(app_instances=9, nat_gateways=3, lcu=5, nat_gb=150, db_storage_gb=100, s3_gb=50, cdn_gb=800)
for name, cost in items.items():
print(f"{name:<14} ${cost:9.2f}")
total = sum(items.values())
print(f"{'total':<14} ${total:9.2f} per month (example prices)")
print(f"largest item: {max(items, key=items.get)}")EC2 app tier $ 273.31
Load balancer $ 47.60
NAT gateways $ 105.30
RDS Multi-AZ $ 221.56
S3 assets $ 1.15
CloudFront $ 68.00
total $ 716.92 per month (example prices)
largest item: EC2 app tier
With these numbers the EC2 app tier and the Multi-AZ database dominate. Typical next steps would be a Savings Plan for the nine instances that always run, Graviton instance types, and checking whether three NAT gateways are needed (they are, for AZ independence, unless the app tier can use VPC endpoints instead).
Step 5: The complete design review
Now combine everything into one reviewer that scores a design and prints an action list. We review two designs: a quick first draft and the improved version.
import ipaddress
import math
def review(d):
findings = [] # (severity, message)
vpc = ipaddress.ip_network(d["vpc"])
for name, (cidr, az, tier) in d["subnets"].items():
if not ipaddress.ip_network(cidr).subnet_of(vpc):
findings.append(("high", f"subnet {name} outside the VPC"))
app_azs = {az for _, az, tier in d["subnets"].values() if tier == "app"}
if len(app_azs) < 2:
findings.append(("high", "app tier runs in a single AZ"))
per_az = d["instances_per_az"]
if per_az * (len(app_azs) - 1) < d["peak_instances"]:
findings.append(("high", f"losing one AZ leaves {per_az * (len(app_azs) - 1)} of {d['peak_instances']} needed instances"))
if not d["db_multi_az"]:
findings.append(("high", "database is not Multi-AZ"))
if d["db_public"]:
findings.append(("high", "database is publicly accessible"))
if any(port == 22 for port, src in d["world_open_ports"] if src == "0.0.0.0/0"):
findings.append(("high", "SSH open to the internet (use Session Manager)"))
if d["nat_gateways"] < len(app_azs):
findings.append(("medium", f"{d['nat_gateways']} NAT gateway(s) for {len(app_azs)} AZs: one AZ failure cuts outbound access"))
if not d["cdn"]:
findings.append(("medium", "static assets served without CloudFront"))
if not d["backups_tested"]:
findings.append(("medium", "backups have never been restored in a test"))
if not d["budget_alert"]:
findings.append(("low", "no budget alert configured"))
weights = {"high": 15, "medium": 5, "low": 2}
score = max(0, 100 - sum(weights[s] for s, _ in findings))
return score, sorted(findings, key=lambda f: ["high", "medium", "low"].index(f[0]))
draft = {
"vpc": "10.0.0.0/16",
"subnets": {"public-a": ("10.0.0.0/24", "eu-west-1a", "public"),
"app-a": ("10.0.10.0/23", "eu-west-1a", "app"),
"data-a": ("10.0.20.0/24", "eu-west-1a", "data")},
"instances_per_az": 6, "peak_instances": 6,
"db_multi_az": False, "db_public": True,
"world_open_ports": [(443, "0.0.0.0/0"), (22, "0.0.0.0/0")],
"nat_gateways": 1, "cdn": False, "backups_tested": False, "budget_alert": False,
}
improved = {
"vpc": "10.0.0.0/16",
"subnets": {f"{tier}-{az[-1]}": (cidr, az, tier) for tier, az, cidr in [
("public", "eu-west-1a", "10.0.0.0/24"), ("public", "eu-west-1b", "10.0.1.0/24"), ("public", "eu-west-1c", "10.0.2.0/24"),
("app", "eu-west-1a", "10.0.10.0/23"), ("app", "eu-west-1b", "10.0.12.0/23"), ("app", "eu-west-1c", "10.0.14.0/23"),
("data", "eu-west-1a", "10.0.20.0/24"), ("data", "eu-west-1b", "10.0.21.0/24")]},
"instances_per_az": 3, "peak_instances": 6,
"db_multi_az": True, "db_public": False,
"world_open_ports": [(443, "0.0.0.0/0")],
"nat_gateways": 3, "cdn": True, "backups_tested": True, "budget_alert": True,
}
for name, d in [("draft", draft), ("improved", improved)]:
score, findings = review(d)
print(f"{name}: score {score}/100")
for severity, message in findings:
print(f" [{severity.upper():<6}] {message}")
if not findings:
print(" no findings: ready for a Well-Architected review")draft: score 13/100
[HIGH ] app tier runs in a single AZ
[HIGH ] losing one AZ leaves 0 of 6 needed instances
[HIGH ] database is not Multi-AZ
[HIGH ] database is publicly accessible
[HIGH ] SSH open to the internet (use Session Manager)
[MEDIUM] static assets served without CloudFront
[MEDIUM] backups have never been restored in a test
[LOW ] no budget alert configured
improved: score 100/100
no findings: ready for a Well-Architected review
The draft "works" on a sunny day, but a single AZ problem, a leaked SSH key or a database scan from the internet would take the shop down or expose its data. The improved design fixes every finding.
Step 6: From the model to real infrastructure
The checked design maps directly to infrastructure as code. A fragment of the CloudFormation template for the app tier:
Resources:
AppSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: app tier, only from the load balancer
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
SourceSecurityGroupId: !Ref AlbSecurityGroup
AppGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
VPCZoneIdentifier: [!Ref AppSubnetA, !Ref AppSubnetB, !Ref AppSubnetC]
MinSize: "9"
MaxSize: "18"
DesiredCapacity: "9"
HealthCheckType: ELB
HealthCheckGracePeriod: 120
TargetGroupARNs: [!Ref AppTargetGroup]
LaunchTemplate:
LaunchTemplateId: !Ref AppLaunchTemplate
Version: !GetAtt AppLaunchTemplate.LatestVersionNumber
Database:
Type: AWS::RDS::DBInstance
DeletionPolicy: Snapshot
Properties:
Engine: postgres
DBInstanceClass: db.m7g.large
MultiAZ: true
StorageEncrypted: true
PubliclyAccessible: false
AllocatedStorage: "100"
ManageMasterUserPassword: true
DBSubnetGroupName: !Ref DataSubnetGroup
VPCSecurityGroups: [!Ref DbSecurityGroup]aws cloudformation deploy --stack-name shop-prod --template-file shop.yaml \
--capabilities CAPABILITY_IAMIdeas to extend the project
- Add a check that every resource has
projectandenvtags. - Model a Region failure: which components need a second Region (Route 53 failover, Aurora Global Database, S3 replication)?
- Add a Route 53 health check and failover record to the design and check that the TTL is short.
- Replace the EC2 app tier with ECS on Fargate and compare the cost model.
- Read the design from a real CloudFormation template (YAML) instead of a dictionary.
Test yourself
Peak load needs 6 instances. With 3 AZs, how many instances per AZ keep full capacity if one AZ fails?
- 2
- 3
- 6
- 1
Why does the improved design use one NAT gateway per AZ?
- NAT gateways are free
- So an AZ failure doesn't cut outbound internet access for the other AZs
- AWS requires three
- To get a static IP per instance
Which tier should be the only one reachable from the internet in a three-tier design?
- The database
- The app instances
- The load balancer (and CDN)
- All of them