The first serverless app I shipped cost $9 a month for the first year. The same workload on EC2 would have been $80. I was a convert. Then traffic grew 50x, I added a few heavy endpoints, and the bill jumped to $2,100/month-more than the EC2 baseline would have been. Serverless isn't cheaper by default. It's cheaper when your traffic is spiky and your requests are cheap to serve. Get those wrong and you'll quietly spend more than you would have on plain VMs.
This is the article I wish I'd had when I started: the SAM template that actually does what you want, the IAM role that's actually least privilege, the cold-start mitigations that actually work, the idempotency layer that actually prevents duplicate side effects, and the cost math that actually tells you when to stop. We're using AWS Lambda because it's the serverless platform most teams start with, but the patterns translate to Cloud Run, Azure Functions, and the others.
When Serverless Is (and Isn't) the Right Call
Let me be honest about this upfront, because the wrong choice here is expensive.
| Workload | Serverless fit | Why |
|---|---|---|
| Spiky HTTP API (10 RPS avg, 1000 RPS peak) | Excellent | You pay for invocations, not idle |
| Steady 100 RPS API 24/7 | Poor | EC2/Fargate is cheaper; you're paying Lambda premium for no benefit |
| Event-driven processing (S3 uploads, SQS) | Excellent | Natural fit; scales with event rate |
| Long-running stream processor (>15 min) | Poor | Lambda's 15-minute timeout; use Fargate or Kinesis Data Analytics |
| Websocket fanout | Mixed | Use API Gateway WebSocket + Lambda, but check Connection WebSocket pricing |
| Heavy ML inference (GPU) | Poor | Lambda has no GPU; use SageMaker endpoints or self-managed |
| Cron jobs (run hourly for 30 seconds) | Excellent | Pay per execution; perfect fit |
| Big data ETL | Mixed | Glue (which is serverless Spark) or Step Functions; pure Lambda gets awkward past ~15 min |
The pattern: serverless wins when you have low average load and high peak load, or when you have discrete event-driven work. It loses when you have steady high load or long-running compute. The break-even point is roughly 200-400ms average duration at steady moderate traffic-past that, container pricing usually wins.
Prerequisites
- An AWS account with billing alerts enabled. (Seriously. Enable them now.)
- The AWS CLI v2 configured with credentials that can create IAM roles, Lambda functions, API Gateway, and DynamoDB.
- AWS SAM CLI installed:
brew install aws-sam-cli(macOS) or follow AWS docs for Linux/Windows. - Python 3.12 (or whatever Lambda runtime you're targeting).
- Docker (SAM local uses it for the Lambda runtime container).
- A basic understanding of IAM, JSON, and what a Lambda function is.
BashCopy
Verify
aws --version
sam --version
python3 --version
docker --version
Architecture: What We're Building
A REST API for a URL shortener. Three endpoints: create short URL, resolve short URL, list URLs for a user. Backed by DynamoDB. Behind API Gateway. With structured logging, tracing, and idempotency on the create endpoint.
CodeCopy
plaintext
[client]
|
v
+----------------------+
| API Gateway HTTP |
| (REST, $0.90/M req)|
+----------+-----------+
|
+----------------+----------------+
| | |
v v v
POST /urls GET /urls/{id} GET /urls
(create) (resolve) (list)
| | |
v v v
+--------------------------------------------------+
| Lambda (Python 3.12) |
| - Powertools: logging, tracing, metrics |
| - Idempotency layer on POST |
| - boto3 DynamoDB client (reuse outside handler)|
+----------------------+---------------------------+
|
v
+-------------------+
| DynamoDB |
| Table: urls |
| PK: short_id |
| GSI: user_id+created_at
| ($1.25/M writes, $0.25/M reads)
+-------------------+
markdown
The whole thing scales to zero when nobody's using it, costs a few dollars at moderate traffic, and survives a Hacker News front page without you doing anything.
Project Layout
CodeCopy
plaintext
url-shortener/
template.yaml # SAM/CloudFormation template
samconfig.toml # deploy config (region, stack name, capabilities)
src/
init.py
app.py # Lambda handler + business logic
requirements.txt # Python deps (boto3, powertools)
models.py # Pydantic schemas
idempotency.py # Idempotency layer
tests/
conftest.py
test_app.py
test_idempotency.py
.github/
workflows/
deploy.yml # CI/CD: test, build, deploy
markdown
SAM convention: each Lambda function has its own folder under src/ with its own requirements.txt. This keeps cold-start dependencies scoped-if you have 5 functions, you don't want all 5 sharing a 50MB bundle with unused libs. For this demo, one function is enough.
The SAM Template
YAMLCopy
yaml
template.yaml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: URL shortener serverless API
Globals:
Function:
Runtime: python3.12
MemorySize: 512
Timeout: 10
Tracing: Active
Environment:
Variables:
LOG_LEVEL: INFO
POWERTOOLS_SERVICE_NAME: url-shortener
URLS_TABLE: !Ref UrlsTable
Layers:
- !Sub arn:aws:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV3:3
Resources:
UrlsTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: url-shortener-urls
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- { AttributeName: short_id, AttributeType: S }
- { AttributeName: user_id, AttributeType: S }
- { AttributeName: created_at, AttributeType: S } KeySchema:
- { AttributeName: short_id, KeyType: HASH } GlobalSecondaryIndexes:
- IndexName: user-urls KeySchema:
- { AttributeName: user_id, KeyType: HASH }
- { AttributeName: created_at, KeyType: RANGE } Projection: ProjectionType: ALL PointInTimeRecoverySpecification: PointInTimeRecoveryEnabled: true
Api:
Type: AWS::Serverless::Api
Properties:
StageName: prod
TracingEnabled: true
MethodSettings:
- ResourcePath: "/" HttpMethod: "" ThrottlingBurstLimit: 200 ThrottlingRateLimit: 100 LoggingLevel: INFO
CreateUrlFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.create_url_handler
Policies:
- DynamoDBCrudPolicy: TableName: !Ref UrlsTable Events: Create: Type: Api Properties: RestApiId: !Ref Api Path: /urls Method: post
ResolveUrlFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.resolve_url_handler
Policies:
- DynamoDBReadPolicy: TableName: !Ref UrlsTable Events: Resolve: Type: Api Properties: RestApiId: !Ref Api Path: /urls/{short_id} Method: get
ListUrlsFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.list_urls_handler
Policies:
- DynamoDBReadPolicy: TableName: !Ref UrlsTable Events: List: Type: Api Properties: RestApiId: !Ref Api Path: /urls Method: get
Outputs:
ApiUrl:
Value: !Sub "https://${Api}.execute-api.${AWS::Region}.amazonaws.com/prod"
markdown
Things worth noting:
-
Globalsdefines defaults applied to all functions. Don't repeat yourself across three functions. -
Tracing: Activeenables AWS X-Ray tracing. Costs nothing extra (free tier) and lets you see end-to-end request flow in the console. - The Powertools layer is a public Lambda layer maintained by AWS. Gives you structured logging, metrics, and tracing with no bundle bloat. Add it.
-
PAY_PER_REQUESTbilling on DynamoDB. No capacity to manage. Cheaper for spiky workloads. -
PointInTimeRecoverySpecificationenables PITR on DynamoDB. Costs extra but is non-negotiable for production data. -
Separate functions per endpoint. Each function has its own IAM policy scoped to exactly what it needs.
CreateUrlFunctiongets CRUD;ResolveUrlFunctiongets read-only. This is what "least privilege" actually looks like. - API Gateway throttling at 100 RPS / 200 burst. Stops a misbehaving client from running up your Lambda bill.
The Lambda Handler: Production-Quality Code
PythonCopy
python
src/app.py
import json
import os
import secrets
from typing import Any
import boto3
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.metrics import Metrics
from boto3.dynamodb.conditions import Key
from botocore.config import Config as BotoConfig
from idempotency import IdempotencyLayer
from models import CreateUrlRequest, UrlRecord
logger = Logger()
tracer = Tracer()
metrics = Metrics()
Reuse outside handler - boto3 clients are expensive to construct.
Lambda reuses the execution environment across invocations (warm starts),
so this client persists and saves ~200ms per warm invocation.
_table = None
_idempotency = None
def get_table():
global _table
if _table is None:
dynamo = boto3.resource(
"dynamodb",
config=BotoConfig(
retries={"max_attempts": 3, "mode": "standard"},
connect_timeout=2,
read_timeout=2,
),
)
_table = dynamo.Table(os.environ["URLS_TABLE"])
return _table
def get_idempotency():
global _idempotency
if _idempotency is None:
_idempotency = IdempotencyLayer(
table_name="url-shortener-idempotency",
ttl_seconds=3600,
)
return _idempotency
app = APIGatewayRestResolver()
@app.post("/urls")
@metrics.log_metrics(capture_cold_start_metric=True)
@tracer.capture_method
def create_url():
body = app.current_event.json_body
request = CreateUrlRequest(**body)
user_id = app.current_event.request_context.authorizer.get("principalId", "anonymous")
# Idempotency: same payload+user within 1h returns the same short_id.
idem_key = f"{user_id}:{hash(json.dumps(body, sort_keys=True))}"
cached = get_idempotency().get(idem_key)
if cached:
logger.info("idempotent_replay", key=idem_key)
return {"statusCode": 200, "body": json.dumps(cached)}
short_id = secrets.token_urlsafe(6)[:8]
record = UrlRecord(
short_id=short_id,
target_url=request.target_url,
user_id=user_id,
created_at=import("datetime").datetime.utcnow().isoformat(),
clicks=0,
)
get_table().put_item(Item=record.model_dump())
get_idempotency().put(idem_key, record.model_dump())
metrics.add_metric(name="UrlCreated", unit="Count", value=1)
return {"statusCode": 201, "body": record.model_dump_json()}
@app.get("/urls/")
@metrics.log_metrics(capture_cold_start_metric=True)
@tracer.capture_method
def resolve_url(short_id: str):
response = get_table().get_item(Key={"short_id": short_id})
item = response.get("Item")
if not item:
return {"statusCode": 404, "body": json.dumps({"error": "not found"})}
# Async increment clicks via UpdateItem (no extra Lambda invocation)
get_table().update_item(
Key={"short_id": short_id},
UpdateExpression="ADD clicks :inc",
ExpressionAttributeValues={":inc": 1},
)
record = UrlRecord(**item)
return {"statusCode": 302, "headers": {"Location": record.target_url}}
@app.get("/urls")
@metrics.log_metrics(capture_cold_start_metric=True)
@tracer.capture_method
def list_urls():
user_id = app.current_event.request_context.authorizer.get("principalId", "anonymous")
response = get_table().query(
IndexName="user-urls",
KeyConditionExpression=Key("user_id").eq(user_id),
ScanIndexForward=False,
Limit=50,
)
return {"statusCode": 200, "body": json.dumps(response.get("Items", []))}
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
def lambda_handler(event: dict[str, Any], context: Any) -> dict[str, Any]:
return app.resolve(event, context)
Handler aliases used by SAM template
create_url_handler = lambda_handler
resolve_url_handler = lambda_handler
list_urls_handler = lambda_handler
markdown
A few decisions worth explaining:
- Boto3 client reuse via module-level globals. Lambda freezes the execution environment between warm invocations. A client constructed once at module load is reused across thousands of invocations. Constructing it inside the handler adds ~200ms per invocation. This is the single biggest Lambda performance optimization.
-
Powertools
APIGatewayRestResolverfor routing. Cleaner than manual event parsing, supports path parameters, and integrates with the OpenAPI spec API Gateway generates. -
capture_cold_start_metric=Trueemits aColdStartmetric. Critical for tracking how often cold starts happen and which functions have the worst ones. - Idempotency layer on POST. Lambda can be invoked multiple times for the same event (SQS retries, API Gateway timeout + retry, client retry). Without idempotency, a double-click creates two short URLs.
-
UpdateItemwithADD clicks :incinstead of read-modify-write. Atomic counter, no race condition, no extra Lambda invocation. -
No
print()calls. Use Powertoolslogger.info(). Structured JSON output, correlated with request ID, ingested by CloudWatch Logs Insights.
Idempotency Layer: Why You Need It and How
Lambda is at-least-once. The same event can be delivered multiple times. Sources of duplicate invocations:
- API Gateway timeout (29s) + client retry
- SQS retries on failure
- EventBridge at-least-once delivery
- Client double-click
- Lambda internal retries on transient errors
If your handler creates a database row, sends an email, or charges a credit card, duplicates are a bug. The fix is an idempotency layer: store a key derived from the request, check it before processing, return the cached result if it exists.
PythonCopy
python
src/idempotency.py
import time
import boto3
from botocore.exceptions import ClientError
class IdempotencyLayer:
'''DynamoDB-backed idempotency with optimistic concurrency.
Uses PutItem with a conditional expression to atomically claim a key.
Subsequent puts for the same key fail with ConditionalCheckFailedException,
which we treat as "another invocation is processing or has processed this."
'''
def init(self, table_name: str, ttl_seconds: int = 3600):
self._table = boto3.resource("dynamodb").Table(table_name)
self._ttl = ttl_seconds
def get(self, key: str) -> dict | None:
response = self._table.get_item(Key={"idempotency_key": key})
return response.get("Item", {}).get("result")
def put(self, key: str, result: dict) -> None:
expires_at = int(time.time()) + self._ttl
try:
self._table.put_item(
Item={
"idempotency_key": key,
"result": result,
"expires_at": expires_at,
},
ConditionExpression="attribute_not_exists(idempotency_key)",
)
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
# Another invocation already wrote this key. Treat as success
# - they've stored the result, we just don't have it locally.
return
raise
plaintext
The DynamoDB table for this needs idempotency_key as the partition key and TTL enabled on expires_at. Add it to your SAM template:
YAMLCopy
yaml
IdempotencyTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: url-shortener-idempotency
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- { AttributeName: idempotency_key, AttributeType: S } KeySchema:
- { AttributeName: idempotency_key, KeyType: HASH } TimeToLiveSpecification: AttributeName: expires_at Enabled: true
markdown
Note: this is a simplified version. AWS Powertools ships a full idempotency decorator that handles in-progress states, parallel invocation coordination, and payload hashing. For anything serious, use @idempotent from Powertools rather than rolling your own. The pattern above is the underlying mechanism-understand it, then use the library.
Cold Starts: The Real Story
Cold starts happen when Lambda needs to spin up a new execution environment. The lifecycle:
CodeCopy
plaintext
[cold start] [warm invocations]
download code → handler() runs
init runtime → handler() runs
init module-level code → handler() runs
construct clients → handler() runs
handler() runs first time handler() runs
plaintext
The first invocation pays the full cost. Subsequent invocations reuse the warm environment. Cold starts typically add 500ms-3s depending on runtime and bundle size.
Cold start contributors, ranked by impact:
| Factor | Impact | Mitigation |
|---|---|---|
| Runtime | Java > C# > Python > Node > Go | Pick a fast-init runtime (Go, Node) for latency-critical paths |
| Bundle size | Larger bundle = slower download/extract | Strip dev deps, use Layers for shared code |
| Heavy module-level init | Constructing clients, loading models at import time | Defer to first invocation (lazy init) |
| VPC attachment | ENI creation adds 1-10s | Use Lambda Hyperplane (no ENI penalty since 2019); avoid VPC if you don't need it |
| Provisioned concurrency | Pre-warmed instances | Pay for it; only for latency-critical paths |
| SnapStart (Java) | Restores from snapshot instead of cold init | Java-only, huge win for JVM workloads |
Provisioned concurrency is the nuclear option. You pay for the capacity whether requests arrive or not. For an API that needs to respond in <100ms always, it's worth it. For most APIs, accept the cold start and tune the other factors.
YAMLCopy
yaml
Provisioned concurrency in SAM
CreateUrlFunction:
Type: AWS::Serverless::Function
Properties:
# ... other props ...
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 5
AutoPublishAlias: live # required for provisioned concurrency
plaintext
The non-obvious win: move heavy initialization out of module scope into the handler with lazy init. Compare:
PythonCopy
python
BAD: pays cost on every cold start, even if this invocation doesn't use it
import pandas as pd
DF = pd.read_csv("reference_data.csv") # 800ms cold start tax
def handler(event, context):
if event.get("use_df"):
return process(DF)
return {"ok": True}
GOOD: pays cost only when actually needed
_DF = None
def get_df():
global _DF
if _DF is None:
import pandas as pd
_DF = pd.read_csv("reference_data.csv")
return _DF
def handler(event, context):
if event.get("use_df"):
return process(get_df())
return {"ok": True}
markdown
Production Considerations
Scaling
Lambda scales automatically: one concurrent invocation per request. The default account-wide concurrency limit is 1,000. If you exceed it, requests get throttled (429). For an API that can spike, request a quota increase ahead of time and set a per-function reserved concurrency to prevent one function from starving others.
YAMLCopy
yaml
CreateUrlFunction:
Type: AWS::Serverless::Function
Properties:
# ... other props ...
ReservedConcurrentExecutions: 100 # cap; protects other functions
markdown
Performance
- Memory is the only knob that scales CPU. 128MB = 1 vCPU share; 1769MB = 1 full vCPU; 10GB = 6 vCPUs. For CPU-bound work, increase memory.
- Use Lambda Power Tools'
lambda-power-tuningto find the sweet spot for your function. Often, more memory = lower total cost because the function runs faster. - Use ARM64 (Graviton) for ~20% price/perf improvement if your code is compatible.
Security
- IAM roles per function with minimal permissions. Don't reuse one role across functions.
- No secrets in environment variables. Use AWS Secrets Manager or Parameter Store, fetched at cold start, cached at module level.
- Enable API Gateway authorizers (Lambda authorizer, Cognito, or IAM auth). Don't expose endpoints publicly without auth.
- VPC for resources that need it, but don't put Lambda in a VPC just because. Public APIs and DynamoDB don't need VPC.
Monitoring
- CloudWatch Logs for structured logs (Powertools emits JSON).
- CloudWatch Metrics for runtime metrics (invocations, errors, duration, throttles, concurrent executions).
- Custom metrics via Powertools
metrics.add_metric()- these become CloudWatch embedded metrics, queryable in Metrics Insights. - X-Ray for distributed tracing.
- Set CloudWatch Alarms on
Errors,Throttles,Duration(p99), andConcurrentExecutions.
YAMLCopy
yaml
CreateUrlAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: CreateUrl-Errors
MetricName: Errors
Namespace: AWS/Lambda
Dimensions:
- { Name: FunctionName, Value: !Ref CreateUrlFunction } Statistic: Sum Period: 60 EvaluationPeriods: 5 Threshold: 5 ComparisonOperator: GreaterThanThreshold TreatMissingData: notBreaching
markdown
Logging
Powertools logs as JSON with request ID, correlation ID, cold start flag, and your custom fields. CloudWatch Logs Insights queries it directly:
CodeCopy
plaintext
filter level == "ERROR"
| stats count() by function_name
| sort @timestamp desc
| limit 50
markdown
Don't log sensitive data. CloudWatch Logs is not encrypted by default (enable CMK if needed). PII in logs is a compliance issue.
Deployment
- Use
sam deploy --guidedonce to set upsamconfig.toml. Subsequent deploys:sam build && sam deploy. - Enable CI/CD. GitHub Actions to SAM deploy on merge to main.
- Use
AutoPublishAlias: liveand pre/post traffic hooks for canary deployments. - Keep deployment under 5 minutes. SAM deploys are CloudFormation under the hood, which is slow. Don't add unnecessary resources to the same stack.
Optimization
- Strip dev dependencies.
pip install --no-deps -t build/or use SAM build with properrequirements.txt. - Use Lambda Layers for shared code across functions.
- Avoid large libraries.
pandasis 50MB; considerpolarsorpyarrowfor Lambda. - Pre-compile native extensions for the Lambda runtime (manylinux wheels).
Common Mistakes
Mistake 1: Constructing boto3 clients inside the handler. Adds ~200ms to every invocation. Move to module scope with lazy init.
Mistake 2: One Lambda function for the whole API. You lose independent scaling, IAM scoping, and per-function monitoring. Split by responsibility.
Mistake 3: Ignoring retries. Lambda can be invoked multiple times for the same event. Without idempotency, you double-charge credit cards, double-send emails, double-write rows.
Mistake 4: Using print() instead of structured logging. CloudWatch Logs gets plain text, you can't query it. Use Powertools Logger.
Mistake 5: Default 3-second timeout on heavy work. Lambda times out, retried, runs again, never completes. Either raise the timeout or break the work into smaller chunks.
Mistake 6: Putting Lambda in a VPC unnecessarily. Old penalty was 10s cold start for ENI creation. Fixed in 2019, but you still don't need VPC for DynamoDB/S3 access. Only use VPC if accessing RDS or internal services.
Mistake 7: One IAM role for all functions. Loses least privilege. A bug in one function can delete DynamoDB tables it shouldn't touch.
Mistake 8: Not setting reserved concurrency. One runaway function eats the account limit. Set per-function caps.
Mistake 9: Sync HTTP calls inside Lambda. If Lambda A calls Lambda B synchronously, you pay for both, plus API Gateway overhead, plus you've built distributed synchronous spaghetti. Use Step Functions or EventBridge for orchestration.
Mistake 10: Not using Powertools. Rolling your own logging/tracing/metrics is reinventing a wheel that AWS maintains well.
Troubleshooting Real Production Issues
Symptom: 502 from API Gateway intermittently.
Likely your Lambda is timing out. Default Lambda timeout is 3s; API Gateway waits 29s. If Lambda exceeds its timeout, API Gateway sees no response and returns 502. Check Duration metric and CloudWatch Logs for "Task timed out".
Symptom: Lambda function works in dev, fails in prod.
Almost always IAM. The dev role has AdministratorAccess; the prod role has scoped permissions. Compare the two and add the missing action. Use IAM Policy Simulator to test.
Symptom: Cold start takes 8 seconds.
Probably VPC attachment (old behavior) or heavy module-level init. Check the function's logs for the INIT_START to first START gap. If it's >2s, profile your imports. python -X importtime app.py shows per-import cost.
Symptom: DynamoDB calls fail intermittently with ProvisionedThroughputExceededException.
On-Demand mode shouldn't throw this. If you're on provisioned capacity, the burst bucket is exhausted. Switch to On-Demand or raise capacity.
Symptom: CloudWatch Logs are missing entries.
Lambda may be hitting log throttling (10 logs/s/-stream by default). Use Powertools Logger which batches; or check if your function is creating many log streams (which it shouldn't-Lambda manages streams).
Symptom: Function invocation count is 10x what you expected.
Either retries (check Errors metric) or you've built a retry loop somewhere (Lambda A → SQS → Lambda B → SQS → ...). Trace the event path.
Symptom: Costs are climbing with no traffic increase.
Probably retries. A function that fails and retries 3x costs 4x. Check Errors and Throttles. Also check for a forgotten EventBridge rule firing every minute.
Symptom: API Gateway returns 429.
You hit the API Gateway or Lambda concurrency limit. Raise it via quota request, or set reserved concurrency appropriately.
Testing Serverless Apps
Three levels:
-
Unit tests for handler logic. Mock boto3 with
motoorstubber. Fast, run in CI on every commit.
PythonCopy
python
tests/test_app.py
import json
import pytest
from moto import mock_aws
import boto3
from app import lambda_handler
@pytest.fixture
def dynamo_table():
with mock_aws():
dynamo = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamo.create_table(
TableName="url-shortener-urls",
KeySchema=[{"AttributeName": "short_id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "short_id", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
os.environ["URLS_TABLE"] = "url-shortener-urls"
yield table
def test_create_url(dynamo_table, monkeypatch):
# Reset module-level cache so the test client picks up our mocked table
import app
app._table = None
event = {
"httpMethod": "POST",
"path": "/urls",
"body": json.dumps({"target_url": "https://example.com"}),
"requestContext": {"authorizer": {"principalId": "user-1"}},
}
response = lambda_handler(event, None)
assert response["statusCode"] == 201
body = json.loads(response["body"])
assert body["target_url"] == "https://example.com"
assert len(body["short_id"]) >= 6
markdown
- Integration tests with LocalStack. LocalStack emulates AWS services locally. Run the full SAM template against it; verify the actual API Gateway -> Lambda -> DynamoDB flow.
- End-to-end tests against a deployed stage. After deploy, hit the real API with httpx. Slow but catches issues unit tests miss (IAM, CloudFormation drift).
YAMLCopy
yaml
.github/workflows/deploy.yml
name: deploy
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5 with: { python-version: "3.12" }
- run: pip install -r src/requirements.txt pytest moto
- run: pytest tests/ -v deploy: needs: test runs-on: ubuntu-latest permissions: id-token: write contents: read steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy aws-region: us-east-1
- uses: aws-actions/setup-sam@v2
- run: sam build
- run: sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
Cost Considerations, Alternatives, Comparison
The honest cost math. For a Lambda + API Gateway + DynamoDB stack:
| Component | Pricing | At 1M req/month | At 100M req/month |
|---|---|---|---|
| Lambda (256MB, 100ms avg) | $0.0000000167/ms-GB | ~$1.70 | ~$170 |
| API Gateway REST | $0.90/M requests | $0.90 | $90 |
| API Gateway HTTP API | $0.10/M requests | $0.10 | $10 |
| DynamoDB On-Demand writes | $1.25/M | $1.25 | $125 |
| DynamoDB On-Demand reads | $0.25/M | $0.25 | $25 |
| CloudWatch Logs | $0.50/GB ingest | ~$0.50 | ~$50 |
| X-Ray | Free for first 100k traces | $0 | ~$5 |
| Total (rough) | ~$5 | ~$525 |
For comparison, an EC2 t3.medium running the same API 24/7: ~$30/month. Break-even is somewhere around 5-10M requests/month, depending on duration.
The numbers tell the story: serverless is wildly cheaper at low volume, comparable at moderate volume, more expensive at high steady volume. The reason to choose serverless isn't always cost-it's ops. No patching, no scaling config, no capacity planning. You pay for the managed service.
| Platform | Sweet spot | Pricing model | Cold start | Ecosystem |
|---|---|---|---|---|
| AWS Lambda | AWS-centric apps | Per-invocation + duration | 100ms-3s | Largest; tied to AWS services |
| Google Cloud Run | Containerized services | Per-vCPU-sec + per-GB-sec | 0-2s | Container-native; great DX |
| Azure Functions | Microsoft stack | Per-invocation + duration | 200ms-3s | Tied to Azure |
| Cloudflare Workers | Edge compute, tiny | Per-request | ~5ms (V8 isolates) | Edge-first; limited runtime |
| Fly.io Machines | Containerized, global | Per-sec + idle | ~50ms | Container-native; simple |
| Modal / Replicate | ML/data workloads | Per-sec | Varies | Built for Python data/ML |
Cloud Run deserves a special mention. It's "serverless containers" - you ship a Docker image, Google runs it on demand, scales to zero. No Lambda-style packaging limits, no runtime constraints. For teams that want serverless billing with container ergonomics, it's often the best choice. Cold start is comparable to Lambda for similar workloads.
Real-World Use Cases
URL shortener. Spiky traffic (viral links), low average load, simple state. Lambda + DynamoDB + API Gateway. Costs $5-50/month for moderate traffic. EC2 baseline would be $30/month with worse scaling.
Webhook receiver. Stripe webhooks → API Gateway → Lambda → SQS → another Lambda for processing. Spiky (Stripe retries), idempotent (event IDs), stateless. Perfect fit.
Image thumbnailing on S3 upload. S3 event → Lambda → resized images back to S3. Spiky (bursty uploads), stateless, fast (ImageMagick on small images). Classic Lambda use case.
Scheduled data sync. EventBridge cron → Lambda → fetch from external API → write to DynamoDB. Runs hourly for 30 seconds. Cost: pennies per month.
Multi-tenant SaaS API. Lambda + DynamoDB per-tenant tables or per-tenant row scoping. Scales with customer count, no idle capacity. Costs track usage.
Slack bot slash command handler. API Gateway → Lambda → Slack API. Sudden bursts when many users run the same command. Stateful conversation state in DynamoDB.
Chat bot backend. Lex or custom NLU → Lambda → DynamoDB for conversation state. Lambda handles each turn; state persists in DynamoDB. Stateless Lambdas are easy to version.
The use cases that fit Lambda well share a pattern: spiky traffic, short-running work, event-driven triggers, stateful data in a managed store. The use cases that don't fit: long-running streams, heavy compute, steady high load, GPU work, anything needing persistent connections.
Conclusion
Serverless is a tool, not a religion. It's the right tool when your workload is spiky, short-running, and event-driven. It's the wrong tool when your workload is steady, long-running, or compute-heavy. The cost math doesn't lie-run the numbers for your actual workload before committing.
The patterns in this article are the ones that have actually worked in production: per-function IAM roles, idempotency on writes, Powertools for observability, lazy initialization, separate functions per endpoint, and CI/CD via SAM. Steal them. The biggest mistake teams make with serverless is treating it as "free compute" and skipping the engineering rigor you'd apply to any other deployment. Apply the rigor, and serverless delivers on its promise. Skip it, and you'll have a $2,000 bill and a 502 error page.
Originally published on Mango Developer.
Top comments (0)