
Build A Serverless URL Shortener on AWS
Learn to build a production-ready serverless URL shortener with Terraform, Lambda, DynamoDB, SQS, and CloudFront, including async click analytics, client-side QR codes, API rate limiting, and a budget-conscious deployment path.
How The Application Works:
The web interface lets a visitor enter a destination URL, optionally choose a custom slug, and create a short link. The result includes a copy button, a QR code with PNG download, an expiration timestamp, and a click count that can be refreshed.
The application supports:
- Generated or custom slugs: generated slugs use seven letters and digits; custom slugs accept 3–32 letters, digits, underscores, or hyphens.
- Link expiration: links default to three days. API clients can request a duration between 1 and 365 days.
- HTTP redirects: valid links return
302with the destination in theLocationheader.
- Click counts: redirect events go through SQS before a separate Lambda updates DynamoDB.
- Browser-generated QR codes: the frontend encodes the short URL locally, without a QR generation API.
- An open demo API: a DynamoDB-backed limiter attempts to restrict creation to five requests per IP per minute by default.
- Optional custom domain configuration: Route 53 and ACM support a custom HTTPS address.

Architecture Deep Dive:
Six AWS services form the main application: CloudFront, S3, API Gateway, Lambda, DynamoDB, and SQS.
Each has a specific job. CloudFront delivers the application over HTTPS. S3 holds the static frontend. API Gateway routes application requests to Python Lambda handlers. DynamoDB stores links and rate-limit records. SQS carries click events to a separate consumer. CloudWatch supplies logs and a click-tracker error alarm alongside that core flow.
Terraform defines the infrastructure in modules, with a separate bootstrap stack for its state bucket. That gives readers both application code to explore and infrastructure they can reproduce.
Component | Responsibility |
|---|---|
Amazon CloudFront | HTTPS delivery, path routing, and caching |
Amazon S3 | Static HTML, CSS, JavaScript, and the vendored QR library |
Amazon API Gateway HTTP API | Routes requests to the appropriate Lambda |
AWS Lambda | Link creation, redirects, metadata retrieval, and click processing |
Amazon DynamoDB | Link records and per-IP rate-limit records |
Amazon SQS | Click-event queue and dead-letter queue |
Amazon CloudWatch | Lambda logs and a click-tracker error alarm |
Terraform bootstrap stack | Separate S3 bucket for application infrastructure state |
CloudFront gives users one address for the UI, API, and short links. The API Gateway endpoint also remains directly accessible, so CloudFront is the intended user entry point rather than an enforced exclusive boundary.

The Terrafrom Code for the Project is available in a GitHub repository for you to try. Repository link is available in the article below.
Routing Static files and short links:
Path routing matters because
/assets/app.js and /my-link need very different destinations.Request path | Destination | Cache behavior |
|---|---|---|
/ | S3, with index.html as the default root object | Static content |
/assets/* | S3 | Static content |
/index.html | S3 | Static content |
/api/* | API Gateway | Caching disabled |
/health | API Gateway | Caching disabled |
/{slug} through the final /* behavior | API Gateway | Redirect caching enabled |

CloudFront evaluates ordered cache behaviors in sequence, making the position of the catch-all important. Specific static and API patterns appear before
/* . AWS explains this matching behavior in its CloudFront cache behavior documentation .
The frontend bucket blocks public access. CloudFront reads its objects through (OAC) Origin Access Control, with a bucket policy scoped to the distribution.
Four small Lambda functions:
The code separates the application into four handlers:
Function | Trigger | Work performed |
|---|---|---|
create_link | POST /api/links | Validate input and store a new link |
redirect | GET /{slug} , HEAD /{slug} , or /health | Resolve a link or return health status |
get_analytics | GET /api/links/{slug} | Return link metadata and click count |
click_tracker | SQS event source mapping | Increment click counts |
Shared validation, configuration, rate-limit, and response helpers are copied into each deployment package. This keeps each function self-contained without introducing a Lambda layer.
Request Workflow Explained:
Creating a short link
The browser sends
POST /api/links through CloudFront and API Gateway to the create_link Lambda. The handler checks the demo rate limiter, validates the URL and slug, and stores the link in DynamoDB.Field | Purpose |
|---|---|
slug | Partition key and short-link identifier |
long_url | Destination URL |
created_at | Creation timestamp |
expires_at | Expiration time in Unix seconds |
click_count | Starts at zero |
is_active | Starts as true |
A conditional write prevents existing slugs from being overwritten; duplicates return
409 Conflict . The API returns the short URL, which the frontend displays and uses to generate a QR code.2. Resolving a short link
The
redirect Lambda looks up the slug and checks whether the link is active and unexpired. Missing or inactive links return 404 ; expired links return 410 .For a valid link, the handler sends a click event to SQS and returns a
302 redirect. It waits for SQS to accept the event before returning. The handler enforces expiration, while DynamoDB TTL removes expired records asynchronously.3. Updating click counts
SQS triggers
click_tracker in batches of up to ten messages. The consumer atomically increments each link’s counter in DynamoDB. Failed messages are retried and can move to a dead-letter queue. Counts may take a moment to update.The count represents processed redirect events, rather than exact visits or unique visitors: cached redirects can bypass tracking,
HEAD requests can generate events, and retries can produce duplicate increments.Here is the complete Request Workflow:

Build and Deploy the Serverless URL Shortener:
The entire Terraform and Python Code for the Project is available in a GitHub Repository:
The commands below create billable resources in your AWS account.
Prerequisites:
- AWS account with credentials configured
- Terraform >= 1.10 (required for S3 native state lockfile)
- Python 3.12+
-
make,zip
In order to deploy resources easily we will use Makefiles.
Make is a classic command-line utility used to automate repetitive tasks, manage dependencies, and provide a standardized way to build, test, and deploy software using configuration files. You can use Terraform commands if you are more familiar with them. Detailed instructions are in the repository.
Clone the repo and run the following commands from the root folder.
1. Bootstrap Terraform remote state S3 Bucket (one time)
make bootstrap-apply
A random hex suffix is appended to the state bucket prefix.
make bootstrap-apply writes gitignored terraform/backend.hcl , then:
cd terraformterraform init -backend-config=backend.hcl2. Build Lambda packages
make buildmake test3. Deploy Infrastructure
cp terraform/terraform.tfvars.example terraform/terraform.tfvarsmake infra-apply
Note the
app_url in the Terrafrom outputs. That is your public shortener URL.4. Try it
Open
app_url , paste a long URL, click Shorten. The result panel will show the short link, click stats, and a QR code (with PNG download).Cost and Cleanup
The application uses on-demand DynamoDB capacity, small Lambda functions, static S3 content, and an SQS consumer that receives messages in batches. Batching reduces consumer invocation overhead; the handler still performs one DynamoDB update per event.
Actual cost depends on requests, Lambda duration, data transfer, storage, logging, region, and account-specific credits. Optional DNS hosting and WAF add costs. Estimate your expected traffic with the AWS Pricing Calculator instead of treating a demo estimate as a guaranteed monthly bill.
When you finish experimenting, destroy the application stack first with
make infra-destroy before removing its state bucket:# From the repository root; review each interactive prompt.make infra-destroymake bootstrap-destroy
The bootstrap destroy target requires an explicit confirmation phrase and enables removal of the bucket's contents. Keep the backend configuration and state available until the application destroy succeeds.
What this Project teaches:
A Serverless URL shortener brings several useful AWS patterns into one application: serving a private static frontend through CloudFront, routing an HTTP API to focused functions, protecting writes with DynamoDB conditions, and moving downstream processing through a queue.
It also makes the tradeoffs visible. Caching affects both analytics and expiration. A queued counter is eventually updated, and retries require idempotency if counts must be exact. TTL simplifies cleanup while leaving the application responsible for enforcing expiration. Terraform makes the infrastructure repeatable, while the separate bootstrap stack introduces its own state lifecycle to manage.
For the AWS Community Builders community, these details are useful discussion points as well as opportunities to extend the project. Try deploying the demo, follow a request through the services, and consider which change you would make first: stronger rate limiting, more accurate analytics, or automated deployment checks.
Thank you
Hope you all enjoyed the article! Keep Building, and keep sharing!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article