Building a Serverless URL Shortener with Amazon API Gateway, AWS Lambda, and DynamoDB
Learn how to build a simple, scalable URL shortener using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB, while applying serverless design principles and least-privilege IAM permissions.
Building a Serverless URL Shortener with Amazon API Gateway, AWS Lambda, and DynamoDB
A URL shortener is a small project, but it is a great way to understand several important AWS concepts: API design, serverless compute, NoSQL data modeling, IAM permissions, and scalable architectures.
In this tutorial, we'll build a simple URL-shortening service using:
- Amazon API Gateway — exposes HTTP endpoints.
- AWS Lambda — processes requests without managing servers.
- Amazon DynamoDB — stores the URL mappings.
- AWS IAM — controls access between services.
Architecture
The application will follow this flow:
Client | | HTTP Request vAmazon API Gateway | vAWS Lambda | vAmazon DynamoDBWhen a user submits a long URL, Lambda generates a short identifier and stores the mapping in DynamoDB.
When someone accesses the short URL, Lambda retrieves the original URL and returns it.
1. Create the DynamoDB Table
Create a DynamoDB table called:
UrlMappingsUse:
Partition key: shortCodeType: StringA record can look like:
{ "shortCode": "aB91x", "url": "https://example.com/some/long/path", "createdAt": "2026-08-29T10:00:00Z"}The
shortCode becomes the unique identifier for each shortened URL.
2. Create the Lambda Function
Create a Lambda function using Python.
The function will accept a URL, generate a short code, and store the mapping.
Example:
import jsonimport randomimport stringimport boto3
table = boto3.resource("dynamodb").Table("UrlMappings")
def generate_code(length=6): characters = string.ascii_letters + string.digits return "".join(random.choice(characters) for _ in range(length))
def lambda_handler(event, context): body = json.loads(event.get("body", "{}")) url = body.get("url")
if not url: return { "statusCode": 400, "body": json.dumps({"error": "URL is required"}) }
short_code = generate_code()
table.put_item( Item={ "shortCode": short_code, "url": url } )
return { "statusCode": 201, "body": json.dumps({ "shortCode": short_code }) }For production workloads, the short-code generation and collision handling should be made more robust.
3. Configure IAM Permissions
The Lambda execution role should have only the permissions required by the function.
For this example, Lambda needs permission to write to the DynamoDB table.
A narrowly scoped policy is preferable to granting broad DynamoDB access.
Conceptually, the permission should look like:
Lambda | | PutItem vUrlMappingsFollowing the principle of least privilege reduces the potential impact if application credentials or execution environments are compromised.
4. Create the API
Create an HTTP API using Amazon API Gateway.
Add an endpoint such as:
POST /shortenConnect the endpoint to the Lambda function.
A client can then send:
{ "url": "https://example.com/articles/aws-serverless"}The API can return:
{ "shortCode": "aB91x"}
5. Implement URL Retrieval
Now we need another endpoint:
GET /{shortCode}The request is sent to Lambda, which retrieves the corresponding DynamoDB item.
The basic flow becomes:
GET /aB91x | vAPI Gateway | vLambda | vDynamoDB | vOriginal URLThe application can then return an HTTP redirect to the original URL.
6. Think About Production Requirements
The basic implementation is intentionally simple. A production URL-shortening service would need additional considerations.
Validation
Validate URLs before storing them.
For example:
- Ensure the URL uses an allowed protocol.
- Reject malformed URLs.
- Consider limiting URL length.
Collision Handling
Randomly generated codes can theoretically collide.
The application should detect an existing
shortCode and generate another code when necessary.Expiration
Some shortened URLs may only need to exist for a limited period.
DynamoDB Time to Live (TTL) can be considered for automatically expiring records.
Rate Limiting
Public endpoints should not accept unlimited requests.
API Gateway throttling and additional application-level controls can help protect the service.
Monitoring
Amazon CloudWatch can be used to monitor Lambda execution, errors, latency, and API activity.
Useful metrics can help answer questions such as:
- How many URLs are being created?
- How many requests are failing?
- How much latency does the API introduce?
- Are Lambda invocations increasing unexpectedly?
7. Why Serverless Works Well Here
This application is a good candidate for serverless architecture because URL-shortening traffic can vary significantly.
With Lambda, compute capacity can scale with incoming requests without requiring us to manage traditional application servers.
DynamoDB also provides a managed NoSQL database that can scale without requiring database-server management.
The resulting architecture has very little infrastructure to operate:
┌─────────────────┐ │ Client │ └────────┬────────┘ │ v ┌─────────────────┐ │ API Gateway │ └────────┬────────┘ │ v ┌─────────────────┐ │ AWS Lambda │ └────────┬────────┘ │ v ┌─────────────────┐ │ DynamoDB │ └─────────────────┘
Conclusion
A URL shortener may look like a simple application, but it demonstrates several important AWS concepts.
The project provides practical experience with:
- Amazon API Gateway
- AWS Lambda
- Amazon DynamoDB
- IAM
- Serverless architecture
- API design
- Monitoring
- Scalability
- Least-privilege security
The most important lesson is that serverless architecture is not just about avoiding servers. It is about choosing managed building blocks that allow you to focus more on application behavior and less on infrastructure management.
Once the basic version works, you can extend it with authentication, custom aliases, expiration, analytics, caching, rate limiting, and a frontend.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article