Compute on AWS: EC2, Lambda, ECS/Fargate, EKS
System Design · Cloud Building Blocks · Basics · 20 min
Pick the right way to run code on AWS and explain how Auto Scaling adds and removes servers as traffic changes.
A row of parking spaces for servers: when the lot gets crowded, new cars (instances) pull in after a short warm-up; when it empties, cars leave one at a time, but never fewer than the minimum and never more than the lot holds.
The idea in everyday words
Getting to work: owning a car (EC2) gives full control but you do the maintenance. Leasing with service included (ECS on Fargate) means you just drive. A taxi (Lambda) shows up when you call and you pay per trip, but the first one can take a minute to arrive. A bus network (EKS) is powerful and flexible but needs people who know how to run it.
Four ways to run code
The question is always how much do you want to manage? More control means more work.
| Option | You manage | AWS manages | Billing | Great for |
|---|---|---|---|---|
| EC2 | OS, patches, scaling setup, app | Hardware, hypervisor | Per second while running | Full control, special hardware, legacy apps |
| ECS on EC2 | Container images, the EC2 fleet | Scheduling containers | EC2 instances | Containers with cost tuning |
| ECS on Fargate | Container images, CPU/memory per task | Servers, OS, placement | Per task vCPU/GB while running | Most container web services |
| EKS | Kubernetes manifests, add-ons, nodes (or Fargate) | Kubernetes control plane | Cluster fee + nodes | Teams already on Kubernetes, portability |
| Lambda | A function and its config | Everything else | Per request + duration × memory | Event-driven, spiky or glue work |
Words to know: a container is your app plus its libraries in one package (an image) that runs the same anywhere. A task (ECS) or pod (Kubernetes) is a running copy of one or more containers.
Other clouds: GCP has Compute Engine + managed instance groups, Cloud Run, Cloud Run functions and GKE. Azure has Virtual Machines + VM Scale Sets, Container Apps, Azure Functions and AKS. Open source: Kubernetes with KEDA or Knative for event-driven scaling.
EC2: instance types, AMIs and pricing models
An instance type name like m7g.large reads as: family m (general purpose), generation 7, attribute g (AWS Graviton, an ARM chip, usually better price/performance), size large.
| Family | Optimized for | Example use |
|---|---|---|
| T | Burstable CPU (credits) | Small, mostly idle services |
| M | Balanced CPU/memory | Web and app servers |
| C | Compute | Video encoding, batch, game servers |
| R / X | Memory | Caches, in-memory databases |
| I / D | Local storage | Search engines, data warehouses |
| P / G / Inf / Trn | GPUs and ML chips | Training and inference |
- An AMI (Amazon Machine Image) is the disk template a new instance boots from: OS + your baked-in software.
- A launch template stores "which AMI, which type, which security groups, which IAM role, what user-data script".
Pricing models (check the AWS pricing pages for numbers):
- On-Demand: pay by the second, no commitment.
- Savings Plans / Reserved Instances: commit to usage for 1 or 3 years for a big discount. For your steady baseline. Compute Savings Plans are the most flexible (they also cover Fargate and Lambda); EC2 Instance Savings Plans and Standard or Convertible Reserved Instances trade flexibility for a deeper discount.
- Spot: spare capacity at a deep discount, but AWS can take it back with a two-minute warning. For stateless, interruptible work.
Auto Scaling groups: capacity that follows demand
An Auto Scaling group (ASG) keeps a fleet of EC2 instances between a minimum and maximum, aiming at a desired count. It launches from a launch template, spreads instances across AZs, and replaces any instance that fails its health check (EC2 status or the load balancer's check).
Scaling policies:
- Target tracking (the usual choice): "keep average CPU at 50%". The ASG does the math.
- Step scaling: "if CPU > 70% add 2, if > 90% add 4".
- Scheduled: "every weekday at 8:00 set min to 10".
- Predictive: learns daily patterns and scales ahead of them.
The target tracking idea in one line: total load ÷ load per instance at target.
import math
cpu = [80, 85, 75, 80] # 4 instances, average 80%
target = 50
desired = math.ceil(sum(cpu) / target) # same as ceil(4 * 80 / 50)
print("desired instances:", desired) # 320 / 50 = 6.4 -> 7
Two timing details matter in interviews:
- Warm-up: a new instance needs time to boot and warm caches before it helps. Scale out early.
- Scale in slowly: removing capacity too fast causes flapping (add, remove, add). Target tracking is deliberately cautious when scaling in.
A real policy (boto3, not runnable here):
autoscaling.put_scaling_policy(
AutoScalingGroupName="web-asg",
PolicyName="cpu50",
PolicyType="TargetTrackingScaling",
TargetTrackingConfiguration={
"PredefinedMetricSpecification": {"PredefinedMetricType": "ASGAverageCPUUtilization"},
"TargetValue": 50.0,
},
)
Lambda: functions on demand
AWS Lambda runs your function when an event happens. No servers to see.
How it gets invoked:
- Synchronous: the caller waits (API Gateway, a Function URL, an ALB).
- Asynchronous: Lambda queues the event and retries on errors (S3 notifications, EventBridge, SNS).
- Poll-based (event source mapping): Lambda reads batches from SQS, Kinesis or DynamoDB Streams for you.
Execution environments: each request runs in an environment (a small micro-VM). The first request into a new environment pays a cold start: download code, start the runtime, run your init code. Later requests reuse it (warm). One environment handles one request at a time, so 100 simultaneous requests need 100 environments.
Concurrency ≈ requests per second × average duration in seconds. At 200 req/s and 0.5 s each, about 100 environments are busy. Accounts have a per-Region concurrency quota; reserved concurrency sets aside (and caps) capacity for one function, and provisioned concurrency keeps environments pre-initialized to avoid cold starts.
Limits to remember (check current quotas): a run can last at most 15 minutes; memory is configurable from 128 MB up to about 10 GB and CPU grows with memory; request and response payloads have size limits; local /tmp space is limited.
Billing: per request plus duration × memory (GB-seconds). Idle costs nothing. Since August 2025 the INIT phase is billed too for on-demand functions on managed runtimes packaged as ZIP files (heavy init code now costs money, not just latency), and Arm (Graviton) functions are cheaper per GB-second than x86. Check the Lambda pricing page for current rates.
Decision guide
Ask these questions in order:
- Is it event-driven, short (under 15 minutes) and spiky or low traffic? → Lambda.
- Is it a long-running web service or worker packaged as a container? → ECS on Fargate (simplest), or ECS on EC2 if you need cheaper steady capacity, GPUs or special instance types.
- Does the team already run Kubernetes, or need its ecosystem and portability? → EKS.
- Do you need OS-level control, special licenses, or a legacy app that isn't containerized? → EC2 in an Auto Scaling group.
| Situation | Pick | Why |
|---|---|---|
| Resize images when uploaded to S3 | Lambda | Event-driven, bursty, short |
| REST API at steady 2,000 req/s | ECS on Fargate (or EC2) | Always busy, so per-request billing is not cheaper |
| ML inference on GPUs | EC2 / ECS on EC2 / EKS | Needs GPU instance types |
| Nightly 3-hour batch job | AWS Batch or ECS task (Fargate/Spot) | Too long for Lambda |
| 50 microservices, platform team, Helm charts | EKS | Kubernetes skills and tooling already exist |
In an interview, any of these can be right. What matters is that you say why: traffic shape, run time, team skills, cost at steady state, and cold-start tolerance.
Step by step
- Start:
ASG: min 2, max 10, target 50% CPU. Each instance handles about 200 req/s at 100% CPU. Traffic 120 req/s → each of 2 instances runs at 30%.
- Traffic rises:
Traffic jumps to 348 req/s → 2 instances at 87%. Desired = ceil(2 × 87 / 50) = 4, so the ASG launches 2 instances.
- Warm-up lag:
New instances boot for about 2 minutes. Meanwhile traffic keeps climbing and the old 2 instances hit 100% CPU.
- CPU is capped:
At 100% CPU the metric can't show the true demand, so one scale-out round underestimates. The ASG needs a second and third round to catch up.
- At max size:
If the formula wants 16 but max is 10, the ASG stops at 10. Max is a cost and safety cap; beyond it, latency rises.
- Scale in:
Traffic falls. After a cooldown the ASG removes instances one at a time until it's back near 2 (the minimum, one spare per AZ).
Code example
def desired_capacity(cpu_readings, target, min_size, max_size):
if not cpu_readings: # no instances yet: start at the minimum
return min_size
total_load = sum(cpu_readings) # total work, in "percent of one instance"
desired = -(-total_load // target) # ceil: instances needed at target each
return max(min_size, min(max_size, desired))
# Simulate one busy hour, one tick per 5 minutes.
CAPACITY = 200 # req/s one instance handles at 100% CPU
TARGET, MIN, MAX = 50, 2, 10
traffic = [150, 300, 700, 1200, 1500, 1500, 1100, 600, 250, 150]
size = MIN
for minute, rps in zip(range(0, 50, 5), traffic):
per_instance = min(100, round(rps / (size * CAPACITY) * 100))
readings = [per_instance] * size
new_size = desired_capacity(readings, TARGET, MIN, MAX)
if new_size < size:
new_size = size - 1 # scale in gently, one at a time
print(f"t={minute:>2}m traffic={rps:>4}/s {size:>2} x {per_instance:>3}% CPU -> desired {new_size}")
size = new_sizeComplexity
- Time: O(n): one pass to sum the n readings
- Space: O(1): only the running total
Interview tips
Justify the compute choice with the workload: 'Traffic is spiky and requests are short, so Lambda; if it becomes steady and high, ECS on Fargate is cheaper.'
For EC2/ECS say: 'stateless app tier in an Auto Scaling group across 3 AZs, target tracking on CPU or request count per target'.
Mention warm-up and that scaling is not instant; pre-scale with scheduled or predictive scaling for known events.
Know Lambda's sharp edges: 15-minute max run, cold starts, concurrency quotas, and that each environment handles one request at a time.
Mention Spot for fault-tolerant workers and Savings Plans for the steady baseline when cost comes up.
Challenge: Target Tracking: Desired Capacity
An Auto Scaling group uses target tracking on CPU. Write desired_capacity(cpu_readings, target, min_size, max_size).
cpu_readings: CPU % of each running instance (integers). Its length is the current size.- Desired = ceil(sum of readings ÷ target), which equals ceil(size × average ÷ target).
- Clamp the result to
[min_size, max_size]. - If there are no instances, return
min_size.
Example: desired_capacity([80, 80, 80, 80], 50, 2, 10) → 7 (320 ÷ 50 = 6.4, rounded up).
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Process Tasks Using Servers (Medium)
- Find Servers That Handled Most Number of Requests (Hard)
- AWS docs: Target tracking scaling policies
- AWS docs: Lambda concurrency
More in Cloud Building Blocks
Previous: AWS Fundamentals: Regions, AZs & IAM · Next: Storage: S3, EBS & EFS