Back to EC2 & Compute
Q4Question 4 of 7

EC2, Instance Families and Launch Parameters

Key Concepts
  • EC2 (Elastic Compute Cloud) provides resizable virtual servers on demand, billed per second while running.
  • Instance families group types by optimized resource: general purpose (M/T), compute optimized (C), memory optimized (R/X), and storage optimized (I/D).
  • The AMI is the starting disk image containing the operating system and pre-installed software like Java.
  • The instance type combines the family and size, such as m6i.large, determining CPU, memory, and network capacity.
  • A key pair provides SSH access, a security group acts as a stateful firewall, and a subnet determines network placement and AZ.
  • An IAM role attached through an instance profile gives the instance temporary AWS credentials without embedded keys.
  • Graviton (ARM-based g-suffix) instances often give the best price-performance for JVM workloads.

Definition

EC2 is a rented virtual server, the family picks what it is good at, and launching it means choosing its image, size, key, firewall, network, permissions, and disks.
  • EC2 (Elastic Compute Cloud) – AWS service that provides resizable virtual servers on demand, billed per second while running.
  • Instance Family – A grouping by optimized resource: general purpose (M/T for balanced), compute optimized (C for CPU), memory optimized (R/X for RAM), storage optimized (I/D for disk throughput).
  • AMI (Amazon Machine Image) – The starting disk image containing the OS and pre-installed software, used as a template for launching instances.
  • Instance Type – The family plus size, such as m6i.large, determining the exact CPU, memory, network, and storage capacity.
  • Instance Profile – A wrapper that attaches an IAM Role to an EC2 instance, providing temporary credentials without embedded access keys.

EC2 is renting an office room from National Bank of India's building instead of constructing your own. The instance family is the type of room: a general-purpose desk, a powerful number-crunching room for the compute team, a huge room full of filing cabinets for memory-heavy work, or a room with fast delivery chutes for storage-heavy work. When you rent the room you pick its layout (AMI), its size (instance type), the key to its door (key pair), the security guard rules (security group), which floor it sits on (subnet), its clearance badge (IAM role), and its cabinets (storage).

Understanding the Concepts

What is EC2?

EC2 (Elastic Compute Cloud) gives you a virtual machine in minutes. You never see the physical hardware; AWS runs a hypervisor and carves out your instance. You pay per second or hour while it runs, and you can stop or terminate it when done. For National Bank of India, EC2 replaces the weeks-long process of buying, racking, and configuring physical servers.

JAVA
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.*;

public class LaunchBankServer {
    public static void main(String[] args) {
        Ec2Client ec2 = Ec2Client.create();
        RunInstancesRequest req = RunInstancesRequest.builder()
                .imageId("ami-0abcd1234")              // AMI: Amazon Linux + Java 17
                .instanceType(InstanceType.M6I_LARGE)  // general purpose, balanced
                .keyName("nbi-settlement-key")         // SSH key pair
                .securityGroupIds("sg-0settlement")    // firewall
                .subnetId("subnet-0private-a")         // private subnet, AZ a
                .iamInstanceProfile(IamInstanceProfileSpecification.builder()
                        .name("SettlementReaderProfile").build())  // IAM role
                .minCount(1).maxCount(1)
                .build();
        var response = ec2.runInstances(req);
        System.out.println("Instance ID: " + response.instances().get(0).instanceId());
    }
}

What are instance families and types?

Instance families match the workload's dominant resource need. Each family letter indicates the optimization:

  • M (General Purpose) – Balanced CPU and memory. Suits typical banking web and API services.
  • T (Burstable) – Cheap for workloads that are idle most of the time and spike occasionally, like an internal admin tool.
  • C (Compute Optimized) – High CPU. Suits CPU-heavy work such as risk calculations or fraud-model scoring.
  • R / X (Memory Optimized) – Large RAM. Suits in-memory caches and large JVM heaps, like a market-data service holding millions of quotes.
  • I / D (Storage Optimized) – High local disk throughput. Suits databases needing very fast local disks.
DIAGRAM
Instance Type Naming Convention:
  m6i.large
  │││  │
  ││└──── Generation (6 = latest)
  │└───── Additional capability (i = Intel, g = Graviton ARM)
  └────── Family (m = general purpose)
         Size: large = 2 vCPU, 8 GB RAM

What is an AMI?

An AMI (Amazon Machine Image) is the starting disk image. It contains the operating system, pre-installed software, and any custom configuration. You can use AWS-provided AMIs (Amazon Linux, Ubuntu), marketplace AMIs, or create your own golden AMI with Java 17, monitoring agents, and security hardening pre-baked.

BASH
# List available Amazon Linux AMIs with Java
aws ec2 describe-images \
  --owners amazon \
  --filters "Name=name,Values=al2023-ami-*" \
  --query 'Images[*].[ImageId,Name]' \
  --output table

What is a key pair and how does it work?

A key pair is an asymmetric cryptographic pair. AWS stores the public key on the instance and gives you the private key as a .pem file. For Linux, you use the private key to SSH in. The key file must have restricted permissions or SSH refuses it.

BASH
# Create a key pair for the settlement team
aws ec2 create-key-pair \
  --key-name nbi-settlement-key \
  --query 'KeyMaterial' \
  --output text > nbi-settlement-key.pem
chmod 400 nbi-settlement-key.pem

# Connect using the key
ssh -i nbi-settlement-key.pem ec2-user@10.0.1.50

What is a security group?

A security group is a stateful firewall that controls inbound and outbound traffic at the instance level. Stateful means if you allow an inbound request, the response is automatically allowed out. You specify allow rules only; anything not explicitly allowed is denied.

JAVA
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.*;

public class CreateSecurityGroup {
    public static void main(String[] args) {
        Ec2Client ec2 = Ec2Client.create();
        var sg = ec2.createSecurityGroup(CreateSecurityGroupRequest.builder()
                .groupName("settlement-service-sg")
                .description("Allow ALB traffic on 8080, SSH from corporate")
                .vpcId("vpc-0abc").build());

        ec2.authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressRequest.builder()
                .groupId(sg.groupId())
                .ipPermissions(
                        IpPermission.builder().ipProtocol("tcp").fromPort(8080).toPort(8080)
                                .userIdGroupPairs(UserIdGroupPair.builder()
                                        .groupId("sg-alb").build()).build(),
                        IpPermission.builder().ipProtocol("tcp").fromPort(22).toPort(22)
                                .ipRanges(IpRange.builder()
                                        .cidrIp("10.0.0.0/16").build()).build()
                ).build());
    }
}

What is a subnet and IAM role in the launch context?

The subnet determines which VPC and Availability Zone the instance lives in, and whether it is public or private. A private subnet has no internet gateway route, keeping the instance invisible to the public internet.

The IAM role, attached through an instance profile, gives the instance temporary credentials to call AWS services. The SDK auto-fetches these credentials, so there are no embedded keys.

DIAGRAM
Launch Parameters Checklist:
┌──────────────────┬──────────────────────────────────────────┐
│ Parameter         │ Purpose                                 │
├──────────────────┼──────────────────────────────────────────┤
│ AMI               │ OS + pre-installed software              │
│ Instance Type     │ Family + size (CPU, RAM, network)        │
│ Key Pair          │ SSH authentication                       │
│ Security Group    │ Stateful firewall (allow rules only)     │
│ Subnet            │ VPC, AZ, public/private placement        │
│ IAM Role          │ Temporary AWS credentials, no keys       │
│ Storage (EBS)     │ Root volume + data volumes               │
└──────────────────┴──────────────────────────────────────────┘

What about storage (EBS volumes)?

EBS (Elastic Block Store) volumes are the disks attached to EC2 instances. The root volume holds the OS, and you can add data volumes for application data. Volume types include gp3 (general purpose SSD, default), io2 (provisioned IOPS for high-performance databases), and st1 (throughput-optimized HDD for sequential workloads).

BASH
# Create an additional EBS volume for settlement data
aws ec2 create-volume \
  --volume-type gp3 \
  --size 100 \
  --availability-zone ap-south-1a \
  --encrypted \
  --tag-specifications 'ResourceType=volume,Tags=[{Key=Name,Value=settlement-data}]'

What should a senior engineer know?

Choosing the right size is a cost and performance decision. Over-provisioning wastes money, under-provisioning causes throttling. Use CloudWatch metrics and AWS Compute Optimizer to right-size. Prefer the latest generation (the 6i/7g suffixes) because newer hardware is cheaper per unit of performance. Graviton (ARM, the g suffix) is often cheapest for JVM workloads.

Also consider Spot instances for fault-tolerant batch workloads like report generation – they cost up to 90% less than On-Demand but can be interrupted. Reserved Instances or Savings Plans cut costs for steady-state workloads like the always-running transfer service.

JAVA
public class InstanceSizingStrategy {
    // Step 1: Start with CloudWatch CPU and memory metrics
    // Step 2: Run Compute Optimizer for right-sizing recommendations
    // Step 3: Pick latest generation (m7g over m5)
    // Step 4: Consider Graviton for JVM workloads (20% cheaper)
    // Step 5: Use Spot for batch, Reserved for steady-state
}

What are common interview follow-up questions?

  • What is the difference between stopping and terminating an instance? Stopping preserves the EBS root volume; terminating deletes it by default.
  • What is an Elastic IP? A static public IP you can reassign between instances, useful for DNS stability.
  • What is user data? A script that runs at first boot to configure the instance, such as installing Java or starting the application.
  • What is placement group? A strategy for placing instances close together (cluster) for low latency, or spread across hardware for fault tolerance.
BASH
# User data script to install Java and start the settlement service
#!/bin/bash
yum install -y java-17-amazon-corretto
aws s3 cp s3://nbi-artifacts/settlement-service.jar /opt/app/
java -jar /opt/app/settlement-service.jar &

Visual Overview

DIAGRAM
┌─────────── EC2 Launch Flow ───────────┐
│                                        │
│  1. Choose AMI                         │
│     └── Amazon Linux + Java 17         │
│                                        │
│  2. Choose Instance Type               │
│     ├── m6i.large (general purpose)    │
│     ├── c6i.xlarge (compute heavy)     │
│     └── r6i.large (memory heavy)       │
│                                        │
│  3. Configure Network                  │
│     ├── VPC: nbi-production            │
│     ├── Subnet: private-az-a           │
│     └── Security Group: sg-settlement  │
│         ├── Inbound: 8080 from ALB     │
│         └── Inbound: 22 from corporate │
│                                        │
│  4. Attach IAM Role                    │
│     └── Instance Profile               │
│         └── SettlementReaderRole       │
│             └── Temp creds from STS    │
│                                        │
│  5. Add Storage                        │
│     ├── Root: 20 GB gp3 (OS)           │
│     └── Data: 100 GB gp3 (app data)   │
│                                        │
│  6. Add Key Pair                       │
│     └── nbi-settlement-key.pem         │
│                                        │
│  7. Launch → Instance running in ~60s  │
└────────────────────────────────────────┘

Key Takeaway

EC2 is Amazon's service for renting resizable virtual servers on demand. Instead of buying hardware and waiting weeks, I call an API and get a running machine in minutes, paying per second while it runs. The thing that matters most when picking an instance is the family, because each family optimizes a different resource. General purpose M and T families balance CPU and memory and suit typical web and API services, compute optimized C family suits CPU-heavy work like risk and fraud scoring, memory optimized R and X families suit large in-memory caches and big JVM heaps, and storage optimized I and D families suit databases that need very fast local disks.

When I launch an instance I think through seven parameters, each with a clear job. The AMI is the starting disk image – the operating system plus any pre-installed software like Java. The instance type is the family and size together, such as m6i.large. The key pair is the SSH key I use to log into a Linux box. The security group is the stateful firewall that controls inbound and outbound traffic. The subnet decides which VPC and Availability Zone the instance sits in and whether it is public or private. The IAM role, attached through an instance profile, gives the instance temporary credentials to call AWS services so I never embed access keys. And the storage is the EBS volumes – the root volume plus any extra data disks.

At National Bank of India I used this directly. Our fraud-scoring service is CPU-heavy, so it runs on a compute-optimized C-family type, while our market-data cache is memory-heavy, so it runs on a memory-optimized R-family type. Matching the family to the workload means we pay for the resource the service actually consumes instead of starving one and wasting the other. Every launch goes into a private subnet with a tight security group and an IAM instance profile, so there are no embedded keys and nothing is exposed to the internet.

One senior point I always add is right-sizing and generation choice. Over-provisioning wastes money and under-provisioning causes throttling, so I use CloudWatch metrics and AWS Compute Optimizer to pick the right size, and I prefer the latest generation because newer hardware is cheaper per unit of performance. For JVM workloads I often choose Graviton, the ARM-based g-suffix types, because they usually give the best price for performance.

Remember one sentence: EC2 is a rented virtual server where the family picks what it is good at and the seven launch parameters configure its image, size, access, firewall, network, permissions, and disks.

---

Share
Use ← → arrow keys to navigate