
Course 5 ยท Scalable and cloud-native architectures
The power to grow and heal on its own
๐ฏ By the end of today
- You can explain the difference between high availability and scalability, and design for both with a load balancer and an Auto Scaling group.
- Your app runs on containers that replace themselves, grow under load and shrink back, driven by an autoscaler you wrote (project M4).
- You can pick between virtual machines, containers and serverless and defend the choice on cost and effort.
- You can put CloudFront in front of a static site and explain cache hits, TTLs and invalidations.
- You can build an event-driven flow where an alarm calls a Lambda function through SNS, and explain why that's how autoscaling works.
๐๏ธ The plan for today
| Time | What | Where |
|---|---|---|
| 0:00 (30 min) | HA vs scalability, load balancing, Auto Scaling, what target tracking does under the hood | Lecture |
| 0:30 (20 min) | Multi-AZ, multi-region, Route 53 routing, caching and CloudFront | Lecture |
| 0:50 (30 min) | Containers in production, serverless, event-driven, microservices, the platform 3.0 landscape | Lecture |
| 1:20 (10 min) | Break | |
| 1:30 (35 min) | Project M4, steps 1 and 2: two containers, the kill drill | Project |
| 2:05 (50 min) | Steps 3 and 4: your own autoscaler, load it both ways | Project |
| 2:55 (15 min) | Step 5: CloudFront over your status page | Project |
| 3:10 (35 min) | Step 6: your idea, designed in NOTES.md | Project |
| 3:45 (15 min) | Step 7: check M4, commit | Project |
โ๏ธ High availability vs scalability
These two words come up in every project defense, and people mix them up.
- High availability (HA) means the service stays up when one piece breaks,
- Scalability means it keeps up when more people show up.
Like a bakery, staying open when a cashier is sick is one thing, serving a hundred people at once is another.
Two servers in two AZs (Availability Zones, separate data centers) give you availability even if traffic never changes.
One giant server gives you some scalability and zero availability, when it dies everything dies.
- Vertical scaling (scale up): a bigger server.
- No code change, but there's a ceiling and every resize means a restart.
- Horizontal scaling (scale out): more servers behind a load balancer.
- No real ceiling and availability comes for free, but your app must run as several copies at once.
If your single app container crashes during a demo, your site is dead until someone notices.
With two containers behind your load balancer, nobody sees a thing.
Horizontal scaling is what the cloud is good at, and it only works if your servers are disposable.
๐ฆ Load balancing, the recap
You built your ALB (Application Load Balancer) in course 3.
It sends each visitor to one of the healthy containers of your target group, like a receptionist sending people to a free desk.
Every few seconds it calls GET /health on each one, and a server that keeps failing gets no more visitors.
With today's Auto Scaling group, that failing server also gets replaced.
The ALB hides a sick server, the Auto Scaling group gets rid of it, and you want both.
๐ Want more? Two kinds of health checks, and keep them shallow
| Load balancer health check | Auto Scaling health check (type ELB) | |
|---|---|---|
| Who decides | The ALB | The Auto Scaling group, trusting the ALB's verdict |
| What happens when a server fails | Visitors stop being sent to it | The server is thrown away and replaced |
| Does it fix the problem? | No, it walks around it | Yes, a fresh server takes its place |
If /health also queried the database, one slow query could mark every server unhealthy at the same moment and take the whole site down, even though the servers were fine.
A good app's /health answers from the process itself, and that's the right default.
Deep checks ("can I reach the database, the cache, the payment provider?") belong in monitoring, where they raise an alarm instead of pulling servers out.
๐ Auto Scaling
Today a crash means you, at 2 a.m., starting a new server by hand.
With Auto Scaling, AWS does it for you.
An Auto Scaling group (ASG) keeps the right number of servers running, it adds some when load grows and removes some when it's quiet, like a supermarket manager opening checkouts when the line grows.
It needs three things:
- A launch template: the recipe for one server.
- Its AMI (Amazon Machine Image, the disk it boots from), plus size, security group, instance profile and user data.
- Three numbers:
min(never fewer),max(never more, so also your cost ceiling) anddesired(how many right now). - A list of subnets in different AZs, so if one data center goes dark the other half keeps running.
A scaling policy moves desired between min and max.
Today you use target tracking, you say "keep average CPU (how busy the processor is) around 50%" and AWS adds or removes servers to stay there.
๐ Want more? Three kinds of policies, grace periods and scale-in
| Target tracking | Step scaling | Scheduled scaling | |
|---|---|---|---|
| You say | "Keep average CPU around 50%" | "If CPU > 70% add 1, if > 90% add 3" | "At 08:00 on weekdays set desired to 6" |
| Who sets up the alarms | AWS, for you | You, in CloudWatch | No alarms, a clock |
| Good for | Most web apps | Spiky traffic where you want precise reactions | Known rush hours |
| Downside | Less control over how fast it reacts | More settings to get wrong | Blind to surprises |
Start with target tracking on one metric, and use step scaling only when you can show a graph where target tracking reacted badly.
- A new server has to boot, run its user data, pull the Docker image and pass health checks, which takes minutes. The health check grace period tells the group to wait, so it doesn't kill a server that's still starting.
- Scaling in (removing servers) is slower on purpose, around 15 minutes of low load, to avoid flapping (adding and removing servers back and forth every minute).
- Scheduled scaling combines with the other two. A shop that knows Black Friday is coming hires extra staff the night before instead of waiting for the line.
๐๏ธ Multi-AZ and multi-region
Data centers do lose power, so Multi-AZ is the normal setup for anything real.
For servers that's your ASG across two AZs, you'll do it today.
For the database, RDS Multi-AZ (RDS is AWS's managed database service) keeps a twin in another AZ that receives every write.
If the main one dies, RDS switches to the twin in a couple of minutes, at the same address.
You pay for two databases to use one, like a spare tire.
Multi-region protects you when a whole region fails, and it's a much bigger step.
Your data is copied hundreds of kilometers away, DNS (the internet's phone book) sends users to the right place, and your whole stack exists twice.
๐ Want more? Active-passive, active-active, RPO and RTO
Two numbers drive the choice.
RPO (Recovery Point Objective) is how much data you can afford to lose, counted in time, "RPO 1 hour" means losing the last hour of messages is acceptable.
RTO (Recovery Time Objective) is how long you can afford to be down.
๐งญ Route 53 routing policies
Route 53 is AWS's DNS service, when someone types a name it answers with an address.
It can pick the address with a rule: the healthy region, the fastest region for this user, or the user's country.
Your project has no domain name, so these stay on paper (and in real console screenshots).
Latency routing is about speed, geolocation is about rules (law, licensing, language), and they can give different answers for the same user.
๐ Want more? The five routing policies and the DNS cache trap
| Policy | What it does | Example for your platform |
|---|---|---|
| Simple | One name, one answer | app.example.com points to your ALB |
| Failover | Main answer while it's healthy, backup answer otherwise | Frankfurt ALB first, a static "we'll be back" page on S3 as backup |
| Latency | Sends each user to the fastest region for them | Users in Montreal go to ca-central-1, users in Paris to eu-west-3 |
| Geolocation | Sends users by country or continent | French users go to the EU stack because of data residency rules |
| Weighted | Splits users by percentage | 90% to the current version, 10% to the new one (a "canary") |
Browsers and phones remember DNS answers for the record's TTL, so with a 300 second TTL some users keep hitting the dead region for up to five minutes after you switch.
โก Caching: CloudFront and friends
A cache answers requests before they reach your servers, so pages load faster and your servers do less.
CloudFront is AWS's CDN (Content Delivery Network), it keeps copies of your files in hundreds of places called edge locations, in front of your origin (an S3 bucket, a load balancer, any web server).
Like corner shops in every city, so customers don't have to drive to the factory.
- Cache hit: the edge has a fresh copy and answers in milliseconds.
- Cache miss: it fetches from the origin and keeps a copy. The
X-Cacheresponse header tells you which. - TTL: how long a copy stays fresh, 24 hours by default.
- Invalidation: you ask CloudFront to throw its copies away early, useful after a deploy.
You fix a typo in index.html and upload it to S3.
The S3 website URL shows the fix right away, the CloudFront URL still shows the typo for up to 24 hours.
CloudFront also gives you HTTPS (the padlock in the browser) on a *.cloudfront.net name for free.
๐ Want more? Cache-Control, versioned files, ElastiCache and a privacy trap
- If you cache a response holding personal data without the user in the cache key, the next visitor sees someone else's page. Cache content that's the same for everyone first.
- The TTL comes from the origin's
Cache-Controlheader, kept within the minimum, default and maximum you set on CloudFront. - Versioned file names (
app.3f9a.js) beat invalidations: new content gets a new URL that no edge has cached yet, so there's nothing to throw away. - ElastiCache (managed Redis-compatible or Memcached) is the other kind of cache, in memory, between your API and the database. With the cache-aside pattern, the API checks the cache first, and on a miss reads RDS and stores the result with a TTL. Caching a hot read for 2 seconds would cut database reads a lot during a busy class and nobody would notice. ElastiCache runs on Floci (a real Redis container), the live room board idea can use it.
๐ฆ Containers in production: ECS vs EKS vs Docker on EC2
You'll hear "we should move to Kubernetes" in every company you join, so you need to know when it's a good idea and when it isn't.
In production, someone has to start containers, restart them when they crash, spread them over machines and roll out new versions.
That's the job of an orchestrator, like a stage manager who knows which actor goes on which stage.
AWS gives you three realistic options:
- Keep Docker on EC2, as you do today.
- ECS (Elastic Container Service), AWS's own orchestrator.
- EKS (Elastic Kubernetes Service), Kubernetes run by AWS.
- Fargate adds "containers without servers" to ECS or EKS, you hand over an image and pay per second for machines you never see.
Don't run Kubernetes for a 3-container app.
It pays off with dozens of services and several teams, for three containers it adds a lot of moving parts to do what an ASG or a small ECS service already does.
If you can't name the Kubernetes feature you need that ECS lacks, you don't need Kubernetes yet.
At Alan we do run Kubernetes, and it pays off because of scale: many services, many engineers shipping every day, and an infra team that keeps it boring for everyone else.
๐ Want more? Docker on EC2 vs ECS vs EKS, side by side
| Docker on EC2 (the VM way, course 2 step 7) | ECS (on EC2 or Fargate) | EKS (managed Kubernetes) | |
|---|---|---|---|
| Who starts the containers | Your user data, one container per server | AWS's own orchestrator | Kubernetes, with AWS running its brain |
| Who looks after the servers | You (ASG + AMI) | You on EC2, nobody on Fargate | You, or nobody with Fargate |
| New versions and restarts | You script them | Built in | Built in, very flexible |
| How hard to learn | Low | Medium | High |
| Cost before running anything | None | None | \$0.10 per hour per cluster, plus extras and people's time |
| Works outside AWS | Yes | No | Yes, mostly |
| Sweet spot | 1 to 3 services, small team | Many services, AWS only, small platform team | Many services and teams, need the Kubernetes ecosystem |
Fargate is often the best answer for a small team. Kubernetes for three containers means a control plane, an ingress controller, access rules (RBAC, role-based access control) and upgrades every few months.
A 5 minute exercise now, your app grows to 3 services (the API, a moderation worker, an export job) maintained by 2 developers.
Pick Docker on EC2, ECS or EKS (the table above helps), write one sentence on why, and one on what would make you switch.
๐ชถ Serverless: Lambda and API Gateway
Keeping a server up all month for a job that runs twice a day wastes money, like renting a car for a year to go to the airport once.
With AWS Lambda you hand AWS a function, it runs when an event happens (an S3 upload, a queue message, a web request, a timer), and you pay only for the seconds it runs, like a taxi.
There's no server to patch, and it goes from zero copies to thousands on its own.
The catch is the cold start, when no warm copy is ready Lambda sets one up first, which adds up to a few seconds.
Fine for background jobs, noticeable when a user is waiting.
API Gateway is a managed front door for web APIs (routing, login checks, rate limits) that forwards requests to Lambda.
It runs on Floci too, but your project doesn't need it: your ALB is already the front door.
Your app on Lambda would cost nearly nothing at 3 a.m.
But 500 requests at once means 500 database connections on a small db.t3.micro, which falls over without a connection pooler (it shares a few connections between requests) like RDS Proxy.
๐ Want more? Lambda's limits and billing
- Billing is per invocation plus GB-seconds (memory multiplied by duration). A 200 ms function called a few thousand times a day costs close to nothing.
- 15 minutes maximum per invocation.
- 128 MB to 10,240 MB of memory, and the CPU grows with the memory you pick.
- 6 MB maximum payload for synchronous calls.
- 1,000 copies running at once per region by default.
- The
Init Durationfield in theREPORTlog line is the cold start, measured.
๐งฎ VM vs containers vs serverless
A VM (virtual machine) is a full server in software, like your EC2 instances.
| VMs (EC2 + ASG) | Containers (ECS/Fargate, EKS) | Serverless (Lambda) | |
|---|---|---|---|
| What you ship | A disk image + a boot script | A container image | A function |
| How fast it scales | Minutes | Seconds to a minute | Under a second to a few seconds |
| Cost when nobody uses it | You pay for running servers | You pay for running containers | Zero |
| Cost when busy all day | Cheapest | Close to VMs | Often the most expensive |
| Long jobs, open connections | Yes | Yes | No (15 min max) |
Spiky or rare work leans serverless, steady always-on work leans VMs or containers.
๐ Want more? Daily work and lock-in
- VMs leave you OS updates and disk images to maintain, containers leave you images and an orchestrator, and serverless leaves you almost nothing, though it's harder to test and debug on your laptop.
- Leaving AWS later is easy from VMs, a little harder from containers on ECS, and hard from Lambda.
Now pick for your platform, VM, container or serverless for each piece, with one line on why:
- (a) your app during the course, steady traffic from 52 students for 4 hours;
- (b) the same API used once a month by 3 people;
- (c) a job that resizes uploaded images;
- (d) a nightly export of all messages to S3 that takes 2 minutes;
- (e) a WebSocket server pushing new messages live to every open browser.
๐ Event-driven architecture: SQS and SNS
Add "send each message to a moderation service" as a direct call in the API, and posting becomes as slow and fragile as moderation.
If moderation is down, nobody can post.
Decoupling fixes that, the API drops an event somewhere, answers right away, and other parts handle it later.
Like a restaurant, the waiter pins the order on a rail and goes back to the tables, and the kitchen picks orders up at its own pace.
Together they give fan-out, one "new message" topic feeds a moderation queue and a statistics queue, each drained at its own pace.
A queue also turns a burst of 10,000 requests into a calm backlog instead of a hammered database.
๐ Want more? Idempotency, visibility timeout and FIFO
- SQS standard queues deliver each message at least once, so sometimes twice. Workers must be idempotent, doing the same job twice gives the same result as doing it once (setting "approved = true" is fine twice, sending a payment is not).
- When a worker picks a message, SQS hides it for the visibility timeout. If the work takes longer than that, the message reappears and a second worker starts on it, so set the timeout above your processing time.
- FIFO queues (first in, first out) keep messages in order and remove duplicates, at a lower throughput.
- A message that keeps failing moves to a dead-letter queue so it doesn't block the rest.
- An SNS subscriber that's down misses the push, unless that subscriber is a queue. Adding a new consumer means adding a subscription, with no change to the API.
๐งฑ Microservices vs monolith
A monolith is one app deployed in one piece, like your app.
Microservices split it into small services with their own code, deploys and data, talking over the network.
Teams ship on their own, but every function call becomes a network call that can fail, and finding a bug means following a request across five services.
Start with a monolith with clean internal modules, and split a piece out only for a concrete reason, like a team that needs to deploy it alone.
A small app like yours should stay a monolith, and you can defend that in front of a jury.
๐ The platform 3.0 landscape
The cloud made four things cheap enough for a startup to build, and they shook up whole industries.
You won't build them here, but you'll meet them all at work. Know their shape.
| Wave | The problem | One-line reference architecture on AWS |
|---|---|---|
| Big Data | Too much data for one database, questions nobody planned | Events land in S3 (a data lake), Glue or EMR (Spark) clean them, Athena or Redshift answer SQL questions |
| IoT (Internet of Things) | Millions of small devices sending tiny messages | Sensors speak MQTT to IoT Core, Kinesis streams the flow, Lambda reacts, Timestream or S3 keeps it |
| Social media | Feeds, friend graphs, viral spikes | A post fans out through SNS and SQS into feeds in DynamoDB, the friend graph lives in Neptune, CloudFront serves the media |
| SDN | Networks that change at the speed of code | You built one: your VPC in session 3, and session 6 turns it into a template |
Look at the arrows, not the logos. It's the same moves as your platform: decouple with queues, keep files in S3, let managed services scale, and pay per use.
๐งช Project M4: it survives, it scales, it has an edge
Your platform is private and watched, but it runs one container: if it dies, you're down, and if a crowd shows up, you're down too.
Today it gets two containers in two AZs, a kill drill, an autoscaler you write yourself, and a CDN in front.
Before you start: M3 green, source env.sh, export GROUP=gXX. Get the new checks:
# Update the check scripts from the course repo
curl -fsSL https://raw.githubusercontent.com/ricoleabricot/puff/main/starter/checks/check.sh -o checks/check.sh
chmod +x checks/check.sh# Update the check scripts from the course repo
curl.exe -fsSL https://raw.githubusercontent.com/ricoleabricot/puff/main/starter/checks/check.ps1 -o checks/check.ps1Step 1: two containers, two AZs. Your service already spans two private subnets, one per AZ. Ask for two copies.
# Two copies of your app, ECS spreads them over your two subnets
aws ecs update-service --cluster $GROUP --service $GROUP-app2 --desired-count 2
# Your load balancer's address
ALB_DNS=$(aws elbv2 describe-load-balancers --names $GROUP-alb2 \
--query 'LoadBalancers[0].DNSName' --output text)
# 30 seconds later: 8 requests, count who answered (whoami prints its Hostname)
for i in $(seq 1 8); do curl -s http://$ALB_DNS/ | grep Hostname; done | sort | uniq -c# Two copies of your app, ECS spreads them over your two subnets
aws ecs update-service --cluster $env:GROUP --service "$env:GROUP-app2" --desired-count 2
# Your load balancer's address
$ALB_DNS = aws elbv2 describe-load-balancers --names "$env:GROUP-alb2" `
--query 'LoadBalancers[0].DNSName' --output text
# 30 seconds later: 8 requests, count who answered (whoami prints its Hostname)
1..8 | ForEach-Object { (curl.exe -s "http://$ALB_DNS/") -match 'Hostname' } | Group-Object -NoElementTwo different hostnames: the load balancer spreads your users over both containers. With your own app, look at its logs instead (aws logs tail /ecs/$GROUP-app).
Step 2: the kill drill. Kill one container on purpose and watch your users not notice.
# Pick one running container
TASK=$(aws ecs list-tasks --cluster $GROUP --service-name $GROUP-app2 --query 'taskArns[0]' --output text)
# Kill it (on Floci a container is a Docker container on your machine)
docker rm -f floci-aws-ecs-${TASK##*/}-app
# Meanwhile, hit your site every 3 seconds: you want 200s all along
for i in $(seq 1 10); do curl -s -o /dev/null -w '%{http_code} ' http://$ALB_DNS/; sleep 3; done; echo
# ECS noticed and started a replacement
aws ecs describe-services --cluster $GROUP --services $GROUP-app2 --query 'services[0].[desiredCount,runningCount]'# Pick one running container
$TASK = aws ecs list-tasks --cluster $env:GROUP --service-name "$env:GROUP-app2" --query 'taskArns[0]' --output text
# Kill it (on Floci a container is a Docker container on your machine)
docker rm -f "floci-aws-ecs-$(($TASK -split '/')[-1])-app"
# Meanwhile, hit your site every 3 seconds: you want 200s all along
1..10 | ForEach-Object { curl.exe -s -o NUL -w '%{http_code} ' "http://$ALB_DNS/"; Start-Sleep 3 }; ''
# ECS noticed and started a replacement
aws ecs describe-services --cluster $env:GROUP --services "$env:GROUP-app2" --query 'services[0].[desiredCount,runningCount]'Write in NOTES.md what you saw and how long the replacement took.
Step 3: your own autoscaler. On real AWS, target tracking adds containers when CPU climbs. Floci doesn't publish CPU and doesn't scale on its own, so you build the mechanism yourself: an alarm, a topic, and a Lambda function that changes the desired count. That's exactly what AWS does for you under the hood.
The function, in Python:
cat > scaler.py <<'PY'
import json, os
import boto3
ecs = boto3.client("ecs")
def handler(event, context):
cluster, service = os.environ["CLUSTER"], os.environ["SERVICE"]
low, high = int(os.environ["MIN"]), int(os.environ["MAX"])
now = ecs.describe_services(cluster=cluster, services=[service])["services"][0]["desiredCount"]
if "Records" in event: # an alarm, through SNS
state = json.loads(event["Records"][0]["Sns"]["Message"])["NewStateValue"]
want = now + 1 if state == "ALARM" else now - 1
else: # a direct call or a schedule: {"desired": 4}
want = int(event["desired"])
want = max(low, min(high, want))
ecs.update_service(cluster=cluster, service=service, desiredCount=want)
print(f"{service}: {now} -> {want}")
return {"from": now, "to": want}
PY
# Zip it (Python's own zip, works everywhere)
python3 -m zipfile -c scaler.zip scaler.py@'
import json, os
import boto3
ecs = boto3.client("ecs")
def handler(event, context):
cluster, service = os.environ["CLUSTER"], os.environ["SERVICE"]
low, high = int(os.environ["MIN"]), int(os.environ["MAX"])
now = ecs.describe_services(cluster=cluster, services=[service])["services"][0]["desiredCount"]
if "Records" in event: # an alarm, through SNS
state = json.loads(event["Records"][0]["Sns"]["Message"])["NewStateValue"]
want = now + 1 if state == "ALARM" else now - 1
else: # a direct call or a schedule: {"desired": 4}
want = int(event["desired"])
want = max(low, min(high, want))
ecs.update_service(cluster=cluster, service=service, desiredCount=want)
print(f"{service}: {now} -> {want}")
return {"from": now, "to": want}
'@ | Set-Content scaler.py
# Zip it (PowerShell's own zip)
Compress-Archive -Path scaler.py -DestinationPath scaler.zip -ForceIts role, allowed to scale your one service and nothing else:
# Who may use the role: Lambda, and the scheduler (for the midnight deadline)
aws iam create-role --role-name $GROUP-scaler-role --assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com", "scheduler.amazonaws.com"]}, "Action": "sts:AssumeRole"}]
}'
# What it may do: read and update your service, write its logs, be invoked
aws iam put-role-policy --role-name $GROUP-scaler-role --policy-name scale-one-service --policy-document "{
\"Version\": \"2012-10-17\",
\"Statement\": [
{\"Effect\": \"Allow\", \"Action\": [\"ecs:DescribeServices\", \"ecs:UpdateService\"],
\"Resource\": \"arn:aws:ecs:us-east-1:000000000000:service/$GROUP/$GROUP-app2\"},
{\"Effect\": \"Allow\", \"Action\": [\"logs:CreateLogGroup\", \"logs:CreateLogStream\", \"logs:PutLogEvents\", \"lambda:InvokeFunction\"],
\"Resource\": \"*\"}
]
}"
SCALER_ROLE=$(aws iam get-role --role-name $GROUP-scaler-role --query Role.Arn --output text)# Who may use the role: Lambda, and the scheduler (for some ideas), in a file
@'
{"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com", "scheduler.amazonaws.com"]}, "Action": "sts:AssumeRole"}]}
'@ | Set-Content scaler-trust.json
aws iam create-role --role-name "$env:GROUP-scaler-role" --assume-role-policy-document file://scaler-trust.json
# What it may do: read and update your service, write its logs, be invoked
@"
{"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["ecs:DescribeServices", "ecs:UpdateService"],
"Resource": "arn:aws:ecs:us-east-1:000000000000:service/$env:GROUP/$env:GROUP-app2"},
{"Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "lambda:InvokeFunction"],
"Resource": "*"}
]}
"@ | Set-Content scaler-policy.json
aws iam put-role-policy --role-name "$env:GROUP-scaler-role" --policy-name scale-one-service `
--policy-document file://scaler-policy.json
$SCALER_ROLE = aws iam get-role --role-name "$env:GROUP-scaler-role" --query Role.Arn --output textThe function, wired to an alarm:
# Create the function: between 2 and 4 copies
SCALER=$(aws lambda create-function --function-name $GROUP-scaler \
--runtime python3.12 --handler scaler.handler --zip-file fileb://scaler.zip --role $SCALER_ROLE \
--environment "Variables={CLUSTER=$GROUP,SERVICE=$GROUP-app2,MIN=2,MAX=4}" \
--query FunctionArn --output text)
# A topic between the alarm and the function, and the right for SNS to call it
SCALE_TOPIC=$(aws sns create-topic --name $GROUP-scale --query TopicArn --output text)
aws sns subscribe --topic-arn $SCALE_TOPIC --protocol lambda --notification-endpoint $SCALER
aws lambda add-permission --function-name $GROUP-scaler --statement-id from-sns \
--action lambda:InvokeFunction --principal sns.amazonaws.com --source-arn $SCALE_TOPIC
# The alarm: load above 70 calls the topic, and back to OK calls it too (to scale in)
aws cloudwatch put-metric-alarm --alarm-name $GROUP-load-high \
--namespace $GROUP --metric-name Load --statistic Average --period 60 --evaluation-periods 1 \
--threshold 70 --comparison-operator GreaterThanThreshold \
--alarm-actions $SCALE_TOPIC --ok-actions $SCALE_TOPIC# Create the function: between 2 and 4 copies
$SCALER = aws lambda create-function --function-name "$env:GROUP-scaler" `
--runtime python3.12 --handler scaler.handler --zip-file fileb://scaler.zip --role $SCALER_ROLE `
--environment "Variables={CLUSTER=$env:GROUP,SERVICE=$env:GROUP-app2,MIN=2,MAX=4}" `
--query FunctionArn --output text
# A topic between the alarm and the function, and the right for SNS to call it
$SCALE_TOPIC = aws sns create-topic --name "$env:GROUP-scale" --query TopicArn --output text
aws sns subscribe --topic-arn $SCALE_TOPIC --protocol lambda --notification-endpoint $SCALER
aws lambda add-permission --function-name "$env:GROUP-scaler" --statement-id from-sns `
--action lambda:InvokeFunction --principal sns.amazonaws.com --source-arn $SCALE_TOPIC
# The alarm: load above 70 calls the topic, and back to OK calls it too (to scale in)
aws cloudwatch put-metric-alarm --alarm-name "$env:GROUP-load-high" `
--namespace $env:GROUP --metric-name Load --statistic Average --period 60 --evaluation-periods 1 `
--threshold 70 --comparison-operator GreaterThanThreshold `
--alarm-actions $SCALE_TOPIC --ok-actions $SCALE_TOPICStep 4: load it. Your app would report its own load. Here you play the app.
# A crowd arrives: load 95
aws cloudwatch put-metric-data --namespace $GROUP --metric-name Load --value 95
# Within a minute: 3 copies, and the function's own log says why
aws ecs describe-services --cluster $GROUP --services $GROUP-app2 --query 'services[0].desiredCount'
aws logs tail /aws/lambda/$GROUP-scaler --since 10m
# The crowd leaves: load 10, back to 2 within a minute
aws cloudwatch put-metric-data --namespace $GROUP --metric-name Load --value 10
aws ecs describe-services --cluster $GROUP --services $GROUP-app2 --query 'services[0].desiredCount'# A crowd arrives: load 95
aws cloudwatch put-metric-data --namespace $env:GROUP --metric-name Load --value 95
# Within a minute: 3 copies, and the function's own log says why
aws ecs describe-services --cluster $env:GROUP --services "$env:GROUP-app2" --query 'services[0].desiredCount'
aws logs tail "/aws/lambda/$env:GROUP-scaler" --since 10m
# The crowd leaves: load 10, back to 2 within a minute
aws cloudwatch put-metric-data --namespace $env:GROUP --metric-name Load --value 10
aws ecs describe-services --cluster $env:GROUP --services "$env:GROUP-app2" --query 'services[0].desiredCount'Copy the two log lines (2 -> 3, 3 -> 2) into NOTES.md.
Step 5: an edge for your status page. CloudFront serves copies of your files from close to your users, and it's what gives you HTTPS on real AWS.
# A CloudFront distribution in front of your status page bucket
read CF_ID CF_DOMAIN < <(aws cloudfront create-distribution \
--origin-domain-name $GROUP-site.s3.amazonaws.com --default-root-object index.html \
--query 'Distribution.[Id,DomainName]' --output text)
# On real AWS: https://$CF_DOMAIN. On Floci it answers here:
curl http://$CF_ID.cloudfront.localhost.floci.io:4566/# A CloudFront distribution in front of your status page bucket
$CF_ID, $CF_DOMAIN = (aws cloudfront create-distribution `
--origin-domain-name "$env:GROUP-site.s3.amazonaws.com" --default-root-object index.html `
--query 'Distribution.[Id,DomainName]' --output text) -split '\s+'
# On real AWS: https://$CF_DOMAIN. On Floci it answers here:
curl.exe "http://$CF_ID.cloudfront.localhost.floci.io:4566/"Step 6: your idea. Your group picked one of the three EPITA ideas on the Project page. Write in NOTES.md, under a ## Idea heading: the problem in one line, the option you pick and why, one option you rejected and why. Each idea reuses pieces you already have:
- The midnight deadline: a schedule that calls your scaler before the rush. EventBridge Scheduler works on Floci:
# At 23:20 on deadline day, your scaler goes to 4 containers
cat > prewarm.json <<EOF
{"Arn": "$SCALER", "RoleArn": "$SCALER_ROLE", "Input": "{\"desired\": 4}"}
EOF
aws scheduler create-schedule --name $GROUP-prewarm \
--schedule-expression "at(2026-11-25T23:20:00)" --flexible-time-window Mode=OFF \
--target file://prewarm.json# At 23:20 on deadline day, your scaler goes to 4 containers (target written to a file)
@"
{"Arn": "$SCALER", "RoleArn": "$SCALER_ROLE", "Input": "{\"desired\": 4}"}
"@ | Set-Content prewarm.json
aws scheduler create-schedule --name "$env:GROUP-prewarm" `
--schedule-expression "at(2026-11-25T23:20:00)" --flexible-time-window Mode=OFF `
--target file://prewarm.json- The live room board: CloudFront in front of your load balancer too, with a cache time you choose. On Floci, put your ALB's DNS name in
.envasALB_ORIGINS=...and restart Floci (docker compose up -d) so CloudFront may reach it. - The internship CV drop: a second, private bucket (no website, no public policy), and a role that may only
s3:GetObjecton it, like your deployer. Prove an AccessDenied for anyone else, and try--region eu-west-3for the bucket.
Step 7: check, commit, push.
./checks/check.sh M4 | tee -a NOTES.md
git add -A
git commit -m "M4"
git push$r = .\checks\check.ps1 M4
$r; $r | Add-Content NOTES.md
git add -A
git commit -m "M4"
git push๐งฏ If it doesn't work
- Only one hostname in step 1: the second container is starting, wait 30 seconds and run the loop again.
- A few
502or000during the kill drill: normal for a few seconds, the load balancer needs one failed health check to stop sending traffic to the dead one. Count them, that's your outage. - The count doesn't move in step 4:
aws cloudwatch describe-alarms --alarm-names $GROUP-load-high --query 'MetricAlarms[0].StateValue', thenaws logs tail /aws/lambda/$GROUP-scaler. AccessDenied in the log means the role's resource doesn't match your service name. ResourceConflictExceptionon create-function: it already exists, useaws lambda update-function-code --function-name $GROUP-scaler --zip-file fileb://scaler.zip.python3 -m zipfilenot found: you're in a terminal without Python 3, use the Codespace or install it.
๐ธ On real AWS
You wouldn't write the scaler yourself: Application Auto Scaling does it for ECS with one target tracking policy (ECSServiceAverageCPUUtilization at 50%), and scheduled actions handle the midnight deadline.
The console's ECS service page has a "Service auto scaling" tab, and CloudWatch shows the two alarms target tracking creates for you: that's your $GROUP-load-high, written by AWS.
CloudFront would get a certificate from ACM and serve https://, which closes the "clear text" sin from course 2.
๐ฒ Today's quiz
๐ค Think about it
- Your service spans two AZs but your database lives in one. If one AZ goes down, when does your app keep working and when does it die?
- Say the database was the slow part during your load test, while API CPU stayed at 20%. Would your CPU policy add servers? Would more servers help?
index.htmlhas a 24 hour TTL and you upload a fix at 10:00. When is everyone sure to see it, and what did you do in step 4 to speed that up?- A classmate wants to move your app to Lambda "to save money". During the course (52 students, 4 hours) or once a month (3 users): when are they right?
- Each new message must now email the teacher and also go through moderation. Draw it with one SNS topic and SQS queues. What goes wrong if the email worker receives the same message twice?
๐ก Hints
- Every server points at one database address. Which AZ is that database in?
- More API servers mean more database connections, not a faster database.
- A TTL is the maximum age of a copy at each edge. Remember what
create-invalidationdid. - Compare "busy for 4 hours" with "idle 29 days a month", then look at the Lambda example about database connections.
- At-least-once delivery means duplicates happen. What does the teacher see in their inbox?