If you followed my 4-Week AWS Serverless Roadmap, this is the exact Week 1–4 capstone project: a production-style URL shortener (like Bitly) built with zero servers to manage.
By the end of this walkthrough, you will have:
- A DynamoDB table with automatic link expiration (TTL)
- Two AWS Lambda functions (
shortenandredirect) - An Amazon API Gateway HTTP API
- A static frontend hosted on Amazon S3 + CloudFront
- An EventBridge scheduled job for nightly analytics/cleanup
- Everything packaged as Infrastructure as Code with AWS SAM
How every piece of the URL shortener connects with zero servers managed.
Step 1: Design the DynamoDB Table
For a URL shortener, our access patterns are simple:
- Create a short code for a long URL (
PutItem). - Look up the long URL by
shortCode(GetItem). - Automatically delete expired links using DynamoDB Time to Live (TTL).
In on-demand capacity mode, DynamoDB bills per read/write request—ideal for spiky or student traffic.
- Table name:
UrlShortenerTable - Partition key:
shortCode(String) - Attributes:
longUrl(String),createdAt(String),expiresAt(Number — Unix epoch seconds for TTL)
Step 2: Write the Lambda Functions (Node.js 20)
1. shorten.mjs — Create a Short Link
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import crypto from "node:crypto";
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const TABLE = process.env.TABLE_NAME;
export const handler = async (event) => {
const body = JSON.parse(event.body || "{}");
const longUrl = body.url?.trim();
if (!longUrl || !/^https?:\/\//i.test(longUrl)) {
return { statusCode: 400, body: JSON.stringify({ error: "Valid http/https URL required" }) };
}
const shortCode = crypto.randomBytes(4).toString("base64url");
const expiresAt = Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60; // 30 days
await ddb.send(
new PutCommand({
TableName: TABLE,
Item: { shortCode, longUrl, createdAt: new Date().toISOString(), expiresAt },
ConditionExpression: "attribute_not_exists(shortCode)",
})
);
return {
statusCode: 201,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ shortCode, longUrl, expiresAt }),
};
};2. redirect.mjs — Redirect Visitors
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb";
const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const TABLE = process.env.TABLE_NAME;
export const handler = async (event) => {
const shortCode = event.pathParameters?.code;
if (!shortCode) return { statusCode: 400, body: "Missing code" };
const { Item } = await ddb.send(
new GetCommand({ TableName: TABLE, Key: { shortCode } })
);
if (!Item) {
return { statusCode: 404, body: "Short link not found or expired" };
}
return {
statusCode: 302,
headers: { Location: Item.longUrl, "Cache-Control": "no-store" },
body: "",
};
};Step 3: Wire Everything with AWS SAM (template.yaml)
Instead of clicking through the AWS Console, define the API Gateway, Lambda functions, IAM permissions, DynamoDB table, and EventBridge schedule in one template.yaml:
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: nodejs20.x
Timeout: 5
MemorySize: 256
Environment:
Variables:
TABLE_NAME: !Ref LinksTable
Resources:
LinksTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: shortCode
AttributeType: S
KeySchema:
- AttributeName: shortCode
KeyType: HASH
TimeToLiveSpecification:
AttributeName: expiresAt
Enabled: true
ShortenFunction:
Type: AWS::Serverless::Function
Properties:
Handler: shorten.handler
Policies:
- DynamoDBWritePolicy:
TableName: !Ref LinksTable
Events:
ShortenApi:
Type: HttpApi
Properties:
Path: /shorten
Method: POST
RedirectFunction:
Type: AWS::Serverless::Function
Properties:
Handler: redirect.handler
Policies:
- DynamoDBReadPolicy:
TableName: !Ref LinksTable
Events:
RedirectApi:
Type: HttpApi
Properties:
Path: /{code}
Method: GETDeploy the backend in two commands:
sam build
sam deploy --guidedStep 4: Add the Frontend & Nightly EventBridge Job
- Frontend on S3 + CloudFront: Put a simple
index.htmlform in a private S3 bucket and serve it through CloudFront with Origin Access Control (OAC). See Host a Frontend on S3 + CloudFront and Connect It to API Gateway for the exact CORS and OAC setup. - Nightly EventBridge Cleanup / Summary: DynamoDB TTL automatically deletes expired items within ~48 hours, and you can pair it with an EventBridge rule (
cron(0 2 * * ? *)) that triggers a Lambda at 2 AM UTC to log daily link counts or archive expired records to S3.
Step 5: Cost & Security Checklist
- Least-privilege IAM:
ShortenFunctiononly getsDynamoDBWritePolicy;RedirectFunctiononly getsDynamoDBReadPolicy. - Rate limiting: Enable throttling on API Gateway so nobody spams
POST /shorten. - Billing alert: Set a $5 AWS Budgets alert before testing.
- Test locally first: Use AWS SAM CLI local testing before deploying changes.
Found this useful?
Share it with your group