
Build a Self-Expiring URL Shortener on AWS with Lambda Function URLs and DynamoDB TTL
Create a serverless link shortener with no API Gateway and no servers, where links delete themselves automatically using DynamoDB TTL and collision-safe conditional writes.
Most URL shortener tutorials reach for API Gateway, a database, and a cleanup cron job. You can skip two of those. In this post, we'll build a shortener where links expire on their own and the whole thing is a single Lambda function plus one DynamoDB table.
What we're building
-
POST /with a long URL returns a short code
-
GET /{code}returns a 302 redirect to the original URL
- Links expire after 7 days, with no cleanup code needed
Architecture
Client -> Lambda Function URL -> Lambda (Python) -> DynamoDB (with TTL)A Lambda function URL gives your function a dedicated HTTPS endpoint, so there is no API Gateway to configure for a simple use case like this.
Step 1: Create the DynamoDB table
- Open the DynamoDB console and choose Create table.
- Table name:
short-links
- Partition key:
code(String)
- Capacity mode: On-demand
- After creation, open the table, go to Additional settings, and enable Time to Live (TTL) with the attribute name
expires_at.
TTL expects a Unix epoch timestamp in seconds. DynamoDB removes expired items in the background, typically within a few days of expiry. Because deletion is not instant, the code below also checks expiry on read.
Step 2: Write the Lambda function
Create a function with the Python 3.12 runtime and paste this in:
import json
import os
import secrets
import string
import time
from urllib.parse import urlparse
import boto3
from botocore.exceptions import ClientError
table = boto3.resource("dynamodb").Table(os.environ.get("TABLE_NAME", "short-links"))
ALPHABET = string.ascii_letters + string.digits
TTL_SECONDS = 7 * 24 * 60 * 60
def make_code(length=7):
return "".join(secrets.choice(ALPHABET) for _ in range(length))
def response(status, body=None, headers=None):
return {
"statusCode": status,
"headers": {"Content-Type": "application/json", **(headers or {})},
"body": json.dumps(body) if body is not None else "",
}
def create_link(event):
try:
url = json.loads(event.get("body") or "{}").get("url", "")
except json.JSONDecodeError:
return response(400, {"error": "Invalid JSON"})
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
return response(400, {"error": "Provide a valid http(s) URL"})
expires_at = int(time.time()) + TTL_SECONDS
# Retry on the rare chance of a code collision
for _ in range(5):
code = make_code()
try:
table.put_item(
Item={"code": code, "url": url, "expires_at": expires_at},
ConditionExpression="attribute_not_exists(code)",
)
return response(201, {"code": code, "expires_at": expires_at})
except ClientError as e:
if e.response["Error"]["Code"] != "ConditionalCheckFailedException":
raise
return response(500, {"error": "Could not allocate a code"})
def resolve_link(code):
item = table.get_item(Key={"code": code}).get("Item")
# TTL deletion is not instant, so check expiry ourselves too
if not item or int(item["expires_at"]) <= int(time.time()):
return response(404, {"error": "Link not found or expired"})
return {"statusCode": 302, "headers": {"Location": item["url"]}, "body": ""}
def lambda_handler(event, context):
method = event["requestContext"]["http"]["method"]
path = event.get("rawPath", "/")
if method == "POST" and path == "/":
return create_link(event)
if method == "GET" and len(path) > 1:
return resolve_link(path.lstrip("/"))
return response(404, {"error": "Not found"})Step 3: Give the function permission
Attach an IAM policy to the function's execution role, scoped to this one table:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["dynamodb:PutItem", "dynamodb:GetItem"],
"Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/short-links"
}
]
}Only these two actions are needed. Keeping the policy this narrow is good least-privilege practice.
Step 4: Enable the function URL
- In the Lambda console, open Configuration > Function URL.
- Choose Create function URL.
- For testing, set Auth type to
NONE. For anything real, useAWS_IAMor put CloudFront in front.
- Save, then copy the URL.
Step 5: Try it
# Create
curl -X POST https://YOUR-FUNCTION-URL/ \
-H "Content-Type: application/json" \
-d '{"url": "https://aws.amazon.com/lambda/"}'
# Response: {"code": "aB3xK9q", "expires_at": 1767225600}
# Resolve
curl -i https://YOUR-FUNCTION-URL/aB3xK9qThe second call should return
302 with a Location header pointing at the original URL.Why conditional writes matter
Random codes can collide. Without protection, a second
PutItem with the same code would silently overwrite the first link. The attribute_not_exists(code) condition makes the write fail instead, and the retry loop picks a new code. This is a cheap way to get safe uniqueness without a read-before-write.Production hardening checklist
- Rate limit creation, for example with AWS WAF behind CloudFront, since an open
POSTendpoint can be abused.
- Validate destinations if you accept public input, to avoid becoming a phishing relay.
- Add CloudWatch alarms on Lambda errors and throttles.
- Use a custom domain through CloudFront for shorter, branded links.
- Switch the auth type away from
NONEbefore sharing the endpoint widely.
Cost
With Lambda and on-demand DynamoDB, a low-traffic shortener typically costs pennies per month, and you pay nothing while it sits idle. Check the current AWS pricing pages for exact numbers in your Region.
Cleanup
Delete the Lambda function, its execution role, and the
short-links table when you're done experimenting.Wrap-up
A single Lambda function URL, one DynamoDB table, and TTL are enough for a useful shortener with automatic cleanup. A natural next step is adding click counters with DynamoDB atomic updates .
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article