Serverless is a cloud computing model where you don't manage servers directly. Instead, the cloud provider automatically handles server provisioning, scaling, and maintenance. You only pay for the actual compute time your code uses.
- No server management: No need to provision, configure, or maintain servers
- Auto-scaling: Automatically scales up or down based on demand
- Pay-per-use: Only pay for actual execution time
- High availability: Built-in redundancy and fault tolerance
- Faster development: Focus on code, not infrastructure
What is Lambda? AWS Lambda is a serverless compute service that runs your code in response to events. It automatically manages the compute resources for you.
How it works:
- You upload your code (Python, Node.js, Java, etc.)
- AWS Lambda runs your code when triggered
- You only pay for the compute time used
- Automatically scales from zero to thousands of concurrent executions
In our project:
- Runtime: Python 3.11
- Handler:
lambda_function.lambda_handler - Memory: 128 MB
- Timeout: 30 seconds
- Triggers: API Gateway HTTP requests
Code example:
def lambda_handler(event, context):
# Your business logic here
return {
'statusCode': 200,
'body': json.dumps({'message': 'Hello from Lambda!'})
}What is API Gateway? API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale.
How it works:
- Acts as a front door for your applications
- Handles HTTP requests and routes them to backend services
- Provides features like authentication, rate limiting, and monitoring
- Supports REST APIs and WebSocket APIs
In our project:
- Type: REST API
- Endpoints:
GET /tasks- List all tasksPOST /tasks- Create new taskDELETE /tasks/{id}- Delete specific task
- Integration: Lambda proxy integration
- Stage:
dev
Request flow:
HTTP Request → API Gateway → Lambda Function → DynamoDB
What is DynamoDB? DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.
How it works:
- NoSQL database (key-value and document store)
- Automatically scales up or down based on demand
- Built-in high availability and durability
- Pay-per-request pricing model
In our project:
- Table:
serverless-todo-api-tasks-dev - Primary Key:
id(String) - Billing Mode: Pay-per-request
- Operations: Create, Read, Delete tasks
Data structure:
{
"id": "uuid-here",
"title": "Task title",
"description": "Task description",
"completed": false,
"created_at": "2025-08-23T11:05:09.335843",
"updated_at": "2025-08-23T11:05:09.335843"
}What is IAM? IAM is a service that helps you securely control access to AWS resources. You can create and manage AWS users and groups, and use permissions to allow and deny their access to AWS resources.
How it works:
- Users: Individual AWS accounts
- Roles: Temporary permissions for services
- Policies: JSON documents that define permissions
- Principle of least privilege: Grant minimum necessary permissions
In our project:
- Lambda Execution Role: Allows Lambda to access DynamoDB
- DynamoDB Policy: Grants read/write permissions to the tasks table
- API Gateway Permissions: Allows API Gateway to invoke Lambda
User → API Gateway → Lambda → DynamoDB → Lambda → API Gateway → User
Step-by-step process:
-
User sends HTTP request to API Gateway
POST https://api-gateway-url/dev/tasks Content-Type: application/json {"title": "New Task", "description": "Task description"} -
API Gateway receives request and routes it to the appropriate Lambda function
-
Lambda function processes request
- Parses the HTTP method and path
- Validates input data
- Performs business logic
-
Lambda interacts with DynamoDB
- Creates, reads, or deletes data
- Handles database operations
-
Lambda returns response to API Gateway
-
API Gateway sends response back to user
Creating a Task:
-
User Request:
curl -X POST /tasks -d '{"title": "Learn AWS", "description": "Study serverless"}' -
API Gateway: Routes to Lambda function
-
Lambda Function:
# Parse request body = json.loads(event['body']) title = body['title'] # Create task in DynamoDB task_item = { 'id': str(uuid.uuid4()), 'title': title, 'completed': False, 'created_at': datetime.utcnow().isoformat() } table.put_item(Item=task_item)
-
DynamoDB: Stores the task
-
Response: Returns the created task to user
Lambda handles various error scenarios:
- Invalid JSON in request body
- Missing required fields
- DynamoDB connection issues
- Task not found (for delete operations)
Example error response:
{
"statusCode": 400,
"body": "{\"error\": \"Title is required\"}"
}Terraform is an open-source infrastructure as code tool that lets you define and provide data center infrastructure using a declarative configuration language.
- Define resources in
.tffiles - Plan changes with
terraform plan - Apply changes with
terraform apply - Destroy resources with
terraform destroy
main.tf: Provider configuration and backend setupvariables.tf: Input variables for customizationlambda.tf: Lambda function and IAM rolesapi_gateway.tf: API Gateway configurationdynamodb.tf: DynamoDB table definitionoutputs.tf: Output values (URLs, ARNs, etc.)
Lambda:
- Pay only for compute time (100ms increments)
- No charges when not in use
- Free tier: 1M requests per month
API Gateway:
- Pay per API call
- Free tier: 1M API calls per month
DynamoDB:
- Pay-per-request pricing
- No minimum capacity requirements
- Pay only for actual read/write operations
For a typical usage scenario:
- 1,000 API calls per day
- Average Lambda execution: 200ms
- 1,000 DynamoDB operations per day
Estimated monthly cost:
- Lambda: ~$0.50
- API Gateway: ~$0.30
- DynamoDB: ~$0.10
- Total: ~$0.90/month
- Least privilege principle: Only necessary permissions
- Lambda execution role: Minimal permissions for DynamoDB access
- No hardcoded credentials: Uses IAM roles
- HTTPS only: All endpoints use HTTPS
- CORS headers: Configured for web applications
- No authentication: Public API (can be enhanced with Cognito)
- Encryption at rest: Automatic encryption
- Encryption in transit: TLS encryption
- IAM-based access: No database passwords
Lambda:
- Scales from 0 to thousands of concurrent executions
- No manual scaling required
- Handles traffic spikes automatically
API Gateway:
- Handles millions of requests per second
- Global edge locations for low latency
- Automatic throttling and rate limiting
DynamoDB:
- Scales automatically based on demand
- No capacity planning required
- Consistent performance at any scale
- Cold start: ~100-200ms for first request
- Warm start: ~10-50ms for subsequent requests
- Database latency: ~1-10ms for DynamoDB operations
- Total response time: ~50-300ms typical
Lambda Logs:
- Automatic logging to CloudWatch
- Log group:
/aws/lambda/serverless-todo-api-dev - Structured logging with request/response data
API Gateway Metrics:
- Request count, latency, error rates
- 4xx and 5xx error tracking
- Integration with CloudWatch dashboards
DynamoDB Metrics:
- Read/write capacity utilization
- Throttled requests
- Error rates and latency
- Separation of Concerns: Each service has a specific responsibility
- Error Handling: Comprehensive error handling in Lambda
- Input Validation: Validates all user inputs
- Idempotency: Safe to retry operations
- Monitoring: Built-in logging and metrics
- Security: IAM roles and HTTPS
- Cost Optimization: Pay-per-request model
- Infrastructure as Code: Reproducible deployments
- Authentication: Add AWS Cognito for user management
- Caching: Add CloudFront for static content
- Monitoring: Enhanced CloudWatch dashboards
- CI/CD: Automated deployment pipeline
- Frontend: React/Vue.js web application
- Advanced Features: Task categories, search, filtering