Sub topic 12
Custom aliases and expiring links
This chapter assumes you know the urls table from the data model chapter, the collision handling idea (a primary key rejects duplicates), and the cache-aside read path. It adds two features to the core design: user-chosen short codes and links that stop working at a set time.
Custom aliases
A custom alias is a short code the user picks, such as sale-2026, instead of one the system generates. It is stored in the same short_code column. That gives you one lookup path for both kinds of code, but it also means they share a namespace.
Three rules keep this safe:
- Validate the format. Allow only letters, digits,
-and_, within the column length (10 characters in our schema). - Reserve system words. Block names like
apioradminso they never clash with your own routes. - Let the database decide uniqueness. Do not check first and insert second, because two requests can pass the check at the same moment. Insert and catch the duplicate-key error. Return
409 Conflictto the caller.
Expiring links
The expires_at column is NULL for links that never expire. Otherwise it holds a UTC timestamp. Expiry has two parts: a check on every read, and a cleanup job.
- Check on read. The resolver compares
expires_atwith the current time. An expired link returns404 Not Found, or410 Goneif you want to say the link existed once. - Cleanup job. A periodic job deletes rows whose
expires_atis in the past. This frees space. It does not decide correctness, because the read check already hides expired rows. The job can run late without causing harm.
A runnable example
This code uses SQLite so you can run it as is.
import re
import sqlite3
from datetime import datetime, timedelta, timezone
ALIAS_RE = re.compile(r"^[A-Za-z0-9_-]{4,10}$")
RESERVED = {"api", "admin", "login", "static"}
db = sqlite3.connect(":memory:")
db.execute("""CREATE TABLE urls (
short_code VARCHAR(10) PRIMARY KEY,
long_url TEXT NOT NULL,
expires_at TEXT NULL)""")
def now() -> datetime:
return datetime.now(timezone.utc)
def create_alias(alias, long_url, ttl_days=None):
if not ALIAS_RE.match(alias) or alias.lower() in RESERVED:
return "400 invalid alias"
expires = None
if ttl_days is not None:
expires = (now() + timedelta(days=ttl_days)).isoformat()
try:
db.execute("INSERT INTO urls VALUES (?, ?, ?)",
(alias, long_url, expires))
except sqlite3.IntegrityError:
return "409 alias taken"
return "201 created"
def resolve(code):
row = db.execute("SELECT long_url, expires_at FROM urls "
"WHERE short_code = ?", (code,)).fetchone()
if row is None:
return None
long_url, expires_at = row
if expires_at and datetime.fromisoformat(expires_at) <= now():
return None
return long_url
print(create_alias("sale-2026", "https://example.com/sale", ttl_days=7))
print(create_alias("sale-2026", "https://example.com/other"))
print(resolve("sale-2026"))The second call prints 409 alias taken, because the primary key rejects the duplicate.
Expiry and the cache
A cache can serve a link after it has expired. If resolve stores a URL in the cache with a 24-hour TTL, but the link expires in one hour, users keep getting redirected for 23 more hours. Set the cache TTL to the smaller of your default TTL and the time remaining until expires_at.
Common errors
- Checking whether an alias exists before inserting it. This creates a race condition.
- Relying on the cleanup job alone, which lets expired links keep working until it runs.
- Reusing an expired code for a new URL while old caches or bookmarks still point to it. Wait a grace period before releasing codes.
- Comparing timestamps in local time. Store and compare in UTC.
Exercise
A link expires at 10:00. At 09:59 a request caches it with a fixed one-hour TTL. At 10:30 the link still redirects. What went wrong, and what is the fix?
Show answer
The cache TTL was longer than the link's remaining lifetime, so the cached entry outlived the expiry. Set the TTL to min(default TTL, expires_at minus now). That would be 60 seconds here.