โ˜๏ธ PuffCloud Computing 101๐ŸŽž๏ธ Slides

Course 5 ยท Scalable and cloud-native architectures

The power to grow and heal on its own

๐ŸŽฏ By the end of today

๐Ÿ—“๏ธ The plan for today

TimeWhatWhere
0:00 (30 min)HA vs scalability, load balancing, Auto Scaling, what target tracking does under the hoodLecture
0:30 (20 min)Multi-AZ, multi-region, Route 53 routing, caching and CloudFrontLecture
0:50 (30 min)Containers in production, serverless, event-driven, microservices, the platform 3.0 landscapeLecture
1:20 (10 min)Break
1:30 (35 min)Project M4, steps 1 and 2: two containers, the kill drillProject
2:05 (50 min)Steps 3 and 4: your own autoscaler, load it both waysProject
2:55 (15 min)Step 5: CloudFront over your status pageProject
3:10 (35 min)Step 6: your idea, designed in NOTES.mdProject
3:45 (15 min)Step 7: check M4, commitProject

โš–๏ธ High availability vs scalability

These two words come up in every project defense, and people mix them 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.

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 checkAuto Scaling health check (type ELB)
Who decidesThe ALBThe Auto Scaling group, trusting the ALB's verdict
What happens when a server failsVisitors stop being sent to itThe server is thrown away and replaced
Does it fix the problem?No, it walks around itYes, 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.

๐ŸŽฌ Hiring cashiers when the line grows (1 min 28)

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 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 trackingStep scalingScheduled 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 alarmsAWS, for youYou, in CloudWatchNo alarms, a clock
Good forMost web appsSpiky traffic where you want precise reactionsKnown rush hours
DownsideLess control over how fast it reactsMore settings to get wrongBlind 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.
๐Ÿ“ˆ A day on a small appOpen full screen

๐Ÿ›๏ธ 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
PolicyWhat it doesExample for your platform
SimpleOne name, one answerapp.example.com points to your ALB
FailoverMain answer while it's healthy, backup answer otherwiseFrankfurt ALB first, a static "we'll be back" page on S3 as backup
LatencySends each user to the fastest region for themUsers in Montreal go to ca-central-1, users in Paris to eu-west-3
GeolocationSends users by country or continentFrench users go to the EU stack because of data residency rules
WeightedSplits users by percentage90% 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.

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.

๐Ÿช Corner shop cacheOpen full screen
๐Ÿ” 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-Control header, 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:

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 containersYour user data, one container per serverAWS's own orchestratorKubernetes, with AWS running its brain
Who looks after the serversYou (ASG + AMI)You on EC2, nobody on FargateYou, or nobody with Fargate
New versions and restartsYou script themBuilt inBuilt in, very flexible
How hard to learnLowMediumHigh
Cost before running anythingNoneNone\$0.10 per hour per cluster, plus extras and people's time
Works outside AWSYesNoYes, mostly
Sweet spot1 to 3 services, small teamMany services, AWS only, small platform teamMany 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.

๐ŸŽฌ VMs, containers, serverless (1 min 27)

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 Duration field in the REPORT log 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 shipA disk image + a boot scriptA container imageA function
How fast it scalesMinutesSeconds to a minuteUnder a second to a few seconds
Cost when nobody uses itYou pay for running serversYou pay for running containersZero
Cost when busy all dayCheapestClose to VMsOften the most expensive
Long jobs, open connectionsYesYesNo (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:

๐Ÿงฐ Pick for your platformOpen full screen

๐Ÿ”€ 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.

๐Ÿ“จ The burstOpen full screen
๐Ÿ” 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.

WaveThe problemOne-line reference architecture on AWS
Big DataToo much data for one database, questions nobody plannedEvents 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 messagesSensors speak MQTT to IoT Core, Kinesis streams the flow, Lambda reacts, Timestream or S3 keeps it
Social mediaFeeds, friend graphs, viral spikesA post fans out through SNS and SQS into feeds in DynamoDB, the friend graph lives in Neptune, CloudFront serves the media
SDNNetworks that change at the speed of codeYou 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.ps1

Step 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 -NoElement

Two 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 -Force

Its 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 text

The 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_TOPIC

Step 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:

# 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

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 502 or 000 during 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', then aws logs tail /aws/lambda/$GROUP-scaler. AccessDenied in the log means the role's resource doesn't match your service name.
  • ResourceConflictException on create-function: it already exists, use aws lambda update-function-code --function-name $GROUP-scaler --zip-file fileb://scaler.zip.
  • python3 -m zipfile not 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

๐ŸŽฒ Today's quizOpen full screen

๐Ÿค” Think about it

๐Ÿ’ก 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-invalidation did.
  • 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?

๐Ÿ“š Go deeper

Back to the timeline