AWS Basics · Lesson 428 min read

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.

Next: pick the right instance family for a workload in one glance.
01

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
vs

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

EC2 is renting an apartment, it’s yours, you furnish it, and you pay rent every month whether you sleep there or not. Lambda is a vending machine, you only pay the moment someone buys something, and you never think about the building, the power, or the cleaning. Same snack, very different bill.

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.

02

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.

PartWhat it isApartment analogy
AMIThe image/template the instance boots from (OS + preinstalled software)The show-home you copy the layout from
Instance typeThe virtual hardware, vCPUs + memory (e.g. t3.micro)How big the apartment is
EBS volumeThe network-attached disk; persists, billed separatelyYour furniture, stays even if you move out
Key pair / SSMHow you get in, SSH key, or (better) Session ManagerThe front-door key
Security groupA stateful firewall on the instance’s network portsThe locked building entrance
User dataA script that runs once on first bootThe move-in checklist
Instance profileAn IAM role the instance assumes, no keys on the boxA 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.)
03

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

It’s a license plate. 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:

T

Burstable

Cheap baseline that banks CPU credits and bursts when busy.

t4g.micro
M

General purpose

Balanced CPU + memory. The safe default for most web/app servers.

m7g.large
C

Compute optimised

CPU-heavy work: batch jobs, encoding, gaming, scientific compute.

c7g.xlarge
R · X · U

Memory optimised

Lots of RAM per core: databases, caches, in-memory analytics.

r7g.large
I · D

Storage optimised

Fast or dense local disk: NoSQL, search, big local datasets.

i4i.large
P · G · Inf · Trn

Accelerated

GPUs and ML chips: model training, inference, graphics.

g5.xlarge

The 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), the g families give you the best price/performance, typically ~20% cheaper for equal work. Start there unless something forces x86.
04

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

EC2 is a taxi with the meter running. It charges by time the moment it starts, whether you’re moving or parked. Forgetting to “stop the taxi” (terminate the instance) is how a test box quietly bills for a month.
Cost pieceHow it billsExample (us-east-1, rough)
The instancePer second it’s running (≥60s), by type & regiont3.micro ≈ $0.0104/hr ≈ $7.6/mo if left on 24/7
EBS volumePer provisioned GB-month, even when stoppedgp3 ≈ $0.08/GB-mo
Public IPv4$0.005/hr each (≈ $3.60/mo), even idleSee Lesson 2
Data transfer out~$0.09/GB to the internetSee 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

On-Demandbaseline
No commitmentLearning, spiky, unknown
Reservedup to ~72% off
1–3 yr, specificSteady, fixed shape
Savings Plansup to ~72% off
1–3 yr spendSteady baseline
Spotup to ~90% off
None, reclaimableFault-tolerant batch / CI

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).
05

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:

handler.py
def handler(event, context):
    name = event.get("name", "world")
    return {"statusCode": 200, "body": f"Hello, {name}!"}

Nice, that’s the win

Lambda is pay-as-you-go electricity. There’s no “server” humming in the background costing money, the meter only moves while your function is actually executing, billed to the millisecond. Idle costs exactly nothing.

The guardrails that shape what Lambda can do (know these cold, they decide if Lambda even fits):

Memory

128 MB → 10 GB

CPU scales with it (1 vCPU @ 1,769 MB)

Timeout

15 min max

Long jobs → containers / Step Functions

Payload

6 MB sync · 1 MB async

Big inputs go via S3, not the request

/tmp scratch

512 MB → 10 GB

Ephemeral; not durable between runs

Package

250 MB zip · 10 GB image

Big dependencies → container image

Concurrency

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)

1 GB×1 sec=1 GB-s
x86 · $0.0000166667ARM · $0.0000133334 (~20% less)

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.
06

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.

Longer / heavier each run →
EC2, runs > 15 min, big RAM, or GPU
Lambda, spiky, event-driven, short
EC2 / containers, steady 24/7
+ Spot for cheap batch

Runs more often →

And the same climb you’ve seen all course, how your compute choices should mature:

Compute maturitythe climb
  1. 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.
  2. 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.
  3. 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.
07

How this shows up in interviews

Interview angle

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.

  1. 1Lambda wins for spiky, event-driven, or infrequent work, it scales from zero and you pay nothing when idle.
  2. 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.
  3. 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.
  4. 4Cold starts add first-call latency (and are now billed), mitigate with smaller packages, ARM, SnapStart, or provisioned concurrency.
  5. 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.

08

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

~25 min Free-tier eligible if you terminate the EC2 when done

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 ready

Your IAM admin user from Lesson 1.

AWS CLI v2 signed in.

aws sts get-caller-identity

An IAM role with AmazonSSMManagedInstanceCore so Session Manager works without SSH (and a Lambda execution role).

  1. 1

    Launch a small free-tier instance with an SSM instance profile, and no SSH key / no inbound port 22.

    Free tier

    Your terminal

    aws cli
    $ aws ec2 run-instances --image-id <al2023-ami> --instance-type t3.micro --iam-instance-profile Name=SSMRole
    AWS docs: ec2 run-instances

    You 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. 2

    Open a shell with Session Manager, no SSH, no open ports.

    Free tier

    Your terminal

    aws cli
    $ aws ssm start-session --target <instance-id>
    AWS docs: ssm start-session

    You should see: a shell on the instance, with no key and no port 22 exposed.

  3. 3

    Create a tiny arm64 Lambda from your handler (arm64 is the cheaper rate).

    Free tier

    Your terminal

    aws cli
    $ aws lambda create-function --function-name hello --runtime python3.13 --architectures arm64 --handler handler.handler --role <role-arn> --zip-file fileb://fn.zip
    AWS docs: lambda create-function

    You should see: the function appears in the Lambda console.

  4. 4

    Invoke it and read the response, your first serverless run.

    Free tier

    Your terminal

    aws cli
    $ aws lambda invoke --function-name hello --payload '{"name":"AWS"}' out.json
    AWS docs: lambda invoke

    You 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).