EC2 — Virtual Machines

Elastic Compute Cloud in depth — instance families and naming, Graviton vs x86, AMIs, launch templates and user data, the instance lifecycle, storage options, security groups, key pairs vs SSM Session Manager, the metadata service, placement groups, and pricing with On-Demand, Savings Plans, Reserved and Spot.

Beginner 6 min readLesson 3 of 19 Interview Q&A

EC2 (Elastic Compute Cloud) rents virtual machines — instances — by the second. It's the original AWS service and still the foundation under much of AWS: containers, managed databases and even Lambda ultimately run on EC2-class hardware via the Nitro system, AWS's custom hypervisor and offload cards (Virtualization and containers).

Instance types

An instance type fixes the CPU, memory, network and storage profile. The name encodes it:

  m 7 g d . 2xlarge
  │ │ │ │    └── size: nano, micro, small, medium, large, xlarge, 2xlarge … 48xlarge, metal
  │ │ │ └─────── extra capability: d = local NVMe, n = enhanced networking, e = extra storage/memory
  │ │ └───────── processor: g = Graviton (ARM), a = AMD, i = Intel
  │ └─────────── generation (higher = newer, usually better price-performance)
  └───────────── family
FamilyOptimised forExamples
T (burstable)Low baseline CPU with burst creditsDev boxes, small sites — t4g.small
M (general purpose)Balanced CPU:memory (1:4 GiB)Most web and app servers
C (compute)More CPU per GiBBatch, encoding, high-traffic APIs
R / X (memory)Large memoryDatabases, in-memory caches, analytics
I / D (storage)Fast local NVMe or dense HDDNoSQL databases, data warehouses
P / G / Trn / Inf (accelerated)GPUs or AWS ML chipsModel training and inference (LLMs)

Each size step roughly doubles vCPUs, memory and price. Graviton (ARM) instances typically give noticeably better price-performance than comparable x86 ones for software that runs on ARM — most Linux, JVM, Node, Python and Go workloads do.

Burstable (T) instances earn CPU credits while idle and spend them when busy. In "standard" mode they throttle to the baseline when credits run out — a common mystery slowdown for production apps on t3.micro.

AMIs and launching

An Amazon Machine Image (AMI) is a template: root volume snapshot, OS, and any baked-in software. Use AWS-maintained images (Amazon Linux 2023, Ubuntu, Bottlerocket for containers, Windows) or build your own golden AMIs with EC2 Image Builder or Packer.

A launch template captures everything needed to start an instance — AMI, type, subnet, security groups, IAM instance profile, storage, user data — so Auto Scaling and scripts launch identical instances.

User data runs on first boot (via cloud-init):

Shell
#!/bin/bash
dnf install -y nginx
systemctl enable --now nginx
echo "hello from $(hostname)" > /usr/share/nginx/html/index.html

Two strategies: bake (everything in the AMI — fast, consistent boots) or fry (minimal AMI plus configuration at boot — flexible, slower). Most teams bake the heavy parts and fry the config.

Lifecycle

stopstarthibernateterminatependingrunningbilledstoppedEBS still billedhibernatedRAM saved to EBSterminatedgone
  • Reboot keeps the same host; stop/start usually moves the instance to new hardware (a useful fix for degraded hosts) and changes the public IP unless you use an Elastic IP.
  • Instance store (local NVMe) is wiped on stop or termination; EBS volumes persist (EBS and EFS). Root EBS volumes are deleted on termination by default.
  • Enable termination protection for anything precious — though for well-run fleets, every instance should be disposable.

Networking and access

  • Instances live in a subnet of a VPC and get a private IP; public subnets can also assign public IPs.
  • Security groups are stateful, allow-only firewalls attached to the network interface. Reference other security groups instead of IPs: "allow 8080 from the load balancer's SG".
  • Don't open SSH to the world. Use SSM Session Manager: shell access through the AWS API, authorised by IAM, logged, with no inbound ports or key pairs at all. EC2 Instance Connect is another option.
Shell
aws ssm start-session --target i-0abc123def4567890

The instance metadata service

From inside an instance, 169.254.169.254 serves metadata: instance ID, AZ, and — critically — the role's temporary credentials. Require IMDSv2, which needs a session token obtained by a PUT request; that blocks most SSRF attacks where an attacker tricks your app into fetching the credentials URL (the cause of the well-known Capital One breach — Web security).

Shell
TOKEN=$(curl -sX PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/availability-zone

Placement groups

StrategyLayoutUse
ClusterPacked close together in one AZLowest latency, highest throughput — HPC, distributed training
SpreadEach on distinct hardware racks (max 7 per AZ per group)A few critical instances that must not fail together
PartitionGroups of instances on separate racksLarge distributed systems aware of racks — Kafka, HDFS, Cassandra

Pricing models

ModelCommitmentDiscount vs On-DemandUse for
On-DemandNone, per second—Spiky, short-lived, unknown workloads
Savings PlansSpend per hour for 1 or 3 yearsUp to ~70%The steady baseline; Compute Savings Plans also cover Fargate and Lambda
Reserved InstancesSpecific type/region for 1 or 3 yearsSimilarOlder model; still used for RDS, ElastiCache, etc.
SpotNone — AWS can reclaim with 2 minutes' noticeUp to ~90%Fault-tolerant work: batch, CI runners, stateless workers, training with checkpoints
Dedicated HostsPhysical server for you—Licensing (per-socket) and compliance

A common shape: Savings Plans for the always-on baseline, On-Demand for daily peaks, Spot for anything interruptible. With Spot, diversify across many instance types and AZs and handle the interruption notice gracefully (Cost optimisation).

When EC2 — and when not

EC2 gives full control: any OS, kernel tuning, GPUs, long-running processes, legacy software. The price is operational work — patching, scaling, recovery. Before reaching for raw EC2, ask whether containers on Fargate, Lambda or a managed service would remove that work.

Interview questions
QWhat happens to data when you stop or terminate an EC2 instance?easy

EBS volumes persist when an instance is stopped and you keep paying for their storage; on termination, volumes marked delete-on-termination (the root volume by default) are deleted and others are detached and kept. Instance store volumes are physically attached to the host and are lost on stop, hibernate or termination. A stopped instance usually restarts on different hardware with a new public IP unless an Elastic IP is attached.

QWhen would you use Spot instances, and how do you handle interruptions?medium

For workloads that can tolerate losing an instance: batch jobs, CI runners, stateless web workers behind a load balancer, big data and ML training with checkpoints. Handle interruptions by diversifying across many instance types and AZs (allocation strategy price-capacity-optimized), watching for the two-minute interruption notice via metadata or EventBridge to drain work and checkpoint, keeping state outside the instance, and mixing Spot with On-Demand capacity in Auto Scaling groups.

QWhy should you enforce IMDSv2?medium

The instance metadata service exposes the instance role's temporary credentials. With IMDSv1, any server-side request forgery bug that lets an attacker make the app fetch an arbitrary URL can leak those credentials. IMDSv2 requires a session token obtained via an HTTP PUT with a custom header and has a hop limit, which typical SSRF vectors can't satisfy.

Key takeaways
  • Instance type names encode family, generation, processor and size; pick the family by CPU:memory ratio and consider Graviton for better price-performance.
  • AMIs and launch templates make instances reproducible; user data configures them on first boot.
  • EBS persists across stop/start; instance store does not. Treat instances as disposable.
  • Use security groups referencing other groups, Session Manager instead of open SSH, and enforce IMDSv2.
  • Placement groups trade fault isolation against network performance.
  • Mix Savings Plans (baseline), On-Demand (peaks) and Spot (interruptible work) to control cost.