Reading25 min read·Module 4

Serverless Cost Optimization

Key concepts

  • Lambda pricing model

  • Memory vs duration tradeoff

  • Provisioned concurrency costs

  • Fargate vs EC2 comparison

  • API Gateway pricing

Overview

Serverless computing offers a pay-per-use pricing model that can dramatically reduce costs for variable workloads. Understanding the pricing models for AWS Lambda, Fargate, and API Gateway is essential for the SAA-C03 exam and for designing cost-optimized serverless architectures.

Core Concept

Serverless cost optimization follows the principle of paying only for what you use. Lambda charges for requests + duration (memory x time), Fargate charges for vCPU + memory per second, and API Gateway charges per request. The key to optimization is right-sizing resources and minimizing execution time.

Exam Tip

Exam questions often compare serverless vs traditional compute costs. Key signals: 'variable/unpredictable traffic' -> Lambda/Fargate, 'consistent 24/7 load' -> consider EC2, 'spiky with idle periods' -> Lambda eliminates idle costs, 'need cold start elimination' -> Provisioned Concurrency adds cost.

Key Concepts

Lambda Pricing Model

AWS Lambda Pricing Model
Figure 1: Lambda Pricing Components

Lambda Pricing Components

Request Charges:

  • $0.20 per 1 million requests
  • First 1 million requests per month are FREE (Free Tier)

Duration Charges:

  • Charged in 1ms increments (previously 100ms)
  • Price based on memory allocated
  • $0.0000166667 per GB-second (approximately)
  • 400,000 GB-seconds FREE per month (Free Tier)

Pricing Formula:

Total Cost = (Requests × $0.0000002) + (GB-seconds × $0.0000166667)

Example Calculation:

  • 10 million requests/month
  • 512 MB memory, 200ms average duration
  • GB-seconds = 10M × 0.5GB × 0.2s = 1,000,000 GB-seconds
  • Request cost: 10M × $0.0000002 = $2.00
  • Duration cost: 1M × $0.0000166667 = $16.67
  • Total: $18.67/month

Lambda Free Tier

Monthly Free Tier (Always Free):

  • 1 million requests per month
  • 400,000 GB-seconds of compute time

Free Tier Examples: | Memory | Free Compute Seconds | |--------|---------------------| | 128 MB | 3,200,000 seconds | | 512 MB | 800,000 seconds | | 1024 MB | 400,000 seconds | | 2048 MB | 200,000 seconds |

Note: Free Tier applies per AWS account, not per function

Memory vs Duration Tradeoff

Lambda Memory vs Duration Tradeoff
Figure 2: Memory Configuration Impact on Cost and Performance

Memory-Duration Optimization

Key Principle: More memory = more CPU = potentially faster execution

CPU Allocation:

  • CPU scales proportionally with memory
  • 1,769 MB = 1 vCPU equivalent
  • 10,240 MB (max) = approximately 6 vCPUs

Optimization Strategy: | Workload Type | Memory Strategy | |---------------|-----------------| | CPU-bound | Increase memory for faster execution | | I/O-bound | Lower memory may be sufficient | | Memory-intensive | Size to actual memory needs |

Cost-Performance Sweet Spot:

  • Higher memory can REDUCE costs if execution time decreases proportionally
  • Test different configurations to find optimal point
  • Use AWS Lambda Power Tuning tool

Example Optimization:

  • 128 MB, 1000ms execution = 0.128 GB-seconds
  • 256 MB, 400ms execution = 0.102 GB-seconds (20% cheaper, 60% faster)
SHAWS Lambda Power Tuning
# Deploy Lambda Power Tuning (via SAM)
git clone https://github.com/alexcasalboni/aws-lambda-power-tuning.git
cd aws-lambda-power-tuning
sam deploy --guided

# Run power tuning analysis
aws stepfunctions start-execution \
  --state-machine-arn arn:aws:states:us-east-1:123456789012:stateMachine:powerTuningStateMachine \
  --input '{
    "lambdaARN": "arn:aws:lambda:us-east-1:123456789012:function:MyFunction",
    "powerValues": [128, 256, 512, 1024, 2048],
    "num": 50,
    "payload": "{}",
    "parallelInvocation": true,
    "strategy": "cost"
  }'

# Analyze Lambda cost breakdown
aws ce get-cost-and-usage \
  --time-period Start=2024-01-01,End=2024-01-31 \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --filter '{
    "Dimensions": {
      "Key": "SERVICE",
      "Values": ["AWS Lambda"]
    }
  }' \
  --group-by Type=DIMENSION,Key=USAGE_TYPE

Provisioned Concurrency Costs

Provisioned Concurrency Pricing

Purpose: Eliminate cold starts by keeping functions initialized

Pricing Components:

  1. Provisioned Concurrency: $0.000004646 per GB-second provisioned
  2. Request charges: Same as standard ($0.20 per 1M)
  3. Duration charges: $0.000009722 per GB-second (when using provisioned)

Cost Calculation:

Provisioned Cost = Provisioned GB-seconds × $0.000004646
Execution Cost = Actual GB-seconds × $0.000009722
Total = Provisioned Cost + Execution Cost + Request Cost

When to Use:

  • Latency-sensitive applications
  • Consistent, predictable traffic patterns
  • APIs requiring sub-100ms response times
  • Applications where cold starts cause timeouts

Cost Comparison (1 GB function, 100 concurrent): | Scenario | Monthly Cost | |----------|--------------| | Standard (variable load) | Pay per use only | | Provisioned (24/7) | ~$339/month baseline | | Provisioned (8 hrs/day) | ~$113/month baseline |

SHProvisioned Concurrency Management
# Configure Provisioned Concurrency
aws lambda put-provisioned-concurrency-config \
  --function-name MyFunction \
  --qualifier prod \
  --provisioned-concurrent-executions 100

# Get Provisioned Concurrency config
aws lambda get-provisioned-concurrency-config \
  --function-name MyFunction \
  --qualifier prod

# Delete Provisioned Concurrency (stop charges)
aws lambda delete-provisioned-concurrency-config \
  --function-name MyFunction \
  --qualifier prod

# Set up scheduled scaling for Provisioned Concurrency
aws application-autoscaling register-scalable-target \
  --service-namespace lambda \
  --resource-id function:MyFunction:prod \
  --scalable-dimension lambda:function:ProvisionedConcurrency \
  --min-capacity 5 \
  --max-capacity 100

# Create scheduled action (scale up for business hours)
aws application-autoscaling put-scheduled-action \
  --service-namespace lambda \
  --resource-id function:MyFunction:prod \
  --scalable-dimension lambda:function:ProvisionedConcurrency \
  --scheduled-action-name scale-up-business-hours \
  --schedule "cron(0 8 ? * MON-FRI *)" \
  --scalable-target-action MinCapacity=50,MaxCapacity=100

Fargate vs EC2 Cost Comparison

Fargate vs EC2 Cost Comparison
Figure 3: Container Hosting Cost Analysis

Fargate Pricing Model

Pricing Dimensions:

  • vCPU: $0.04048 per vCPU per hour
  • Memory: $0.004445 per GB per hour

Pricing Example (1 vCPU, 2 GB):

  • vCPU: $0.04048/hour
  • Memory: $0.004445 × 2 = $0.00889/hour
  • Total: $0.04937/hour = ~$36/month

Fargate Spot:

  • Up to 70% discount vs regular Fargate
  • Tasks can be interrupted with 2-minute warning
  • Best for fault-tolerant workloads

Savings Plans for Fargate:

  • Compute Savings Plans apply to Fargate
  • Up to 52% savings with 1-year commitment
  • Up to 56% savings with 3-year commitment

Fargate vs EC2 Cost Comparison

FactorFargateEC2Winner
Compute Cost (steady 24/7)Higher per-unit costLower per-unit costEC2
Variable/Burst WorkloadsPay per second of usePay even when idleFargate
Management OverheadZero server managementPatching, scaling, etc.Fargate (TCO)
Container StartupSecondsMinutes (if scaling EC2)Fargate
Spot PricingUp to 70% discountUp to 90% discountEC2
Savings PlansUp to 56% (Compute SP)Up to 72% (EC2 Instance SP)EC2

Fargate vs EC2 Decision Framework

Choose Fargate When:

  • Variable or unpredictable workloads
  • Want to eliminate infrastructure management
  • Need rapid scaling (seconds vs minutes)
  • Team lacks EC2/container expertise
  • Workloads run for short periods

Choose EC2 When:

  • Steady 24/7 workloads
  • Cost is primary concern for large scale
  • Need GPU instances (Fargate has limited support)
  • Require specific instance types
  • Can commit to Reserved Instances

Break-Even Analysis:

  • Fargate typically more expensive at >70% utilization
  • EC2 more cost-effective for steady, predictable workloads
  • Factor in operational costs (patching, monitoring, etc.)

Hybrid Approach:

  • EC2 for baseline steady-state
  • Fargate for burst capacity
  • Fargate Spot for batch processing
SHFargate Cost Analysis
# List Fargate tasks and their resource allocation
aws ecs list-tasks --cluster my-cluster

# Describe task definition to see resource allocation
aws ecs describe-task-definition \
  --task-definition my-task:1 \
  --query 'taskDefinition.{cpu:cpu,memory:memory}'

# Get Fargate cost breakdown
aws ce get-cost-and-usage \
  --time-period Start=2024-01-01,End=2024-01-31 \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --filter '{
    "Dimensions": {
      "Key": "SERVICE",
      "Values": ["Amazon Elastic Container Service"]
    }
  }' \
  --group-by Type=DIMENSION,Key=USAGE_TYPE

# Create Fargate Spot capacity provider
aws ecs create-capacity-provider \
  --name fargate-spot-provider \
  --auto-scaling-group-provider '{
    "autoScalingGroupArn": "arn:aws:autoscaling:...",
    "managedScaling": {
      "status": "ENABLED",
      "targetCapacity": 100
    }
  }'

API Gateway Pricing

API Gateway Pricing Models

REST API Pricing:

  • $3.50 per million requests (first 333M)
  • $2.80 per million requests (333M - 667M)
  • $2.38 per million requests (667M - 1B)
  • $1.51 per million requests (over 1B)

HTTP API Pricing:

  • $1.00 per million requests (first 300M)
  • $0.90 per million requests (over 300M)
  • Up to 71% cheaper than REST APIs

WebSocket API Pricing:

  • $1.00 per million messages
  • $0.25 per million connection minutes

Data Transfer:

  • Standard AWS data transfer rates apply
  • $0.09 per GB (first 10 TB out to internet)

Caching (REST API only):

  • $0.02 to $3.80 per hour based on cache size
  • 0.5 GB to 237 GB cache options

REST API vs HTTP API

FeatureREST APIHTTP API
Price per Million Requests$3.50$1.00
AWS Lambda IntegrationYesYes
CachingYes (built-in)No (use CloudFront)
Request ValidationYesNo
API KeysYesNo (use authorizers)
Usage PlansYesNo
Private APIsYesYes
WebSocketNo (separate)No (separate)
Best ForFull-featured APIsSimple/cost-sensitive

API Gateway Cost Optimization

HTTP API Migration:

  • Switch REST to HTTP for up to 71% savings
  • Ensure required features are available
  • HTTP API covers most common use cases

Caching Strategy:

  • Enable caching for repeated requests
  • Cache size based on working set
  • TTL tuning for freshness vs cost

Request Reduction:

  • Batch operations where possible
  • Use GraphQL for reducing request count
  • Implement client-side caching

Direct Lambda URLs:

  • Free alternative for simple use cases
  • No API management features
  • Good for internal services

Cost Comparison (10M requests/month): | API Type | Monthly Cost | |----------|-------------| | REST API | $35.00 | | HTTP API | $10.00 | | Lambda Function URLs | $0.00 (only Lambda costs) |

SHAPI Gateway Cost Management
# Get API Gateway usage
aws apigateway get-usage \
  --usage-plan-id abc123 \
  --start-date 2024-01-01 \
  --end-date 2024-01-31

# Create HTTP API (lower cost)
aws apigatewayv2 create-api \
  --name "cost-optimized-api" \
  --protocol-type HTTP \
  --target "arn:aws:lambda:us-east-1:123456789012:function:MyFunction"

# Enable caching on REST API
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations '[
    {"op": "replace", "path": "/cacheClusterEnabled", "value": "true"},
    {"op": "replace", "path": "/cacheClusterSize", "value": "0.5"}
  ]'

# Create Lambda function URL (free alternative)
aws lambda create-function-url-config \
  --function-name MyFunction \
  --auth-type AWS_IAM

Best Practices

  1. Right-Size Lambda Memory: Use Lambda Power Tuning to find optimal memory configuration
  2. Use HTTP APIs When Possible: 71% cost savings over REST APIs for simple use cases
  3. Implement Caching Layers: API Gateway caching, Lambda response caching, CloudFront
  4. Schedule Provisioned Concurrency: Only provision during peak hours, not 24/7
  5. Leverage Free Tiers: Design to maximize free tier usage for development/testing
  6. Consider Lambda Function URLs: Free alternative for internal or simple APIs
  7. Use Fargate Spot: Up to 70% savings for fault-tolerant containerized workloads
  8. Apply Compute Savings Plans: Covers Lambda, Fargate, and EC2 with single commitment

Common Exam Scenarios

Exam Scenario Decision Guide

ScenarioRecommended SolutionKey Reasoning
Variable traffic API with unpredictable spikesLambda + HTTP APIPay only for actual usage, scales automatically
Latency-sensitive API requiring <50ms responseLambda with Provisioned ConcurrencyEliminates cold starts, consistent performance
Containerized app with steady 24/7 loadEC2 with Reserved InstancesLower cost for consistent workloads
Batch container jobs that can tolerate interruptionFargate SpotUp to 70% savings on container compute
Simple webhook endpoint, cost is priorityLambda Function URLNo API Gateway charges
API with caching needs, full feature set requiredREST API with caching enabledBuilt-in caching, request validation, usage plans
Multi-service architecture (Lambda + Fargate + EC2)Compute Savings PlansSingle commitment covers all compute types
Short-duration containers (< 1 minute)Lambda container imagesPer-millisecond billing more economical

Common Pitfalls

Over-Provisioning Lambda Memory

Allocating maximum memory (10 GB) "just in case" leads to excessive costs. Lambda charges by GB-seconds, so 10 GB for a simple function processing small payloads wastes 90%+ of spend. Always test and right-size memory allocation based on actual requirements.

Provisioned Concurrency 24/7

Running Provisioned Concurrency around the clock for workloads that only need low latency during business hours wastes money. A 1 GB function with 100 provisioned concurrency costs ~$339/month. Use scheduled scaling to provision only during peak periods.

Using REST API When HTTP API Suffices

Defaulting to REST API when HTTP API provides needed functionality costs 3.5x more per request. HTTP APIs support Lambda integration, JWT authorizers, and CORS - sufficient for most use cases. Only use REST API when you need caching, request validation, or usage plans.

Ignoring Cold Start Impact on Cost

Cold starts not only affect latency but also cost money. A function that times out due to cold start is billed for the full timeout duration. Cold starts causing retries multiply your request and duration costs. Address cold starts for reliability AND cost efficiency.

Fargate for Constant Workloads

Using Fargate for containers running 24/7 at high utilization is more expensive than EC2 with Reserved Instances. Fargate excels for variable workloads but costs ~30-40% more for steady-state. Evaluate workload patterns before choosing container hosting.

Quick Reference

Serverless Pricing Summary

ServicePricing ModelFree Tier
Lambda$0.20/1M requests + $0.0000166667/GB-sec1M requests + 400K GB-sec/month
Fargate$0.04048/vCPU-hr + $0.004445/GB-hrNone
API Gateway REST$3.50/1M requests1M requests/month (12 months)
API Gateway HTTP$1.00/1M requests1M requests/month (12 months)

Lambda Cost Formula

Monthly Cost = (Requests × $0.0000002) + (GB-seconds × $0.0000166667)

GB-seconds = (Memory in GB) × (Duration in seconds) × (Number of invocations)

Key Cost Optimization Strategies

StrategySavings PotentialImplementation
Right-size Lambda memory20-50%Lambda Power Tuning
REST to HTTP APIUp to 71%Migrate if features allow
Scheduled Provisioned Concurrency50-70%Auto Scaling scheduled actions
Fargate SpotUp to 70%Use for fault-tolerant tasks
Compute Savings PlansUp to 66%1-3 year commitment
Lambda Function URLs100% API costsReplace simple API Gateway

CLI Quick Reference

# Analyze Lambda function cost drivers
aws lambda get-function-configuration \
  --function-name MyFunction \
  --query '{Memory:MemorySize,Timeout:Timeout}'

# Get Lambda invocation metrics
aws cloudwatch get-metric-statistics \
  --namespace AWS/Lambda \
  --metric-name Invocations \
  --dimensions Name=FunctionName,Value=MyFunction \
  --start-time 2024-01-01T00:00:00Z \
  --end-time 2024-01-31T23:59:59Z \
  --period 2592000 \
  --statistics Sum

# Check Provisioned Concurrency utilization
aws cloudwatch get-metric-statistics \
  --namespace AWS/Lambda \
  --metric-name ProvisionedConcurrencyUtilization \
  --dimensions Name=FunctionName,Value=MyFunction \
  --start-time 2024-01-01T00:00:00Z \
  --end-time 2024-01-31T23:59:59Z \
  --period 86400 \
  --statistics Average

Test Your Knowledge

Q

A company has a Lambda function with 512 MB memory that runs for 2 seconds per invocation. They receive 5 million requests per month. After testing with Lambda Power Tuning, they find that 1024 MB memory reduces execution time to 800ms. Which statement about the cost impact is CORRECT?

ACost will double because memory doubled
BCost will decrease because GB-seconds decreased
CCost will stay the same (memory increase offsets duration decrease)
DCost will increase slightly but performance gains justify it
Q

A startup is building an API that will receive variable traffic (100 requests during quiet hours, 10,000 requests during peak). They need basic Lambda integration and JWT authentication. Which API Gateway option is MOST cost-effective?

AREST API with caching enabled
BHTTP API
CREST API with usage plans
DWebSocket API
Q

A company runs containerized workloads on Fargate. The application handles batch processing that can tolerate interruption and restart. Current monthly Fargate cost is $5,000. Which strategy provides the MOST cost savings?

ASwitch to EC2 with On-Demand instances
BUse Fargate Spot for batch workloads
CApply Compute Savings Plans (3-year)
DMigrate to Lambda container images
Q

A financial services company has a Lambda function serving an API that requires consistent sub-100ms response times during trading hours (9 AM - 4 PM EST). Cold starts are causing occasional timeouts. Which solution is MOST cost-effective?

AEnable Provisioned Concurrency 24/7
BSchedule Provisioned Concurrency for trading hours only
CIncrease Lambda memory to maximum (10 GB)
DUse Lambda Function URLs instead of API Gateway

Further Reading

Related services

LambdaFargateAPI Gateway