EC2 vs ECS vs EKS vs Lambda: What They Are and Which to Use When
A detailed, practical guide to AWS compute: what EC2, ECS, EKS and Lambda are, how they differ in control, scaling, cost and operations, and a decision framework for choosing the right one.
The big picture
Every application needs somewhere to run. AWS offers several "compute" services, and they mostly differ in one thing: how much of the stack you manage yourself. Think of it like food. EC2 is buying groceries and cooking. ECS and EKS are meal kits: ingredients come prepped, you assemble. Lambda is ordering a dish: you say what you want, someone else handles the kitchen.
If you are new to AWS, start with What Is AWS? for regions, availability zones and the shared responsibility model.
EC2: virtual servers
Amazon EC2 (Elastic Compute Cloud) gives you virtual machines called instances. You pick the CPU, memory, storage and operating system (an AMI), and you get a machine you can SSH into. What you run on it is entirely up to you.
Key concepts
- Instance types: families tuned for workloads — general purpose (t, m), compute (c), memory (r, x), GPU/accelerated (p, g, inf).
- AMI: the disk image the instance boots from.
- EBS: network-attached block storage that outlives the instance.
- Security groups: virtual firewalls on each instance.
- Auto Scaling groups: add or remove instances based on load or schedules.
- Pricing options: On-Demand, Savings Plans / Reserved (commit for discount), Spot (spare capacity, up to ~90% off, can be reclaimed).
Strengths and weaknesses
- Pros: full control, any software, any OS, GPUs, long-running processes, predictable performance.
- Cons: you patch the OS, configure scaling, handle failures and pay while it's idle.
aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t3.small \ --key-name my-key \ --security-group-ids sg-0123456789abcdef0
ECS: AWS-native containers
Amazon ECS (Elastic Container Service) is AWS's own container orchestrator. You package your app as a Docker image, describe how to run it in a task definition, and ECS keeps the right number of copies running, restarts failed ones, and plugs them into load balancers.
Key concepts
- Cluster: a logical group where tasks run.
- Task definition: a blueprint — image, CPU, memory, ports, env vars, IAM role.
- Task: a running instance of that blueprint.
- Service: keeps N tasks running, does rolling deploys, registers with an ALB.
- Launch type: run tasks on EC2 instances you manage, or on Fargate (serverless).
{
"family": "orders-api",
"requiresCompatibilities": ["FARGATE"],
"cpu": "512",
"memory": "1024",
"networkMode": "awsvpc",
"containerDefinitions": [{
"name": "api",
"image": "123456789012.dkr.ecr.ap-south-1.amazonaws.com/orders:1.4.0",
"portMappings": [{ "containerPort": 8080 }]
}]
}- Pros: simple, deeply integrated with IAM, ALB, CloudWatch; no control-plane fee.
- Cons: AWS-only; smaller ecosystem than Kubernetes.
EKS: managed Kubernetes
Amazon EKS (Elastic Kubernetes Service) runs the Kubernetes control plane for you — the API server and etcd, across multiple availability zones. You deploy standard Kubernetes objects (Deployments, Services, Ingress) and the same manifests and Helm charts work on any Kubernetes cluster.
Key concepts
- Control plane: managed by AWS, billed hourly per cluster.
- Nodes: managed node groups (EC2), self-managed nodes, Karpenter, or Fargate profiles.
- Pods / Deployments / Services: the standard Kubernetes building blocks.
- Ecosystem: Helm, Argo CD, Istio, Prometheus, operators.
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders-api }
spec:
replicas: 3
selector: { matchLabels: { app: orders } }
template:
metadata: { labels: { app: orders } }
spec:
containers:
- name: api
image: orders:1.4.0
ports: [{ containerPort: 8080 }]- Pros: portable, huge ecosystem, fine-grained control, great for many teams and services.
- Cons: steep learning curve, cluster upgrades, add-on management, control-plane cost.
Lambda: functions on demand
AWS Lambda runs your code in response to events — an HTTP request via API Gateway, a file landing in S3, a message in SQS, a schedule. There are no servers to see. Lambda scales from zero to thousands of concurrent executions automatically, and you pay per request and per millisecond of run time.
Key concepts and limits
- Max run time: 15 minutes per invocation.
- Memory: 128 MB to 10 GB; CPU scales with memory.
- Cold starts: first request on a new environment is slower; provisioned concurrency and SnapStart reduce it.
- Stateless: keep state in DynamoDB, S3, ElastiCache or a database.
- Packaging: zip upload or container image up to 10 GB.
def handler(event, context):
for record in event["Records"]:
key = record["s3"]["object"]["key"]
print(f"New upload: {key}")
return {"status": "ok"}- Pros: zero idle cost, automatic scaling, almost no operations.
- Cons: time limit, cold starts, harder local debugging, expensive at constant high load, connection limits on relational databases (use RDS Proxy).
Where Fargate fits
Fargate is not a fifth option to compare — it's a way to run ECS or EKS containers without managing EC2 nodes. You declare CPU and memory per task or pod, and AWS provides the compute. It sits between "containers on your own servers" and Lambda.
Side-by-side comparison
| EC2 | ECS | EKS | Lambda | |
|---|---|---|---|---|
| Unit you deploy | Virtual machine | Container task | Kubernetes pod | Function |
| Who runs servers | You | You or Fargate | You or Fargate | AWS |
| Scaling | Auto Scaling groups | Service auto scaling | HPA + Karpenter / Cluster Autoscaler | Automatic, per request |
| Max run time | Unlimited | Unlimited | Unlimited | 15 minutes |
| Scale to zero | No | Possible, not native | Possible with add-ons | Yes |
| Cold start | Minutes (boot) | Seconds | Seconds | Milliseconds to seconds |
| Portability | High (it's a VM) | AWS-only | Any Kubernetes | Low (event model is AWS-specific) |
| Learning curve | Medium | Low–medium | High | Low |
| Extra fee | None | None | Per-cluster hourly | None |
| Best for | Full control, GPUs, legacy apps | Containers on AWS, simply | Large platforms, Kubernetes teams | Events, APIs with spiky traffic |
How the bills differ
- EC2: you pay per second for instances while they run, busy or idle. Cheapest per unit of compute at steady load, especially with Savings Plans or Spot.
- ECS: no orchestrator fee; you pay for the EC2 instances or Fargate vCPU/memory per second.
- EKS: an hourly fee per cluster plus the nodes or Fargate usage.
- Lambda: per request plus GB-seconds; includes a monthly free tier. Wins for spiky or low traffic, loses for 24/7 heavy load.
Which to use when
Choose EC2 when
- You need OS-level access, custom kernels, special drivers or licensed software.
- You run GPUs for training/inference, databases you self-manage, or legacy apps that can't be containerized.
- Load is steady and you want the lowest cost with reserved pricing.
Choose ECS when
- You have containerized microservices and want them running on AWS with minimal fuss.
- Your team is small and doesn't want to learn and operate Kubernetes.
- You want long-running services, workers or batch jobs — start on Fargate.
Choose EKS when
- Your company already uses Kubernetes or needs portability across clouds or on-premises.
- You run many services across many teams and want a shared platform with GitOps, service mesh, operators.
- You need Kubernetes-native tools (Kubeflow, Spark operator, Argo).
Choose Lambda when
- Work is triggered by events: uploads, queue messages, webhooks, cron jobs.
- Traffic is unpredictable or low and you want to pay nothing while idle.
- Each task finishes within 15 minutes and holds no local state.
Real architectures
- Early-stage SaaS: API on ECS Fargate behind an ALB, RDS Postgres, Lambda for image resizing and scheduled emails.
- Image upload pipeline: S3 upload → Lambda creates thumbnails → SQS → Lambda writes metadata to DynamoDB.
- Large platform team: EKS with Karpenter, Argo CD for deploys, Spot nodes for batch, on-demand for APIs.
- ML workloads: GPU EC2 instances for training, containers on ECS/EKS for inference, Lambda for lightweight pre/post processing.
Most mature systems mix them. The question isn't "which one forever" but "which one for this workload."
Interview angle
In a system design interview, naming the compute layer and justifying it shows maturity. Good answers sound like:
- "The upload processor is event-driven and short, so Lambda triggered by S3 — no idle cost."
- "The core API has steady traffic and long-lived connections, so containers on ECS Fargate with auto scaling."
- "We'd consider EKS only once we have many teams and services that benefit from a shared platform."
Be ready for follow-ups on cold starts, database connection limits from Lambda, Spot interruptions and how each option scales. See also how code flows from local to production.
Official documentation
- Amazon EC2 documentation
- Amazon ECS documentation
- Amazon EKS documentation
- AWS Lambda documentation
- AWS Fargate for ECS
- AWS decision guide: choosing compute
- AWS Pricing Calculator
Keep reading
Suggested next articles based on this one.
Git vs Scion: Why Anthropic Replaced Git for Its Monorepo
Git was built for humans working offline. Anthropic's agents work online, all the time, at huge scale. That mismatch is why Scion exists.
ReadStop Adding AI to Everything: Choose the Simplest Reliable Solution
Log alerts, rate limits, slow queries, caches, service calls, and deployments: solve the deterministic problem first. Add AI where uncertainty actually exists.
Read5 DevOps Concepts Developers Usually Get Wrong
Five familiar DevOps terms hide important operational differences. Learn the mechanism, the common mistake, and what changes in production.
ReadDesign it, don't just read it.
Practise LLD and system design problems with structured rubrics and AI feedback.
Start practising free