This lesson combines 3 topics: EC2 Advanced Concepts, Containers (ECS, EKS, Fargate), Lambda & Serverless.
Learning Objectives
- Understand EC2 pricing and optimization in depth
- Master Spot Instances strategies
- Know how to design for cost and performance
- Understand the architecture of ECS and EKS
- Master Fargate vs EC2 launch types
- Know how to design container architectures
- Understand Lambda architecture and limits
- Master event-driven patterns
- Know how to optimize Lambda performance
Part 1: EC2 Advanced Concepts
1. EC2 Purchase Options Deep Dive
On-Demand vs Reserved vs Spot
2. Spot Instances Strategies
Spot Fleet
Spot Instance Interruption Handling
Interruption Warning (2 minutes):
1. CloudWatch Event / EventBridge
2. Instance metadata check
3. Graceful shutdown logic
Best Practices:
- Use Auto Scaling with mixed instances
- Checkpointing for long-running jobs
- SQS for job queues (visibility timeout)
- Diversify across instance types and AZs
3. EC2 Fleet
Mixed Instances Policy
{
"LaunchTemplateConfigs": [{
"LaunchTemplateSpecification": {
"LaunchTemplateId": "lt-xxxxx",
"Version": "$Latest"
},
"Overrides": [
{"InstanceType": "c5.large", "WeightedCapacity": 2},
{"InstanceType": "c5.xlarge", "WeightedCapacity": 4},
{"InstanceType": "m5.large", "WeightedCapacity": 2}
]
}],
"TargetCapacitySpecification": {
"TotalTargetCapacity": 100,
"OnDemandTargetCapacity": 20,
"SpotTargetCapacity": 80,
"DefaultTargetCapacityType": "spot"
}
}
4. Capacity Reservations
Types
On-Demand Capacity Reservations:
- Reserve capacity in specific AZ
- No term commitment
- Charged whether used or not
- Can share via AWS RAM
Capacity Reservation + Savings Plans/RI:
- Apply discounts to capacity reservations
- Best of both worlds
5. EC2 Placement Strategies
Comparison
| Strategy | Use Case | Limitation |
|---|---|---|
| Cluster | HPC, low latency | Same rack, single AZ |
| Spread | Critical instances | Max 7 per AZ |
| Partition | HDFS, Cassandra | Max 7 partitions per AZ |
6. Instance Families & Graviton
Graviton generations compared
| Generation | Families | Performance vs prev | Main use case |
|---|---|---|---|
| Graviton2 (2019) | m6g, c6g, r6g, t4g | Baseline (vs x86) | Web apps, containers, dev/test — cost-conscious |
| Graviton3 (2022) | m7g, c7g, r7g | +25% perf, +60% energy efficiency | General-purpose production workloads |
| Graviton4 (2024) | m8g, c8g, r8g, x8g | +30% perf vs Graviton3 | Databases (Aurora, RDS, MemoryDB), in-memory cache, large containers |
Graviton talking points for SAP-C02:
- ARM-based — binaries must be recompiled (most modern runtimes already support it: JVM, Python, Node.js, .NET 6+, Go, Rust). Native x86 binaries do NOT run.
- Pricing: 20-40% cheaper than equivalent x86 in terms of vCPU/RAM.
- Sustainability Pillar: ARM = less energy ⇒ scenarios about "reducing carbon footprint" usually have Graviton as the correct answer.
- Best-fit workloads: stateless web tier, containers (EKS/ECS with Fargate Graviton), open-source databases (PostgreSQL, MySQL on Aurora Graviton), Redis/Memcached.
- DO NOT use for: x86-only legacy apps, GPU workloads (still use p4/p5), high-performance Windows-on-EC2 (ARM Windows support is limited).
Exam keyword
| Question hint | Answer |
|---|---|
| "Reduce cost AND carbon footprint for the web tier" | Graviton (m7g/m8g) or Fargate Graviton |
| "x86 workload + needs to migrate to ARM, modern app (Java/Python/Node)" | Graviton — recompile + test |
| "Legacy .NET Framework Windows app" | x86 (Graviton does not yet fully support Windows .NET Framework) |
Part 2: Containers (ECS, EKS, Fargate)
1. Container Services Overview
2. ECS Architecture
Components
EC2 vs Fargate Launch Type
| Feature | EC2 | Fargate |
|---|---|---|
| Server management | You manage | AWS manages |
| Pricing | Per EC2 instance | Per vCPU/memory/second |
| Scaling | ASG + Capacity Provider | Automatic |
| GPU support | Yes | No |
| Spot pricing | Via EC2 Spot | Fargate Spot |
| Persistent storage | EBS | EFS + EBS (per-task, since 01/2024) + ephemeral storage |
3. EKS Architecture
Components
EKS Add-ons
- CoreDNS
- kube-proxy
- Amazon VPC CNI
- AWS Load Balancer Controller
- EBS CSI Driver
- EFS CSI Driver
4. Service Discovery & Mesh
AWS Cloud Map
AWS App Mesh
Service Mesh for:
- Traffic routing
- Observability (X-Ray integration)
- mTLS between services
- Circuit breakers
- Retries
Components:
- Virtual Nodes
- Virtual Routers
- Virtual Services
- Envoy proxy (sidecar)
2026 note: App Mesh reached end of support (EOS) on 30/09/2026. New workloads use VPC Lattice (managed) or self-managed Istio/Linkerd.
Amazon VPC Lattice (GA 2023)
Managed application networking for service-to-service traffic — it replaces the App Mesh use case for cross-account/cross-VPC microservices.
VPC Lattice is a Regional service: the service network, services, and VPC associations live in one Region. Cross-account sharing via AWS RAM is native; cross-Region is not native — you need an extra connection via Transit Gateway inter-Region peering, VPC peering, or Cloud WAN, then expose it through an endpoint/resource configuration.
When to use VPC Lattice (vs alternatives):
| Use case | Lattice | App Mesh | ALB/NLB + PrivateLink |
|---|---|---|---|
| Cross-account service mesh, IAM-based auth | ✓ best | Complex | Feasible but configuration-heavy |
| Sidecar-free (no Envoy injection) | ✓ | ✗ (Envoy) | ✓ |
| Layer 7 routing with weighted targets | ✓ | ✓ | ALB only |
| EKS service-to-service within a cluster | OK | ✓ (legacy) | ✗ |
| Need circuit breaker, pinned mTLS | Limited | ✓ | ✗ |
| Internal single-VPC traffic | ALB is better | OK | ALB is better |
Exam keyword:
- "Cross-account service communication with least operational overhead" → VPC Lattice
- "Centralized auth + observability for microservices spread across multiple VPCs" → VPC Lattice
- "Existing App Mesh in production" → plan a migration to VPC Lattice or ECS Service Connect (App Mesh reached EOS on 30/09/2026).
5. Container Security
IAM Roles
Task Role:
- Permissions for containers in task
- Access AWS services (S3, DynamoDB, etc.)
Task Execution Role:
- Permissions for ECS agent
- Pull images from ECR
- Send logs to CloudWatch
- Retrieve secrets
Secrets Management
Options:
1. Secrets Manager
- Automatic rotation
- Cross-account sharing
2. Parameter Store
- Simple secrets
- Lower cost
3. Environment variables (not recommended for secrets)
Integration:
{
"secrets": [{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:region:account:secret:name"
}]
}
Part 3: Lambda & Serverless
1. Lambda Architecture
2. Lambda Invocation
Invocation Types
1. SYNCHRONOUS (RequestResponse)
- Wait for function to complete
- Get result immediately
- Examples: API Gateway, ALB
2. ASYNCHRONOUS (Event)
- Fire and forget
- Automatic retry (2 times)
- Examples: S3, SNS, EventBridge
3. POLL-BASED (Event Source Mapping)
- Lambda polls source
- Batch processing
- Examples: SQS, Kinesis, DynamoDB Streams
Event Source Mapping
3. Lambda Performance
Cold Start vs Warm Start
Provisioned Concurrency
Memory & CPU Optimization
4. Lambda@Edge & CloudFront Functions
Comparison
5. Serverless Application Model (SAM)
SAM Template
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Timeout: 30
Runtime: python3.12
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
CodeUri: ./src
Events:
Api:
Type: Api
Properties:
Path: /items
Method: GET
Policies:
- DynamoDBReadPolicy:
TableName: !Ref MyTable
Review Questions
-
What are the Spot Fleet allocation strategies?
Show answer
5 strategies: (1) lowestPrice — launches from the pool with the lowest price (higher interruption risk), (2) diversified — spreads instances across all specified pools (reduces interruptions), (3) capacityOptimized — launches from the pool with the most capacity, (4) capacityOptimizedPrioritized — prefers the pools you specify but still optimizes for capacity, (5) priceCapacityOptimized — balances price and capacity. AWS now recommends
priceCapacityOptimizedfor most workloads (replacingcapacityOptimized, which was recommended previously) — this is also the answer to the "recommended strategy" question on the current exam. -
How do you handle Spot interruptions?
Show answer
(1) Poll Instance Metadata for
/latest/meta-data/spot/termination-timeevery 5 seconds — 2 minutes before termination, (2) an EventBridge rule listening for the EC2 Spot Instance Interruption Warning event, (3) Graceful shutdown: checkpoint work, drain connections, flush state to S3/EFS/DynamoDB, (4) ASG with Mixed Instances — automatically replaces Spot with an On-Demand fallback, (5) SQS Visibility Timeout > processing time so messages are not reprocessed after an interruption. -
How does EC2 Fleet differ from Spot Fleet?
Show answer
Spot Fleet: manages only Spot Instances (and can add On-Demand). EC2 Fleet: manages Spot + On-Demand + Reserved Instances against a target capacity (vCPUs, memory, units). EC2 Fleet is more flexible — you can specify a mix ratio (e.g. 80% Spot, 20% On-Demand), multiple instance types, and allocation strategies. It also supports the instant request type (does not maintain the fleet, only launches). EC2 Fleet is a superset of Spot Fleet capabilities.
-
When should you use Capacity Reservations?
Show answer
Use them when you need to guarantee EC2 capacity in a specific AZ: (1) Disaster Recovery — you need to know capacity is available when you fail over, (2) Compliance — instances must be available in a specific AZ, (3) Planning large events — Black Friday, product launches that need guaranteed scale-out. You pay the On-Demand rate even when unused. Combine with Savings Plans or Zonal RIs to get both capacity and a discount.
-
What does an ECS Task Definition contain?
Show answer
A Task Definition is the blueprint for container(s): (1) Container definitions (image URI, CPU/memory, port mappings, env vars, secrets, log config), (2) Launch type (Fargate/EC2) and network mode (awsvpc for Fargate), (3) CPU and Memory allocation for the task, (4) Task Execution Role (ECS agent permissions), (5) Task Role (app code permissions), (6) Volumes, health check, stop timeout. It is versioned — a new revision is created on every change.
-
How do the Fargate and EC2 launch types differ?
Show answer
Fargate: serverless compute — no EC2 to manage, pay per task vCPU+GB, scales automatically, no ECS agent to run, each task has its own ENI (awsvpc only). EC2 launch type: you manage the EC2 cluster (OS patching, cluster scaling, ECS Agent), pay for EC2 even when idle, can use Spot and GPU instances. Fargate is good for variable workloads and new services; EC2 for steady workloads, cost optimization with large clusters, or GPU needs.
-
What are EKS Managed Node Groups?
Show answer
EKS Managed Node Groups are AWS-managed EC2 nodes for an EKS cluster — AWS automatically provisions, configures, and upgrades the worker nodes. Kubernetes version upgrades are applied automatically when the cluster is upgraded. Less operational overhead than self-managed nodes. Supports Spot Instances and On-Demand. Different from EKS Fargate Profiles (fully serverless, no nodes to manage). Managed Node Groups are the middle ground: you have node visibility but AWS handles the lifecycle.
-
What is AWS Cloud Map used for?
Show answer
Service Discovery for microservices — register services with a name and attributes, and clients discover them via DNS or API calls. ECS integrates with Cloud Map out of the box: when a task starts → it registers automatically, when a task stops → it deregisters automatically. Clients look up
service.namespaceto get healthy endpoints. Supports health check integration. Replaces Consul or Eureka in AWS-native environments. Fits ECS, EKS, Lambda, and EC2 microservices. -
How does the Task Role differ from the Task Execution Role?
Show answer
Task Execution Role: permissions for the ECS agent (infrastructure side) — pull images from ECR, write logs to CloudWatch, get secrets from Secrets Manager/Parameter Store when the task starts. Task Role: permissions for the application code in the container — AWS API calls the app needs at runtime (S3 read, DynamoDB write, SQS send...). Least privilege: the Task Role has only the permissions the app needs, no infrastructure permissions. They are two separate IAM Roles.
-
What are the 3 types of Lambda invocation?
Show answer
(1) Synchronous (RequestResponse) — the caller waits for the response, errors are handled on the caller side (API GW, ALB, Cognito). (2) Asynchronous (Event) — Lambda queues the event, retries 2 times on failure, DLQ for unprocessed events (S3, SNS, EventBridge). (3) Event Source Mapping — Lambda polls the source service (SQS, DynamoDB Streams, Kinesis, Kafka), batch processing. Error handling differs per invocation type — important for architecture design.
- When does a cold start happen?
Show answer
A cold start happens when no warm execution environment is available: (1) First invocation after a deploy, (2) Scale-out when more concurrent executions are needed, (3) After a period of inactivity (the environment is reclaimed). Cold start = download code + init runtime + run init code (import statements, DB connections, SDK clients) = 100ms to a few seconds. To reduce cold starts: Provisioned Concurrency, optimize init code, use SnapStart (Java 11+, Python 3.12+, .NET 8+ — Python and .NET since 11/2024), lazy-load resources.
- What problem does Provisioned Concurrency solve?
Show answer
It solves cold start latency by keeping N execution environments warm and initialized — the function responds immediately with no cold start delay. Good for: latency-sensitive APIs (P99 requirements), functions with heavy init (ML models, connection pools), predictable traffic spikes (8 AM business hours). Cost: charged by the amount of provisioned concurrency × time — even when idle. Trade-off: cost vs latency.
- How does Lambda@Edge differ from CloudFront Functions?
Show answer
Lambda@Edge: runs Node.js/Python, max 5-30 seconds of execution, can make network calls (DynamoDB, Secrets Manager), deployment package max 1 MB for viewer triggers / 50 MB for origin triggers, 4 event triggers (viewer/origin request/response). CloudFront Functions: JavaScript only, max 1 ms, NO network calls, 10 KB code limit, only 2 triggers (viewer request/response). CloudFront Functions are ~6× cheaper, for lightweight operations (header manipulation, URL rewrite, simple redirects). Lambda@Edge for complex logic that needs external data.
- How does Event Source Mapping work?
Show answer
Event Source Mapping lets Lambda poll event sources: SQS, DynamoDB Streams, Kinesis Data Streams, Apache Kafka (MSK), self-managed Kafka. The Lambda service (not the function code) polls the source and batches records → invokes the Lambda function with the batch. Config: BatchSize (1-10,000 records), BisectOnFunctionError (split the batch on failure), DestinationConfig (DLQ/DLS for failed records), Filter patterns. SQS: Lambda deletes messages after successful processing; Kinesis/DDB Streams: automatic checkpointing.
Hands-on Exercises
Part 1: EC2 Advanced Concepts
-
Create an ASG with a Mixed Instances Policy: create a Launch Template, configure an Auto Scaling Group mixing 20% On-Demand / 80% Spot with the
priceCapacityOptimizedallocation strategy and at least 3 instance types (e.g. c5.large, c6i.large, m5.large). Observe in the console which pools the fleet chooses and why. -
Handle Spot interruptions: write a script (user data or a systemd service) that polls
http://169.254.169.254/latest/meta-data/spot/instance-actionevery 5 seconds; when a warning appears, log it to CloudWatch Logs and simulate a graceful shutdown (drain jobs, upload a checkpoint to S3). You can test with the Fault Injection Service (FIS) actionaws:ec2:send-spot-instance-interruptions. -
Compare Graviton cost: launch m5.large (x86) and m7g.large (Graviton3) side by side, run the same simple benchmark (e.g.
sysbench cpu), and compare price/performance. Write down your conclusion for the "reduce cost and carbon footprint" scenario.
Part 2: Containers (ECS, EKS, Fargate)
-
Deploy a service on ECS Fargate: create a cluster, a task definition (nginx or your own app container built and pushed to ECR) with separate Task Role and Task Execution Role, and an ECS Service with 2 tasks behind an ALB. Verify that each task has its own ENI (awsvpc mode) and that logs flow into CloudWatch Logs.
-
Fargate Spot + capacity provider strategy: configure the service to use a mix of
FARGATEbase 1 +FARGATE_SPOTweight 3; scale the service to 8 tasks and observe the distribution. Write down the trade-off for production (Spot tasks can be reclaimed with a 2-min warning). -
Secrets injection: create a secret in Secrets Manager and inject it into the container via
secretsin the task definition (no plaintext env var). Verify the app can read the secret and that the secret does not appear in the console/describe-tasks. -
(Optional) VPC Lattice: create a service network, associate 2 different VPCs, expose an HTTP service with an IAM auth policy — compare the amount of configuration with an equivalent ALB + PrivateLink solution.
Part 3: Lambda & Serverless
-
Lambda Power Tuning: deploy AWS Lambda Power Tuning (a Step Functions state machine) and run tuning for a CPU-bound function with memory levels 128MB–2048MB. Identify the optimal cost/duration point and compare it with the example table in the lesson.
-
Event Source Mapping with SQS: create an SQS queue + DLQ, configure an event source mapping with BatchSize 10 and
maxReceiveCount3. Send intentionally failing messages, observe the retries and the messages landing in the DLQ; explain why the visibility timeout should be ≥ 6× the function timeout. -
Provisioned Concurrency + alias: publish a version, create an alias
live, and enable Provisioned Concurrency = 2 on the alias. Use a script to send 10 concurrent requests and compare P99 latency before/after (cold starts disappear on the 2 warm environments). -
SAM deploy: use the SAM template in section 5 (
sam build && sam deploy --guided) to create an API GET /items that reads DynamoDB; then runsam deleteto clean up the resources.
References
- EC2 Nitro System
- Placement Groups
- EC2 Fleet
- Amazon ECS Developer Guide
- Amazon EKS User Guide
- AWS Fargate
- Amazon ECR
- Amazon VPC Lattice FAQs (Regional service)
- AWS Lambda Developer Guide
- Lambda Best Practices
- Lambda Concurrency
- Lambda@Edge
- Lambda SnapStart (Java, Python, .NET)