devHọc Dev

Week 3 - Day 1: Compute (Advanced EC2, Containers, Lambda/Serverless)

Week 3 – Day 1

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

┌─────────────────────────────────────────────────────────┐│EC2PURCHASEOPTIONS││││ON-DEMAND(100%price)││├──Nocommitment││├──Paybysecond(Linux)orhour(Windows)││└──Bestfor:Short-term,unpredictableworkloads││││RESERVED(1yrmax~40%,3yrmax~72%)││├──1or3yearcommitment││├──Standard(higherdiscount)vsConvertible││└──Bestfor:Steady-stateworkloads││││SPOT(upto90%discount)││├──Canbeinterruptedwith2-minnotice││├──PaycurrentSpotprice(optionalmaxprice)││└──Bestfor:Fault-tolerant,flexibleworkloads││││SAVINGSPLANS(Computemax66%,EC2Instancemax72%)││├──Committo$/hourusage││├──Compute(flexible)orEC2Instance(higherdisc.)││└──Bestfor:Consistentcomputeusage│└─────────────────────────────────────────────────────────┘

2. Spot Instances Strategies

Spot Fleet

┌─────────────────────────────────────────────────────────┐│SPOTFLEET││││TargetCapacity:100vCPUs││││LaunchPools:││┌─────────────────────────────────────────────────┐│││Pool1:c5.large(2vCPU)-Weight:2││││Pool2:c5.xlarge(4vCPU)-Weight:4││││Pool3:m5.large(2vCPU)-Weight:2││││Pool4:m5.xlarge(4vCPU)-Weight:4│││└─────────────────────────────────────────────────┘││││AllocationStrategies(5):││-lowestPrice:Cheapestpoolsfirst(highrisk)││-diversified:Spreadacrosspools││-capacityOptimized:Poolswithmostcapacity││-capacityOptimizedPrioritized:+prioritylist││-priceCapacityOptimized:Balanceprice+capacity││→AWSRECOMMENDEDformostworkloads│└─────────────────────────────────────────────────────────┘

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

StrategyUse CaseLimitation
ClusterHPC, low latencySame rack, single AZ
SpreadCritical instancesMax 7 per AZ
PartitionHDFS, CassandraMax 7 partitions per AZ

6. Instance Families & Graviton

Graviton generations compared

GenerationFamiliesPerformance vs prevMain use case
Graviton2 (2019)m6g, c6g, r6g, t4gBaseline (vs x86)Web apps, containers, dev/test — cost-conscious
Graviton3 (2022)m7g, c7g, r7g+25% perf, +60% energy efficiencyGeneral-purpose production workloads
Graviton4 (2024)m8g, c8g, r8g, x8g+30% perf vs Graviton3Databases (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 hintAnswer
"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

┌─────────────────────────────────────────────────────────┐│AWSCONTAINERSERVICES││││ORCHESTRATION:││├──ECS(AWSnative)││└──EKS(Kubernetes)││││COMPUTE:││├──EC2(self-managed)││├──Fargate(serverless)││└──Outposts(on-premises)││││REGISTRY:││└──ECR(ElasticContainerRegistry)││││DEPLOYMENT:││├──CodeDeploy(ECS)││├──AppMesh(servicemesh)││└──CloudMap(servicediscovery)│└─────────────────────────────────────────────────────────┘

2. ECS Architecture

Components

┌─────────────────────────────────────────────────────────┐│ECSCLUSTER││││┌─────────────────────────────────────────────────┐│││ECSSERVICE││││┌───────────────────────────────────────────┐│││││TASKDEFINITION││││││-Containerimages││││││-CPU/Memory││││││-Portmappings││││││-Environmentvariables││││││-IAMTaskRole│││││└───────────────────────────────────────────┘││││││││┌─────────┐┌─────────┐┌─────────┐│││││TASK││TASK││TASK││││││(running)││(running)││(running)│││││└─────────┘└─────────┘└─────────┘│││└─────────────────────────────────────────────────┘││││CAPACITYPROVIDERS:││├──Fargate││├──FargateSpot││└──EC2AutoScalingGroup│└─────────────────────────────────────────────────────────┘

EC2 vs Fargate Launch Type

FeatureEC2Fargate
Server managementYou manageAWS manages
PricingPer EC2 instancePer vCPU/memory/second
ScalingASG + Capacity ProviderAutomatic
GPU supportYesNo
Spot pricingVia EC2 SpotFargate Spot
Persistent storageEBSEFS + EBS (per-task, since 01/2024) + ephemeral storage

3. EKS Architecture

Components

┌─────────────────────────────────────────────────────────┐│EKSCLUSTER││││┌─────────────────────────────────────────────────┐│││CONTROLPLANE(AWSManaged)││││-APIServer││││-etcd││││-ControllerManager││││-Scheduler│││└─────────────────────────────────────────────────┘│││││▼││┌─────────────────────────────────────────────────┐│││DATAPLANE(Youmanage)││││││││NodeGroups:││││├──ManagedNodeGroups(recommended)││││├──Self-ManagedNodes││││└──FargateProfiles│││└─────────────────────────────────────────────────┘│└─────────────────────────────────────────────────────────┘

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

┌─────────────────────────────────────────────────────────┐│AWSCLOUDMAP││││Namespace:company.local││││Services:││├──api.company.local│││├──Instance1:10.0.1.50:8080│││└──Instance2:10.0.2.50:8080│││││└──database.company.local││└──Instance1:10.0.3.100:5432││││Discovery:DNSorAPI│└─────────────────────────────────────────────────────────┘

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.

┌──────────────────────────────────────────────────────────────┐│VPCLATTICE││││┌──────────────┐│││Service│←logicalservice(consumer-facing)│││Network│scope:VPC,account,orOrganization││└──────┬───────┘│││associate││┌──────┴──────────────────────────────────┐│││VPCs(cross-accountOK,sameRegion)│││└─────────────────────────────────────────┘││││ProviderServices:││-HTTP/HTTPS,gRPC,HTTP/2││-Targettypes:EC2,ALB,Lambda,IP,k8spods(viaEKS)││-Weightedrouting,healthchecks,retries││-IAMauth-basedaccesscontrol(resource-levelpolicies)││-VPCLattice→CloudWatch/Firehoseaccesslogs│└──────────────────────────────────────────────────────────────┘

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 caseLatticeApp MeshALB/NLB + PrivateLink
Cross-account service mesh, IAM-based auth✓ bestComplexFeasible but configuration-heavy
Sidecar-free (no Envoy injection)✓✗ (Envoy)✓
Layer 7 routing with weighted targets✓✓ALB only
EKS service-to-service within a clusterOK✓ (legacy)✗
Need circuit breaker, pinned mTLSLimited✓✗
Internal single-VPC trafficALB is betterOKALB 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

┌─────────────────────────────────────────────────────────┐│LAMBDAFUNCTION││││┌─────────────────────────────────────────────────┐│││EXECUTIONENVIRONMENT││││││││┌─────────────┐┌────────────────────────┐│││││Runtime││FunctionCode││││││(Python,││+Dependencies││││││Node.js)││(LambdaLayer)│││││└─────────────┘└────────────────────────┘││││││││/tmp(512MB-10GBephemeralstorage)│││└─────────────────────────────────────────────────┘││││Configuration:││-Memory:128MB-10,240MB││-Timeout:upto15minutes││-Concurrency:1000default(canincrease)│└─────────────────────────────────────────────────────────┘

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

┌─────────────────────────────────────────────────────────┐│EVENTSOURCEMAPPING││││┌─────────────┐Poll┌─────────────────┐│││SQS│◄────────────│LambdaService││││Queue│││││└─────────────┘Batch│Invokesyour│││(1-10k)│functionwith│││││batchof│││▼│records│││┌──────────────┴──────────────┐│││LambdaFunction│││└─────────────────────────────┘││││BatchSettings:││-BatchSize:1-10,000(SQS),1-10,000(Kinesis)││-BatchWindow:0-300seconds││-Parallelization:Pershard(Kinesis/DynamoDB)│└─────────────────────────────────────────────────────────┘

3. Lambda Performance

Cold Start vs Warm Start

COLDSTART(Firstinvocation):┌────────────────────────────────────────────────────────┐│Download│Initialize│Initialize│Execute││Code│Runtime│Handler│Handler││(50-100ms)│(100-300ms)│(varies)│(varies)│└────────────────────────────────────────────────────────┘Total:500ms-2sWARMSTART(Subsequentinvocations):┌─────────────────────────────────────────────────┐│ExecuteHandlerOnly││(varies)│└─────────────────────────────────────────────────┘Total:Executiontimeonly

Provisioned Concurrency

┌─────────────────────────────────────────────────────────┐│PROVISIONEDCONCURRENCY││││Pre-initializedexecutionenvironments:││││┌────────┐┌────────┐┌────────┐┌────────┐│││Warm││Warm││Warm││Warm││││Env││Env││Env││Env│││└────────┘└────────┘└────────┘└────────┘││││Benefits:││-Nocoldstart││-Predictablelatency││││Cost:││-Payforprovisionedcapacity+invocations│└─────────────────────────────────────────────────────────┘

Memory & CPU Optimization

Memory↑=CPU↑Testresults(example):┌─────────────────────────────────────────────────────────┐│Memory│Duration│Cost/Invocation│BestValue│├──────────┼──────────┼─────────────────┼─────────────────┤│128MB│10.0s│$0.0000208│││256MB│5.5s│$0.0000229│││512MB│3.0s│$0.0000250│││1024MB│1.5s│$0.0000250│←Optimal││2048MB│1.2s│$0.0000400││└─────────────────────────────────────────────────────────┘Tool:AWSLambdaPowerTuning

4. Lambda@Edge & CloudFront Functions

Comparison

┌─────────────────────────────────────────────────────────┐│EDGECOMPUTINGOPTIONS││││CLOUDFRONTFUNCTIONS:││-Sub-millisecondstartup││-JavaScriptonly││-Max10KBcode││-Viewerrequest/responseonly││-Use:URLrewrites,headermanipulation││││LAMBDA@EDGE:││-Regionaldeploymenttoedges││-Node.js,Python││-Package:1MB(viewer)/50MB(origintriggers)││-Alltriggers(viewer+origin)││-Use:Complexlogic,externalcalls│└─────────────────────────────────────────────────────────┘

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

  1. 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 priceCapacityOptimized for most workloads (replacing capacityOptimized, which was recommended previously) — this is also the answer to the "recommended strategy" question on the current exam.

  2. How do you handle Spot interruptions?

    Show answer

    (1) Poll Instance Metadata for /latest/meta-data/spot/termination-time every 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.

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

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

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

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

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

  8. 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.namespace to get healthy endpoints. Supports health check integration. Replaces Consul or Eureka in AWS-native environments. Fits ECS, EKS, Lambda, and EC2 microservices.

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

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

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

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

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

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

  1. 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 priceCapacityOptimized allocation 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.

  2. Handle Spot interruptions: write a script (user data or a systemd service) that polls http://169.254.169.254/latest/meta-data/spot/instance-action every 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) action aws:ec2:send-spot-instance-interruptions.

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

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

  2. Fargate Spot + capacity provider strategy: configure the service to use a mix of FARGATE base 1 + FARGATE_SPOT weight 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).

  3. Secrets injection: create a secret in Secrets Manager and inject it into the container via secrets in 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.

  4. (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

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

  2. Event Source Mapping with SQS: create an SQS queue + DLQ, configure an event source mapping with BatchSize 10 and maxReceiveCount 3. 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.

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

  4. SAM deploy: use the SAM template in section 5 (sam build && sam deploy --guided) to create an API GET /items that reads DynamoDB; then run sam delete to clean up the resources.

References


Next lesson →