Build a Cost-Aware Serverless API on AWS with Lambda, API Gateway, and DynamoDB
Learn how to design a production-ready serverless API on AWS using Lambda, API Gateway, and DynamoDB, with practical guidance on cost controls, security, and observability.
Serverless is a great fit for APIs that need to scale quickly without managing servers. In this article, we’ll build a simple but production-minded serverless API using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.
The goal is not just to make the API work, but to make it secure, observable, and cost-aware.
Architecture
The application uses three core AWS services:
- Amazon API Gateway receives HTTPS requests and routes them to Lambda.
- AWS Lambda contains the application logic.
- Amazon DynamoDB stores application data with low-latency access.
A typical request flow looks like this:
Client
→ Amazon API Gateway
→ AWS Lambda
→ Amazon DynamoDB
→ ResponseThis design removes server management, scales automatically, and lets you pay primarily for the requests and compute you actually use.
Design the API
For this example, imagine a simple task-management API.
Method | Endpoint | Purpose |
|---|---|---|
POST | /tasks | Create a task |
GET | /tasks/{id} | Get one task |
GET | /tasks | List tasks |
DELETE | /tasks/{id} | Delete a task |
Each task can include:
{
"taskId": "123",
"title": "Deploy serverless API",
"status": "in_progress",
"createdAt": "2026-11-02T05:45:00Z"
}Model the DynamoDB Table
Use a single-table design when your access patterns are known.
For this example, a simple table is enough:
- Partition key:
PK
- Sort key:
SK
Store tasks like this:
PK = USER#<userId>
SK = TASK#<taskId>This makes it easy to retrieve all tasks for a user while keeping records isolated by user.
Lambda Handler Example
Here is a minimal Python example for creating a task:
import json
import os
import uuid
from datetime import datetime, timezone
import boto3
table = boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
def handler(event, context):
try:
body = json.loads(event.get("body") or "{}")
title = body.get("title")
if not title:
return response(400, {"message": "title is required"})
task_id = str(uuid.uuid4())
now = datetime.now(timezone.utc).isoformat()
table.put_item(
Item={
"PK": f"USER#demo-user",
"SK": f"TASK#{task_id}",
"taskId": task_id,
"title": title,
"status": body.get("status", "todo"),
"createdAt": now,
}
)
return response(201, {"taskId": task_id, "title": title})
except Exception:
return response(500, {"message": "Internal server error"})
def response(status_code, payload):
return {
"statusCode": status_code,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(payload),
}In a real application, replace
demo-user with an authenticated user identifier from Amazon Cognito, JWT claims, or another identity provider.Secure the API
Do not rely on API Gateway alone for authorization.
Recommended controls:
- Use Amazon Cognito or a JWT authorizer to authenticate users.
- Apply least-privilege IAM permissions to each Lambda function.
- Restrict DynamoDB access to only the required table and actions.
- Enable AWS WAF on API Gateway for public-facing workloads.
- Validate request bodies before writing to DynamoDB.
Example least-privilege IAM policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:Query",
"dynamodb:DeleteItem"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Tasks"
}
]
}Add Observability
A serverless API can fail in ways that are hard to debug without telemetry.
Add:
- Amazon CloudWatch Logs for Lambda logs.
- AWS X-Ray for distributed tracing.
- CloudWatch alarms for Lambda errors, throttles, latency, and API Gateway 5xx responses.
- Structured JSON logging so logs are easier to search.
Example structured log:
{
"level": "INFO",
"requestId": "abc-123",
"userId": "demo-user",
"action": "create_task",
"status": "success"
}Control Costs
Serverless can be inexpensive, but unbounded usage can still create surprises.
Practical cost controls:
- Set API Gateway usage plans and throttling limits.
- Use Lambda memory sizing based on measured performance, not guesswork.
- Use DynamoDB on-demand capacity for unpredictable traffic, or provisioned capacity for stable workloads.
- Add CloudWatch billing alarms.
- Cache frequent read responses using Amazon API Gateway caching or Amazon CloudFront where appropriate.
Deployment Tips
Use AWS SAM, AWS CDK, or Terraform instead of creating resources manually.
Infrastructure as code gives you:
- Repeatable deployments.
- Version-controlled infrastructure.
- Easier rollback.
- Consistent environments for development, staging, and production.
Final Thoughts
A serverless API on AWS can be simple to start and powerful in production when you design for security, observability, and cost from day one.
Start with a narrow set of endpoints, define your DynamoDB access patterns early, and automate deployment. That foundation will make it much easier to grow the application later.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article