Goal and Architecture
Build a web application that survives the failure of one Availability Zone, scales with traffic, keeps the database private, and is cheap to clean up.
text
Users ─► Route 53 ─► CloudFront (static from S3, dynamic to ALB) ─► WAF
│
VPC 10.0.0.0/16 │
AZ-a ▼ AZ-b
┌ public 10.0.1.0/24 ┐ Application Load Balancer ┌ public 10.0.2.0/24 ┐
│ NAT GW a │ │ NAT GW b │
└────────────────────┘ └────────────────────┘
┌ private app 10.0.11.0/24 ┐ Auto Scaling group (EC2) ┌ private app 10.0.12.0/24 ┐
│ web/app instance │ ◄───────────────────────────►│ web/app instance │
└──────────────────────────┘ └──────────────────────────┘
┌ private data 10.0.21.0/24┐ RDS Multi-AZ (primary + standby) ┌ 10.0.22.0/24 ┐
└──────────────────────────┘ └──────────────┘
Requirements
- Two AZs, no single point of failure
- Only the load balancer is public; app and database are private
- Auto scaling on CPU or requests
- Database Multi-AZ, encrypted, automated backups
- Static files from S3 + CloudFront
- Logs and alarms
- Everything tagged
project=shop
Step 1: Network
- Create a VPC
10.0.0.0/16 with DNS hostnames enabled
- Create 6 subnets: public a/b, private app a/b, private data a/b
- Create and attach an Internet Gateway; public route table
0.0.0.0/0 → IGW for public subnets
- Create one NAT Gateway per AZ (in public subnets); each private app route table sends
0.0.0.0/0 to its own AZ NAT
- Add a gateway endpoint for S3 to the private route tables to save NAT cost
- Enable VPC Flow Logs to CloudWatch Logs or S3
bash
VPC=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --query Vpc.VpcId --output text)
aws ec2 modify-vpc-attribute --vpc-id $VPC --enable-dns-hostnames
PUBA=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.1.0/24 --availability-zone ap-south-1a --query Subnet.SubnetId --output text)
PUBB=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.2.0/24 --availability-zone ap-south-1b --query Subnet.SubnetId --output text)
APPA=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.11.0/24 --availability-zone ap-south-1a --query Subnet.SubnetId --output text)
APPB=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.12.0/24 --availability-zone ap-south-1b --query Subnet.SubnetId --output text)
DBA=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.21.0/24 --availability-zone ap-south-1a --query Subnet.SubnetId --output text)
DBB=$(aws ec2 create-subnet --vpc-id $VPC --cidr-block 10.0.22.0/24 --availability-zone ap-south-1b --query Subnet.SubnetId --output text)
IGW=$(aws ec2 create-internet-gateway --query InternetGateway.InternetGatewayId --output text)
aws ec2 attach-internet-gateway --internet-gateway-id $IGW --vpc-id $VPC
EIPA=$(aws ec2 allocate-address --domain vpc --query AllocationId --output text)
NATA=$(aws ec2 create-nat-gateway --subnet-id $PUBA --allocation-id $EIPA --query NatGateway.NatGatewayId --output text)
Step 2: Security Groups (Chain Them)
| Group | Inbound | Why |
| alb-sg | 80 and 443 from 0.0.0.0/0 | Public entry |
| app-sg | 80 (or 8080) from alb-sg only | Only the load balancer reaches instances |
| db-sg | 3306 or 5432 from app-sg only | Only the app reaches the database |
Referencing security groups instead of IP ranges keeps the rules correct while instances come and go.
Step 3: Database
bash
aws rds create-db-subnet-group --db-subnet-group-name shop-db --db-subnet-group-description "shop data subnets" --subnet-ids $DBA $DBB
aws rds create-db-instance --db-instance-identifier shop-db --engine mysql --db-instance-class db.t4g.medium \
--allocated-storage 50 --storage-type gp3 --storage-encrypted --multi-az \
--manage-master-user-password --master-username admin \
--db-subnet-group-name shop-db --vpc-security-group-ids $DBSG --no-publicly-accessible \
--backup-retention-period 7 --deletion-protectio
- Multi-AZ gives a standby in the other AZ with automatic failover
--manage-master-user-password keeps the password in Secrets Manager with rotation
- For heavy read traffic add read replicas or use Aurora
Step 4: Launch Template, Target Group, ALB and Auto Scaling
bash
# User data installs a simple web app and reads the DB secret at start
cat > userdata.sh <<'EOF'
#!/bin/bash
dnf install -y nginx
echo "Hello from $(hostname -f)" > /usr/share/nginx/html/index.html
echo "ok" > /usr/share/nginx/html/health
systemctl enable --now nginx
EOF
aws ec2 create-launch-template --launch-template-name shop-lt --launch-template-data "{
\"ImageId\":\"$AMI\",\"InstanceType\":\"t3.small\",\"SecurityGroupIds\":[\"$APPSG\"],
\"IamInstanceProfile\":{\"Name\":\"shop-ec2-profile\"},
\"MetadataOptions\":{\"HttpTokens\":\"required\"},
\"UserData\":\"$(base64 -w0 userdata.sh)\"}"
TG=$(aws elbv2 create-target-group --name shop-tg --protocol HTTP --port 80 --vpc-id $VPC --health-check-path /health --query 'TargetGroups[0].TargetGroupArn' --output text)
ALB=$(aws elbv2 create-load-balancer --name shop-alb --subnets $PUBA $PUBB --security-groups $ALBSG --query 'LoadBalancers[0].LoadBalancerArn' --output text)
aws elbv2 create-listener --load-balancer-arn $ALB --protocol HTTP --port 80 --default-actions Type=forward,TargetGroupArn=$TG
aws autoscaling create-auto-scaling-group --auto-scaling-group-name shop-asg \
--launch-template LaunchTemplateName=shop-lt,Version='$Latest' --min-size 2 --max-size 6 --desired-capacity 2 \
--vpc-zone-identifier "$APPA,$APPB" --target-group-arns $TG --health-check-type ELB --health-check-grace-period 120
aws autoscaling put-scaling-policy --auto-scaling-group-name shop-asg --policy-name cpu50 --policy-type TargetTrackingScaling \
--target-tracking-configuration '{"PredefinedMetricSpecification":{"PredefinedMetricType":"ASGAverageCPUUtilization"},"TargetValue":50}'
- IMDSv2 required (
HttpTokens=required) blocks a common credential-theft path
- ELB health checks let the ASG replace instances that fail the app check, not only the VM check
- Instances are in private subnets, outbound through NAT
Step 5: HTTPS, DNS and CDN
- Request a public certificate in ACM for
shop.example.com (DNS validation)
- Add an HTTPS listener (443) on the ALB with the certificate, and redirect 80 to 443
- Create a CloudFront distribution: origin 1 = S3 bucket (static, with Origin Access Control), origin 2 = ALB (dynamic). Route
/static/* to S3
- Create Route 53 alias records for the domain to the CloudFront distribution
- Attach AWS WAF with managed rules to CloudFront (or ALB)
Step 6: Observe and Alarm
bash
aws cloudwatch put-metric-alarm --alarm-name shop-5xx --namespace AWS/ApplicationELB --metric-name HTTPCode_Target_5XX_Count \
--dimensions Name=LoadBalancer,Value=app/shop-alb/abc123 --statistic Sum --period 60 --evaluation-periods 3 \
--threshold 10 --comparison-operator GreaterThanThreshold --alarm-actions $SNS_TOPIC --treat-missing-data notBreaching
aws cloudwatch put-metric-alarm --alarm-name shop-db-cpu --namespace AWS/RDS --metric-name CPUUtilization \
--dimensions Name=DBInstanceIdentifier,Value=shop-db --statistic Average --period 300 --evaluation-periods 3 \
--threshold 80 --comparison-operator GreaterThanThreshold --alarm-actions $SNS_TOPIC
Step 7: Test Failure
| Test | How | Expected result |
| Instance failure | Terminate one instance | ALB stops sending traffic; ASG launches a replacement |
| AZ failure | Stop all instances in one AZ (or set the subnet unavailable in a test) | The other AZ serves traffic; ASG recreates capacity |
| Database failover | aws rds reboot-db-instance --force-failover | Standby becomes primary in about 1 to 2 minutes; app reconnects through the same endpoint |
| Load spike | Run a load tool such as hey or ab against the URL | CPU target tracking adds instances |
Well-Architected Review of Your Build
| Pillar | What you did |
| Security | Private subnets, chained security groups, encryption, IMDSv2, WAF, Secrets Manager |
| Reliability | Two AZs, ASG, Multi-AZ RDS, health checks, backups |
| Performance | CloudFront, auto scaling, right-sized instances |
| Cost | Gateway endpoint for S3, scaling in when quiet, tags; consider Savings Plans and one NAT in dev |
| Operational excellence | Launch template, alarms, infrastructure as code (next step) |
| Sustainability | Graviton instances and scaling in reduce energy use |
Estimated Cost and Cleanup
- The main costs are NAT gateways, ALB, RDS Multi-AZ and EC2. Running this for a few hours costs little, running it for a month is not free-tier
- Always tag resources and set a Budget alarm
- Cleanup order: CloudFront → ALB and listeners → ASG → NAT gateways → release Elastic IPs → RDS (remove deletion protection) → endpoints → subnets → route tables → IGW → VPC
- Or define everything in CloudFormation/CDK and delete the stack in one command
Practice Extensions
- Convert the build to a CloudFormation template or CDK app
- Add ElastiCache for sessions and caching
- Replace MySQL with Aurora and add a reader
- Add a blue/green deployment with CodeDeploy or a second target group
- Add a cross-Region DR copy of backups
Conclusion
A highly available three-tier app uses a VPC with public, app and data subnets in two AZs, an ALB, an Auto Scaling group in private subnets, Multi-AZ RDS, chained security groups, CloudFront and WAF at the edge, alarms, and tested failure behavior. Tag everything and clean up in the right order.
Quick Summary: architecture; requirements; network; security groups; RDS; ALB/ASG commands; HTTPS/DNS/CDN; alarms; failure tests; Well-Architected review; cost and cleanup.