TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท cloud ยท infrastructure ยท scaling

Amazon EC2 and Auto Scaling

Rented virtual machines in the AWS cloud, booted from an image with a chosen type, storage and pricing model, and kept at the right healthy count across Availability Zones by an Auto Scaling group.

14 min6 animations

๐Ÿ“š Builds on๐ŸŽก Load balancing๐Ÿ˜๏ธ Amazon VPC: subnets, route tables and security groups

๐Ÿ–จ๏ธ Cheat sheet

Hiring a food truck

You want to sell food at a huge festival, but you don't want to buy a truck, look after it and store it all year. So you hire one from a truck hire yard. You call the yard, and a few minutes later a truck is parked on the field with its engine running, ready to serve.

You pay for the time you have it. Switch it off for the night and you stop paying for the truck itself. Hand it back and it's gone for good, and someone else can hire it. Each truck you hire is called an instance.

Instances: rented virtual machines

Amazon Elastic Compute Cloud (EC2) rents you virtual machines, called instances. Each runs on a physical host in one Availability Zone (AZ), one of several isolated data-centre groups inside an AWS Region. You call RunInstances (or click Launch in the console), EC2 picks a host with capacity, and the instance boots in minutes.

StateWhat it means
pendingBeing placed on a host and booting
runningUp; you are billed for compute time
stoppedShut down; no compute charge, but attached EBS volumes are still billed
terminatedDeleted for good; it can't be started again

You reach the instance over the network (SSH, Session Manager, or your app's own port), controlled by security groups, which are stateful firewalls attached to the instance. A stopped instance usually comes back on a different host, and its auto-assigned public IPv4 address changes unless you use an Elastic IP.

Renting a virtual machine5 steps
๐Ÿ™‹You๐ŸขTruck hire yard
Press play and watch it happen!

Models, sizes and an order form

The yard has different models. Grill trucks have extra burners, some trucks have huge fridges, and small vans are fine for a quiet day. Each model comes in sizes, from small to extra large, and a bigger truck costs more.

Kitting out every truck by hand would be slow, and no two would come out the same. So you keep a fit-out plan: the ovens, the menu and the recipes, exactly as you want them. Then you fill in an order form, called a launch template: "this model, this size, kitted out from this plan". Hand the yard the form and you get as many identical trucks as you like.

New menu? Write a new version of the form. Trucks ordered from then on arrive with the new menu.

Instance types, AMIs and launch templates

An instance type fixes the hardware: vCPUs, memory, network and local storage. Names read family, generation, attributes, size. In m7g.large, m is the general-purpose family, 7 the generation, g means an AWS Graviton (Arm) processor, and large the size.

FamilyTuned for
tBurstable: a CPU baseline plus credits for short bursts
mGeneral purpose: balanced CPU and memory
cCompute: more CPU per GiB
rMemory: more GiB per vCPU
i, dLocal storage: i fast NVMe SSD, d dense HDD
g, pGPUs

Within a family, each size from large up to 8xlarge doubles vCPUs and memory, and the price scales with them. Above that (12xlarge, 16xlarge, 24xlarge) the steps are smaller.

An Amazon Machine Image (AMI) is the template for the root disk: a snapshot of the operating system plus whatever you baked in (runtime, agent, your app), and the block device mapping. AMIs belong to a Region; copy them to use them elsewhere.

A launch template bundles everything needed to launch: AMI ID, instance type, key pair, security groups, IAM instance profile, network settings and user data (a script run at first boot). Templates are versioned, and an Auto Scaling group points at a version (or $Latest / $Default). Changing the template doesn't touch running instances; new launches use it, and an instance refresh replaces existing ones. Launch configurations are the legacy predecessor: AWS no longer adds features to them, and newer accounts can't create them.

One template, identical instances4 steps
๐Ÿ“‹ Order form๐Ÿ“˜ Fit-out plan๐ŸขTruck hire yard
Press play and watch it happen!

A cool box and a built-in fridge

Every truck has a built-in fridge. It's right there behind the counter, so grabbing things from it is very quick. Restarting the engine doesn't matter, but if you switch the truck off for the night or hand it back, the yard empties that fridge. Anything left inside is gone.

So the stock that matters goes in a cool box on wheels, called a volume. It's plugged into the truck, but it belongs to you. When the truck goes back, the cool box stays on the field, and you wheel it into the next truck.

There's one catch: it's too heavy to carry across the festival, so it only fits trucks in the same field. To move the stock further, you pack a copy into the yard's warehouse and fill a new cool box in the other field.

EBS volumes and instance store

Instances have two kinds of block storage.

EBS volumeInstance store
WhereNetwork-attached, separate from the hostDisks physically on the host
LifetimeIndependent of the instanceSurvives a reboot; lost on stop, hibernate or terminate
ScopeOne AZ; attaches only to instances in that AZTied to that one instance
Typical useRoot disks, databases, anything you keepCaches, scratch space, buffers
BackupSnapshots, stored incrementally in S3None; copy data out yourself

An EBS volume can be detached and attached to another instance in the same AZ. To move data to another AZ, take a snapshot and create a new volume from it there. By default the root volume is deleted when its instance terminates (the DeleteOnTermination flag), so snapshot it or clear the flag if you need it. Instance store is very fast and comes with the instance type, but only on types that include it (look for a d in the name, such as m7gd, or the i family).

EBS volume and instance store4 steps
๐ŸŒณ Field ATruck 1's fridge0123Your cool box0123๐ŸššTruck 1
Press play and watch it happen!

Three ways to pay

The yard lets you pay in three ways. Pay as you go: hire a truck whenever you like, for as long as you like, at the full price. Make a promise: tell the yard you'll spend a set amount every hour for one or three years, and you get a good discount on that amount.

Or take the yard's spare trucks, the ones sitting idle, called Spot trucks. They're much cheaper, but when the yard needs one back, it gives you a two-minute warning and takes it. Spare trucks are perfect for work that can stop and start again in another truck, and a bad idea for the one truck everyone is queuing at.

Pricing: On-Demand, Savings Plans, Spot

ModelYou commit toGood for
On-DemandNothing; pay for the time it runsSpiky or short-lived work, the baseline price
Savings PlansA spend in $/hour for 1 or 3 yearsSteady baseline usage
Reserved InstancesA specific instance configuration for 1 or 3 yearsThe older commitment model; zonal RIs also reserve capacity
SpotNothing, but EC2 can reclaim the instanceFault-tolerant, stateless, flexible work

A Compute Savings Plan applies across instance families, sizes and Regions (and to Fargate and Lambda); an EC2 Instance Savings Plan is locked to one family in one Region for a deeper discount. Savings Plans are a billing discount, not a capacity reservation.

Spot Instances use spare EC2 capacity at a steep discount. When EC2 needs the capacity back, it issues an interruption notice two minutes ahead, visible in instance metadata and as an EventBridge event, then stops, hibernates or terminates the instance. If the interruption behaviour is hibernate, there is no two-minute warning: hibernation begins as soon as the notice is issued. Poll for the notice, drain work and checkpoint state to S3 or another durable store. To lower the odds of interruption, diversify across instance types and AZs, for example with an Auto Scaling group mixed instances policy (On-Demand base plus Spot).

On-Demand, Savings Plans and Spot4 steps
๐ŸขTruck hire yard๐ŸššPay-as-you-go truck๐ŸššPromise truck๐Ÿ›ปSpare truck๐Ÿ““ Your notebook
Press play and watch it happen!

The festival manager

Ordering and checking trucks yourself all day is tiring. So you hire a festival manager and give them a note: "never fewer than 2 trucks, aim for 3, never more than 6". The manager and the trucks they look after are called an Auto Scaling group.

The manager orders trucks with your order form and spreads them across the festival's fields. Each field has its own power and water, so a flooded field can't close every truck at once.

The manager also keeps checking on every truck. When one breaks down, they send it back and order a fresh one. If a whole field loses power, they order trucks in a field that still has it.

Auto Scaling groups, health checks and AZs

An Auto Scaling group (ASG) is a set of instances launched from one launch template, with three numbers:

  • minimum: the group never goes below it;
  • desired capacity: what it runs right now;
  • maximum: the group never goes above it, whatever the scaling policies say.

You give the group subnets in several AZs (see VPC), and it balances instances across them. If an AZ has trouble, it launches in the healthy ones, and rebalances once the AZ is back.

The group checks health continuously. By default it uses EC2 status checks, which only say whether the instance and its host work, not whether your app does. Set the health check type to ELB and the group also trusts the load balancer's health checks (see load balancing). An unhealthy instance is terminated and replaced. The health check grace period stops a freshly booted instance from being judged before your app has started.

๐Ÿ”ง Going deeper

Gotchas

  • Treat instances as cattle, not pets: anything only on one instance (uploaded files, sessions, instance store) disappears when the group replaces it. Keep state in EBS-backed databases, S3 or a shared cache.
  • A grace period shorter than your app's start-up time makes the group kill instances that were just slow to boot, in a loop.
  • An ASG with min = max = 1 is a cheap way to get a self-healing single instance.
An Auto Scaling group keeps the count5 steps
๐ŸŒณ Field A๐ŸŒป Field B๐Ÿง‘โ€๐Ÿ’ผFestival manager
Press play and watch it happen!

The lunch rush

At the gate stands a steward who points each customer to a truck with room, called the load balancer. You give the manager one more rule: "keep every truck about half busy".

At lunchtime the queues grow and every truck gets too busy, so the manager orders another truck. As soon as it's ready, the steward starts sending customers to it. When lunch is over and the trucks are quiet, the manager picks one truck to send back. The steward stops sending it new customers, and once it has served the people already in its queue, it goes back.

Target tracking behind a load balancer

Attach the ASG to an Application Load Balancer target group. Every instance the group launches is registered as a target and gets traffic once it passes the load balancer's health check; on scale-in it is deregistered first, and the deregistration delay lets in-flight requests finish.

A target tracking policy names a metric and a target value, and the group adjusts desired capacity to hold it, within min and max. It is built to add capacity quickly and remove it cautiously. Predefined metrics include ASGAverageCPUUtilization, ASGAverageNetworkIn, ASGAverageNetworkOut and ALBRequestCountPerTarget.

1aws autoscaling put-scaling-policy \2  --auto-scaling-group-name web \3  --policy-name cpu-50 \4  --policy-type TargetTrackingScaling \5  --target-tracking-configuration '{6    "PredefinedMetricSpecification": { "PredefinedMetricType": "ASGAverageCPUUtilization" },7    "TargetValue": 50.08  }'

For a Spring Boot app, point the target group's health check at an Actuator endpoint that checks only the instance itself, such as /actuator/health/readiness (outside Kubernetes, enable it with management.endpoint.health.probes.enabled=true). Leave shared dependencies out of it: with the ELB health check type, a check that includes the database fails on every instance at once during a database outage, and the group replaces the whole fleet without fixing anything. Keep graceful shutdown on (the default since Spring Boot 3.4; set server.shutdown=graceful on older versions) so a terminating instance finishes its requests.

Target tracking behind a load balancer6 steps
๐ŸŽช Trucks on duty๐Ÿ‘ฅCustomers๐ŸฆบGate steward๐Ÿง‘โ€๐Ÿ’ผFestival manager๐ŸššTruck 1๐ŸššTruck 2
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿ’ฅFlash sale (naive)A shop that works on a normal day and falls over when the sale opens.guided design
  • ๐Ÿ›ก๏ธFlash sale (resilient)The same shop with a queue, caching and pre-warming, so the spike is survived.guided design

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Amazon EC2 and Auto Scaling, told the same way as the story.
  1. You keep today's orders only in the truck's built-in fridge, then switch the truck off for the night. What's there in the morning?
  2. Your cool box is in field A. Can you wheel it straight into a truck in field B?
  3. The yard gives your spare truck a two-minute warning. What does that tell you about using spare trucks?
  4. One truck breaks down. The manager's note says aim for 3. What does the manager do?
  5. At the lunch rush every truck is far too busy, and the rule is about half busy. What happens next?
Answer every question to check.Passing marks Amazon EC2 and Auto Scaling as done.
Got the hang of Amazon EC2 and Auto Scaling? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 4 of 12

โ† Previous on the path๐Ÿ˜๏ธ Amazon VPC: subnets, route tables and security groupsNext on the path โ†’๐Ÿชฃ Amazon S3

๐Ÿ‘‰ Read next

  • ๐ŸšAmazon CloudWatchA delivery van's dashboard: gauges, a trip log and warning lights that come on when a reading stays red.