Project 2: Build a Serverless Web Application with S3, API Gateway, Lambda, DynamoDB and Cognito

AWS Solutions Architect 60 min min read Updated: Nov 17, 2026 Intermediate
Project 2: Build a Serverless Web Application with S3, API Gateway, Lambda, DynamoDB and Cognito
Intermediate Topic 2 of 3

Goal and Architecture

Build a to-do application where users sign in, then create, list and complete their own tasks. There are no servers to patch, it scales automatically and costs almost nothing when idle.

text Browser ─► CloudFront ─► S3 (HTML/JS) ← static front end β”‚ β”œβ”€β–Ί Cognito User Pool (sign up / sign in) β†’ JWT token β”‚ └─► API Gateway (HTTP API) + JWT authorizer β”œβ”€ POST /tasks β†’ Lambda createTask ─┐ β”œβ”€ GET /tasks β†’ Lambda listTasks ─┼─► DynamoDB (PK = userId, SK = taskId) └─ PUT /tasks/{id} β†’ Lambda completeTaskβ”˜ DynamoDB Streams / EventBridge β†’ Lambda notify (optional)

Data Model (Single Table)

AttributeRoleExample
userIdPartition keythe Cognito sub value
taskIdSort keyULID or timestamp-based id (sorted by time)
title, done, createdAtAttributesBuy milk, false, 2026-11-17T10:00:00Z

A **query on userId returns only that user's tasks, fast and cheap. Use on-demand capacity** for unpredictable traffic.

Step 1: Install SAM and Create the Project

bash pip install aws-sam-cli # or use the installer from AWS docs sam --version mkdir todo && cd todo mkdir src

Step 2: The SAM Template

yaml AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: Serverless to-do application Globals: Function: Runtime: python3.12 Architectures: [arm64] Timeout: 10 MemorySize: 256 Environment: Variables: TABLE: !Ref TasksTable Resources: TasksTable: Type: AWS::DynamoDB::Table Properties: BillingMode: PAY_PER_REQUEST AttributeDefinitions: - {AttributeName: userId, AttributeType: S} - {AttributeName: taskId, AttributeType: S} KeySchema: - {AttributeName: userId, KeyType: HASH} - {AttributeName: taskId, KeyType: RANGE} PointInTimeRecoverySpecification: {PointInTimeRecoveryEnabled: true} SSESpecification: {SSEEnabled: true} UserPool: Type: AWS::Cognito::UserPool Properties: AutoVerifiedAttributes: [email] UsernameAttributes: [email] Policies: PasswordPolicy: {MinimumLength: 10} UserPoolClient: Type: AWS::Cognito::UserPoolClient Properties: UserPoolId: !Ref UserPool GenerateSecret: false ExplicitAuthFlows: [ALLOW_USER_SRP_AUTH, ALLOW_REFRESH_TOKEN_AUTH] Api: Type: AWS::Serverless::HttpApi Properties: Auth: DefaultAuthorizer: JwtAuth Authorizers: JwtAuth: JwtConfiguration: issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool} audience: [!Ref UserPoolClient] IdentitySource: $request.header.Authorization CorsConfiguration: AllowOrigins: ['https://todo.example.com'] AllowHeaders: [Authorization, Content-Type] AllowMethods: [GET, POST, PUT, OPTIONS] CreateTask: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.create_task Policies: [DynamoDBWritePolicy: {TableName: !Ref TasksTable}] Events: Post: {Type: HttpApi, Properties: {ApiId: !Ref Api, Path: /tasks, Method: POST}} ListTasks: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.list_tasks Policies: [DynamoDBReadPolicy: {TableName: !Ref TasksTable}] Events: Get: {Type: HttpApi, Properties: {ApiId: !Ref Api, Path: /tasks, Method: GET}} CompleteTask: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.complete_task Policies: [DynamoDBCrudPolicy: {TableName: !Ref TasksTable}] Events: Put: {Type: HttpApi, Properties: {ApiId: !Ref Api, Path: '/tasks/{id}', Method: PUT}} Outputs: ApiUrl: {Value: !Sub 'https://${Api}.execute-api.${AWS::Region}.amazonaws.com'} UserPoolId: {Value: !Ref UserPool} ClientId: {Value: !Ref UserPoolClient}
  • SAM policy templates (like DynamoDBReadPolicy) give least-privilege access to only that table
  • HTTP API is cheaper and faster than REST API, and supports JWT authorizers directly
  • arm64 (Graviton) reduces cost

Step 3: Lambda Code

python import json, os, time, uuid import boto3 from boto3.dynamodb.conditions import Key table = boto3.resource("dynamodb").Table(os.environ["TABLE"]) def _user(event): return event["requestContext"]["authorizer"]["jwt"]["claims"]["sub"] def _resp(code, body): return {"statusCode": code, "headers": {"Content-Type": "application/json"}, "body": json.dumps(body)} def create_task(event, context): data = json.loads(event.get("body") or "{}") title = (data.get("title") or "").strip() if not title or len(title) > 200: return _resp(400, {"error": "title is required (max 200 characters)"}) item = {"userId": _user(event), "taskId": f"{int(time.time()*1000)}-{uuid.uuid4().hex[:8]}", "title": title, "done": False} table.put_item(Item=item) return _resp(201, item) def list_tasks(event, context): r = table.query(KeyConditionExpression=Key("userId").eq(_user(event)), Limit=100) return _resp(200, r["Items"]) def complete_task(event, context): task_id = event["pathParameters"]["id"] try: table.update_item( Key={"userId": _user(event), "taskId": task_id}, UpdateExpression="SET done = :t", ConditionExpression="attribute_exists(taskId)", ExpressionAttributeValues={":t": True}) except table.meta.client.exceptions.ConditionalCheckFailedException: return _resp(404, {"error": "task not found"}) return _resp(200, {"taskId": task_id, "done": True})
  • The user id comes from the verified JWT, never from the request body, so users cannot read others' data
  • Validate input and use a condition expression to avoid creating phantom items
  • Create the boto3 client outside the handler so warm invocations reuse it

Step 4: Build, Deploy and Test

bash sam validate --lint sam build sam deploy --guided # stack name: todo-app, region, allow IAM role creation, save config # create a test user aws cognito-idp sign-up --client-id $CLIENT_ID --username me@example.com --password 'Str0ng!Passw0rd' aws cognito-idp admin-confirm-sign-up --user-pool-id $POOL_ID --username me@example.com # for command line tests, enable ALLOW_USER_PASSWORD_AUTH on the client temporarily TOKEN=$(aws cognito-idp initiate-auth --client-id $CLIENT_ID --auth-flow USER_PASSWORD_AUTH \ --auth-parameters USERNAME=me@example.com,PASSWORD='Str0ng!Passw0rd' --query AuthenticationResult.IdToken --output text) curl -s -X POST $API/tasks -H "Authorization: $TOKEN" -H 'Content-Type: application/json' -d '{"title":"Learn AWS"}' curl -s $API/tasks -H "Authorization: $TOKEN" curl -s -o /dev/null -w "%{http_code}\n" $API/tasks # no token β†’ 401
Result

{"userId":"a1b2...","taskId":"1763375000000-9f3c2d1a","title":"Learn AWS","done":false} 401

Local testing: sam local invoke and sam local start-api run functions in a container on your machine. Use sam logs --tail to follow CloudWatch logs and sam sync --watch for fast development deploys.

Step 5: Front End on S3 and CloudFront

  1. Create a private S3 bucket (Block Public Access on) for the static files
  2. Create a CloudFront distribution with Origin Access Control so only CloudFront can read the bucket
  3. Use Amplify Auth/JS libraries or amazon-cognito-identity-js to sign users in and call the API with the ID/access token
  4. Set the CloudFront default root object index.html, add an ACM certificate and a Route 53 alias
  5. Upload files with aws s3 sync ./site s3://todo-site --delete and invalidate the CDN cache when you change files

Step 6: Add an Event-Driven Feature

Send a reminder when a task is created, without slowing the API.

yaml TaskEvents: Type: AWS::SQS::Queue Properties: {VisibilityTimeout: 60, RedrivePolicy: {deadLetterTargetArn: !GetAtt TaskDlq.Arn, maxReceiveCount: 3}} TaskDlq: Type: AWS::SQS::Queue Notify: Type: AWS::Serverless::Function Properties: CodeUri: src/ Handler: app.notify Events: Queue: {Type: SQS, Properties: {Queue: !GetAtt TaskEvents.Arn, BatchSize: 5, FunctionResponseTypes: [ReportBatchItemFailures]}}
  • The API function sends a message to SQS and returns immediately
  • DLQ keeps poison messages for investigation
  • Partial batch failure reporting retries only failed messages
  • Make the consumer idempotent because delivery is at least once

Step 7: Operate It

AreaDo this
LogsCloudWatch Logs with retention set (for example 30 days). Use structured JSON logs
Metrics and alarmsLambda Errors, Throttles, API 5xx, DynamoDB throttles
TracingEnable X-Ray or Powertools for AWS Lambda tracer
SecurityWAF on CloudFront/API, least privilege roles, KMS-encrypted table, no secrets in code
CostBudget alert. Check free tier. Pay-per-request is cheap at small scale
LimitsSet reserved concurrency to protect the table from runaway traffic; use API throttling

Estimated Cost

At small scale (thousands of requests per day) Lambda, API Gateway, DynamoDB, S3 and Cognito are covered by or close to the free tier. Always check current pricing on the AWS pricing pages, as free tier terms change.

Cleanup

bash aws s3 rm s3://todo-site --recursive sam delete --stack-name todo-app

Practice Extensions

  1. Add a GSI to list tasks by done status
  2. Add a CI/CD pipeline with GitHub Actions or CodePipeline that runs sam build and sam deploy
  3. Add DynamoDB Streams β†’ EventBridge Pipes for audit events
  4. Add Cognito groups and an admin-only route
  5. Add canary deployments with SAM DeploymentPreference

Conclusion

A serverless app combines S3 and CloudFront for the front end, Cognito for sign-in, an HTTP API with a JWT authorizer, Lambda for logic and DynamoDB for data. Define everything in SAM, take the user id from the token, validate input, decouple extras with SQS, and watch errors, throttles and cost.

Quick Summary: architecture; data model; SAM template; Lambda code; deploy/test; front end; events; operations; cost; cleanup.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators