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.
| State | What it means |
|---|---|
pending | Being placed on a host and booting |
running | Up; you are billed for compute time |
stopped | Shut down; no compute charge, but attached EBS volumes are still billed |
terminated | Deleted 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.
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.
| Family | Tuned for |
|---|---|
t | Burstable: a CPU baseline plus credits for short bursts |
m | General purpose: balanced CPU and memory |
c | Compute: more CPU per GiB |
r | Memory: more GiB per vCPU |
i, d | Local storage: i fast NVMe SSD, d dense HDD |
g, p | GPUs |
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.
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 volume | Instance store | |
|---|---|---|
| Where | Network-attached, separate from the host | Disks physically on the host |
| Lifetime | Independent of the instance | Survives a reboot; lost on stop, hibernate or terminate |
| Scope | One AZ; attaches only to instances in that AZ | Tied to that one instance |
| Typical use | Root disks, databases, anything you keep | Caches, scratch space, buffers |
| Backup | Snapshots, stored incrementally in S3 | None; 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).
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
| Model | You commit to | Good for |
|---|---|---|
| On-Demand | Nothing; pay for the time it runs | Spiky or short-lived work, the baseline price |
| Savings Plans | A spend in $/hour for 1 or 3 years | Steady baseline usage |
| Reserved Instances | A specific instance configuration for 1 or 3 years | The older commitment model; zonal RIs also reserve capacity |
| Spot | Nothing, but EC2 can reclaim the instance | Fault-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).
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.
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 = 1is a cheap way to get a self-healing single instance.
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.