Compute: EC2, Instance Families & Lambda
The two ways to run your code on AWS, rent a computer, or rent a single function-run, explained simply, then all the way down.
From your mentor
Every workload you ever deploy runs on one of these. We start with one plain-English question, do you want a computer, or just a function to run?, and end with you decoding any instance name on sight and knowing exactly what it costs.
AWS compute is just two choices: rent a whole computer, or rent a single function-run.
In 10 minutes you’ll know which to reach for. You do NOT need to memorize every instance type.
Pick your way in, same idea, 5 doors
Two ways to run code on AWS. Either rent a computer that’s always on (EC2), or hand AWS one function and pay only while it runs (Lambda). That’s the whole menu, everything else is just sizing.
Two ways to run code
Almost all of AWS compute comes down to a single choice: do you want a whole computer you control, or do you just want a piece of code to run when something happens?
Say you wrote a small web API. There are two fundamentally different ways to run it on AWS, and understanding the difference is most of this lesson.
Amazon EC2
Rent a whole computer
- What you rent
- A whole virtual computer (a server)
- It runs
- 24/7, until you stop it
- You manage
- OS, patching, scaling, the lot
- You pay
- Per second it’s on (busy or idle)
- Best when
- Steady, always-on, full control
AWS Lambda
Run a function on demand
- What you rent
- A single run of your function
- It runs
- Only when triggered, then vanishes
- You manage
- Just your code, AWS runs it
- You pay
- Per request + compute time used
- Best when
- Spiky, event-driven, infrequent
In plain English
There’s a third option, containers (ECS/EKS/Fargate), which sit between these two, but that’s its own lesson. Master these two first; containers make sense only once you have.
What an EC2 instance is actually made of
An 'instance' isn't one thing, it's a few parts clicked together. Knowing them turns the launch wizard from scary to obvious.
| Part | What it is | Apartment analogy |
|---|---|---|
| AMI | The image/template the instance boots from (OS + preinstalled software) | The show-home you copy the layout from |
| Instance type | The virtual hardware, vCPUs + memory (e.g. t3.micro) | How big the apartment is |
| EBS volume | The network-attached disk; persists, billed separately | Your furniture, stays even if you move out |
| Key pair / SSM | How you get in, SSH key, or (better) Session Manager | The front-door key |
| Security group | A stateful firewall on the instance’s network ports | The locked building entrance |
| User data | A script that runs once on first boot | The move-in checklist |
| Instance profile | An IAM role the instance assumes, no keys on the box | A staff badge that opens the right doors |
The disk outlives the instance
Terminate an instance and its EBS volume can linger and keep billing unless “delete on termination” is set. This is a classic source of a creeping bill, see Lesson 2’s cost traps.Get in without SSH keys
Modern best practice: don’t open port 22 or manage SSH keys at all. Attach an instance profile and use Session Manager to open a shell through the AWS API, no inbound ports, fully logged. (That’s the Rung-3 way; we’ll do it in your task list.)Decode any instance name in 5 seconds
Instance names look like a cat walked across the keyboard, c7gn.xlarge, but every character means something. Learn the pattern once and you’ll never be lost in the picker again.
Tap each part of the name
Family, what it’s optimised for
“c” means compute-optimised. The opening letters are the machine’s specialty: T burstable, M general, C compute, R/X memory, I/D storage, P/G accelerated. (See the gallery below.)
Nice, that’s the win
c7gn.xlarge reads as: a compute-tuned, 7th-gen, Graviton + network-optimised machine in the xlarge size. Once you see the pattern, any name decodes on sight.Those opening letters are the machine’s specialty. Here’s the whole lineup at a glance:
Burstable
Cheap baseline that banks CPU credits and bursts when busy.
t4g.microGeneral purpose
Balanced CPU + memory. The safe default for most web/app servers.
m7g.largeCompute optimised
CPU-heavy work: batch jobs, encoding, gaming, scientific compute.
c7g.xlargeMemory optimised
Lots of RAM per core: databases, caches, in-memory analytics.
r7g.largeStorage optimised
Fast or dense local disk: NoSQL, search, big local datasets.
i4i.largeAccelerated
GPUs and ML chips: model training, inference, graphics.
g5.xlargeThe burstable (T) trick, and trap
A T-class instance is like a phone battery for CPU: when it’s idle it banks “CPU credits,” then spends them to burst when busy. Great and cheap for spiky low traffic, but if it runs hot for too long it runs out of credits and throttles (or costs extra in unlimited mode). For steady load, use M/C instead.Default to Graviton
When a workload runs on ARM (most modern languages do), theg families give you the best price/performance, typically ~20% cheaper for equal work. Start there unless something forces x86.What an instance actually costs
The #1 beginner surprise: an instance bills for every second it’s on, doing nothing or not. Here’s the real cost model.
Careful here
| Cost piece | How it bills | Example (us-east-1, rough) |
|---|---|---|
| The instance | Per second it’s running (≥60s), by type & region | t3.micro ≈ $0.0104/hr ≈ $7.6/mo if left on 24/7 |
| EBS volume | Per provisioned GB-month, even when stopped | gp3 ≈ $0.08/GB-mo |
| Public IPv4 | $0.005/hr each (≈ $3.60/mo), even idle | See Lesson 2 |
| Data transfer out | ~$0.09/GB to the internet | See Lesson 2 |
And you can buy the same instance four ways, trading commitment for a discount (full detail in Lesson 2):
Same instance, four prices, bar = relative cost
Stopped ≠ free
A stopped instance doesn’t bill for compute, but its EBS volume and any allocated Elastic IP still do. To pay nothing, you must terminate (and delete the volume).Lambda, in depth
You hand AWS a function and the events that should trigger it. AWS runs it on demand, scales it from zero to thousands automatically, and bills you only for what runs.
Your code is just a handler, a function that receives an event and returns a result:
def handler(event, context):
name = event.get("name", "world")
return {"statusCode": 200, "body": f"Hello, {name}!"}Nice, that’s the win
The guardrails that shape what Lambda can do (know these cold, they decide if Lambda even fits):
128 MB → 10 GB
CPU scales with it (1 vCPU @ 1,769 MB)
15 min max
Long jobs → containers / Step Functions
6 MB sync · 1 MB async
Big inputs go via S3, not the request
512 MB → 10 GB
Ephemeral; not durable between runs
250 MB zip · 10 GB image
Big dependencies → container image
1,000 / region
Soft limit, raise via Service Quotas
Cold starts, the shop with the lights off
When a function hasn’t run recently, AWS must spin up a fresh execution environment before your code runs, a cold start (often 100 ms–1 s+). It’s like the first customer waiting for the shop lights to flicker on. As of Aug 2025 the init phase is billed too.Fixes: smaller packages, ARM, SnapStart (Java), or provisioned concurrency for latency-critical paths.Pricing is two simple parts, requests, and compute measured in GB-seconds:
Part 1 · Requests
$0.20 / 1M
Same on x86 and ARM. One invocation = one request.
Part 2 · Compute (GB-seconds)
Always free: 1M requests + 400,000 GB-seconds every month (x86 + ARM combined).
Worked example, a million runs, basically free
A 128 MB function that runs 100 ms, called 1,000,000 times a month: that’s 0.125 GB × 0.1 s × 1,000,000 = 12,500 GB-seconds and 1M requests. Both sit inside the free tier (400,000 GB-s + 1M requests), so it costs $0.00. That’s why Lambda is the beginner’s best friend for small, spiky workloads.EC2 vs Lambda, when to use which
Match the tool to the traffic shape. Get this right and both your bill and your operational pain drop.
Runs more often →
And the same climb you’ve seen all course, how your compute choices should mature:
- Rung 0 · Naive
One big always-on instance
Launch a large EC2, run everything on it, leave it on 24/7, SSH in to deploy.
You pay full price around the clock, it’s a single point of failure, and it can’t handle a traffic spike. - Better
Right-sized + Auto Scaling
Pick the smallest instance family that fits, put it behind Auto Scaling so capacity follows demand.
You stop paying for headroom you don’t use, and the system grows and shrinks with traffic. - Best practice today
Serverless where it fits
Move event-driven and spiky pieces to Lambda; keep steady cores on right-sized compute. Use Graviton + Spot to cut cost.
You pay near-zero for idle, scale to zero automatically, and operate far less infrastructure.
How this shows up in interviews
“When would you choose Lambda over EC2, and when would that be a mistake?”
How to answer it
Answer by traffic shape and the hard limits, then name the cost trade-off. Specifics (cold starts, 15-min limit, GB-seconds) show real experience.
- 1Lambda wins for spiky, event-driven, or infrequent work, it scales from zero and you pay nothing when idle.
- 2It’s the wrong choice for steady, high-throughput, 24/7 traffic: an always-on server (right-sized EC2 or containers) is cheaper than always-on Lambda concurrency.
- 3Lambda’s hard limits can disqualify it: 15-minute timeout, up to 10 GB memory, 6 MB sync payload, no GPU, long or heavy jobs go to EC2.
- 4Cold starts add first-call latency (and are now billed), mitigate with smaller packages, ARM, SnapStart, or provisioned concurrency.
- 5Right-size and prefer Graviton/Spot on EC2 to control cost either way.
Green flags
- Reasons by traffic pattern + the hard limits
- Knows always-on Lambda can cost more than a server
- Mentions cold starts, Graviton, right-sizing unprompted
Red flags
- “Lambda is always cheaper”
- Doesn’t know the 15-min / memory limits
- Defaults to one giant always-on instance
Q.Decode m7g.large.
A.Read it left to right: family, generation, capabilities, size.
- m = general-purpose (balanced CPU:memory).
- 7 = 7th generation (newer = better price/perf).
- g = Graviton / ARM (cheaper than x86).
- large = the size step (2 vCPU / 8 GiB here).
They’re checking: That you can decode any instance name on sight.
Q.What’s a cold start and how do you reduce it?
A.The one-off latency to spin up a fresh execution environment before your code runs on an idle function.
- Smaller deployment packages, and ARM/Graviton.
- SnapStart (Java), or provisioned concurrency for latency-critical paths.
They’re checking: That you use provisioned concurrency only where latency truly matters.
Q.How is Lambda CPU controlled, you only set memory?
A.Yes, CPU scales linearly with memory. There is no separate CPU dial.
- 1 vCPU ≈ 1,769 MB, up to ~6 vCPUs at 10,240 MB.
- Raising memory can make a CPU-bound function faster AND cheaper, it finishes sooner.
They’re checking: That you know memory is the CPU dial, and tuning it can cut cost.
Q.A T-class instance got slow under load, why?
A.It ran out of CPU credits and throttled to its baseline.
- Burstable T credits bank while idle and drain under sustained load.
- Unlimited mode bills extra instead of throttling; for steady load use M (balanced) or C (compute).
They’re checking: That you match burstable vs steady instance types to the workload.
Q.When would you use Spot instances?
A.For fault-tolerant, interruptible work, up to ~90% off, accepting a 2-minute reclaim notice.
- Good: batch, CI, stateless workers, anything that can checkpoint and resume.
- Bad: a long single stateful job with no checkpointing.
They’re checking: That you weigh interruption risk against the savings.
Your turn, run code both ways
Launch a tiny EC2 the safe way, then deploy a Lambda, and watch the Lambda cost essentially nothing. ~25 minutes, inside the Free plan.
Now do it in your own account
As your IAM admin user, run code both ways: a tiny EC2 the safe way, then a Lambda that costs almost nothing. Stay in one region and use the smallest sizes.
Before you start
3 to have readyYour IAM admin user from Lesson 1.
AWS CLI v2 signed in.
aws sts get-caller-identityAn IAM role with AmazonSSMManagedInstanceCore so Session Manager works without SSH (and a Lambda execution role).
- 1
Launch a small free-tier instance with an SSM instance profile, and no SSH key / no inbound port 22.
Free tierYour terminal
aws cli
AWS docs: ec2 run-instances$ aws ec2 run-instances --image-id <al2023-ami> --instance-type t3.micro --iam-instance-profile Name=SSMRoleYou should see: an InstanceId; it reaches running with no open SSH port.
Free-tier eligible (750 hrs/mo, first year). Terminate it in the teardown.
- 2
Open a shell with Session Manager, no SSH, no open ports.
Free tierYour terminal
You should see: a shell on the instance, with no key and no port 22 exposed.
- 3
Create a tiny arm64 Lambda from your handler (arm64 is the cheaper rate).
Free tierYour terminal
aws cli
AWS docs: lambda create-function$ aws lambda create-function --function-name hello --runtime python3.13 --architectures arm64 --handler handler.handler --role <role-arn> --zip-file fileb://fn.zipYou should see: the function appears in the Lambda console.
- 4
Invoke it and read the response, your first serverless run.
Free tierYour terminal
aws cli
AWS docs: lambda invoke$ aws lambda invoke --function-name hello --payload '{"name":"AWS"}' out.jsonYou should see: out.json holds the function’s response.
Last step: tear it down
Once you’ve seen it work, remove everything so nothing keeps billing.
Terminate the EC2 instance, this is the one that bills by the hour.
aws ec2 terminate-instances --instance-ids <id>Confirm its EBS volume was deleted, a detached volume bills even after the instance is gone.
Delete the Lambda to keep the account tidy (it costs ~nothing idle).
Re-check Billing after a day, a forgotten instance is the classic first bill.
Next up
Next, Storage: S3, EBS & EFS
The three core storage types, when each fits, and the S3 security ladder (public bucket → Block Public Access → private + encrypted).