Sub topic 12
Custom aliases and expiring links
This chapter adds two features to the shortener's core path: user-chosen aliases and links that stop working at a set time. Both look small, but they add edge cases to code generation, the data model, caching, and redirects.
You should already know the urls table with its short_code primary key, the collision handling from earlier chapters, cache-aside reads, and the difference between 301 and 302 redirects.
Why these features are harder than they look
Generated codes are chosen by the system, so the system controls their shape and can retry on a collision. A custom alias is chosen by a user, so you inherit three new problems:
- The user controls the input, so you have to validate it.
- Aliases compete for a shared namespace, so two users can want the same one.
- The alias may collide with a code you generate later.
Expiry adds a time dimension. A row that was valid when written becomes invalid without anyone touching it. Every layer that remembers the row (the database, the cache, and the user's browser) must forget it at about the right moment.
Custom aliases
The API shape
Extend the create endpoint with an optional alias field and an optional expires_in_seconds field:
POST /api/links
{"long_url": "https://example.com/sale", "alias": "spring-sale", "expires_in_seconds": 3600}The status codes are:
201 Createdon success.400 Bad Requestif the alias fails validation.409 Conflictif the alias is already taken.
Use 409 for a taken alias. The request is well formed, but it conflicts with the current state of the system. A client can react to 409 by offering a different alias.
Validating the alias
Aliases need rules because they appear in URLs and are typed by humans. A reasonable policy is:
- Character set: letters, digits, hyphen, and underscore only. This avoids URL-encoding surprises and lookalike Unicode characters.
- Length: 3 to 32 characters. Very short aliases are scarce and attractive to squatters. Very long ones defeat the purpose of a short link.
- Reserved words: reject names that your own routes use, such as
api,admin,login, andstatic. Otherwise/admincould be hijacked by a user, or your own route could shadow their link. - Case: generated base62 codes are case-sensitive. For custom aliases, consider treating
Saleandsaleas the same alias. Otherwise someone can register a near-duplicate of another person's link and impersonate it.
Claim the alias atomically
The most common bug is check-then-insert:
# Wrong: two requests can both pass the check.
if not exists(alias):
insert(alias, long_url)Two concurrent requests can both see "not taken" and then both insert. One insert overwrites the other, or both succeed in a store without a uniqueness guarantee. The fix is to let the database decide. The PRIMARY KEY on short_code rejects the second insert, and your code translates that error into a 409. This is the same mechanism that detects collisions for generated codes.
Alias and generated-code namespaces
Custom aliases and generated codes share one table, so they share one namespace. A custom alias like abc1234 can block a code your counter produces later. There are three ways to handle this:
| Approach | How it works | Trade-off |
|---|---|---|
| Retry on conflict | If a generated code hits an existing row, generate the next one | Simple. The cost is one extra insert, and it is rare. |
| Length separation | Generated codes are always 7 characters. Custom aliases must differ in length, for example 8 to 32 | No overlap, but it restricts aliases. |
| Prefix or separate table | Aliases live in their own table or have a marker | Clean separation, but the redirect path now checks two places. |
Retry on conflict is usually enough, because it reuses the collision logic you already have.
Expiring links
Storing expiry
The expires_at column from the data model chapter is already nullable. NULL means the link never expires. Store timestamps in UTC and compare them using one clock source, preferably the application server's clock passed in explicitly, as the code below does. This also makes the logic testable.
Lazy expiry versus active cleanup
You do not need a job that flips a flag the instant a link expires. Combine two mechanisms:
- Lazy check on read. The resolver compares
expires_atwith the current time. If the time has passed, it treats the link as expired, even though the row still exists. This is exact and costs one comparison. - Background purge. A periodic job deletes expired rows in small batches. This reclaims storage and frees the codes. It does not need to be punctual, because the lazy check already guarantees correctness.
Delete in batches (for example 1,000 rows per statement) so one purge does not hold locks for long or flood replicas with a huge transaction. An index on expires_at keeps the purge from scanning the whole table.
What to return for an expired link
Return 410 Gone for a link that is known to have expired. It tells clients and crawlers the resource existed and is intentionally gone. Return 404 Not Found for a code that does not exist. After the purge deletes the row, the same code becomes a 404. This is acceptable, but if you need a permanent 410 you must keep a tombstone row.
Example implementation
This runnable example uses SQLite. It claims aliases atomically, checks expiry lazily, computes a cache TTL, and purges in batches.
import re
import sqlite3
from datetime import datetime, timedelta, timezone
ALIAS_RE = re.compile(r"^[A-Za-z0-9_-]{3,32}$")
RESERVED = {"api", "admin", "login", "static", "health"}
SCHEMA = """
CREATE TABLE urls (
short_code TEXT PRIMARY KEY,
long_url TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT NULL
);
CREATE INDEX idx_urls_expires_at ON urls (expires_at);
"""
class InvalidAlias(Exception):
pass
class AliasTaken(Exception):
pass
def create_custom(db, alias, long_url, now, ttl=None):
if not ALIAS_RE.match(alias) or alias.lower() in RESERVED:
raise InvalidAlias(alias)
expires_at = (now + ttl).isoformat() if ttl else None
try:
with db:
db.execute(
"INSERT INTO urls (short_code, long_url, created_at, expires_at) "
"VALUES (?, ?, ?, ?)",
(alias, long_url, now.isoformat(), expires_at),
)
except sqlite3.IntegrityError:
raise AliasTaken(alias)
def resolve(db, code, now):
row = db.execute(
"SELECT long_url, expires_at FROM urls WHERE short_code = ?", (code,)
).fetchone()
if row is None:
return 404, None
long_url, expires_at = row
if expires_at is not None and datetime.fromisoformat(expires_at) <= now:
return 410, None
return 302, long_url
def cache_ttl(expires_at, now, default=3600):
if expires_at is None:
return default
remaining = int((expires_at - now).total_seconds())
return max(0, min(default, remaining))
def purge_expired(db, now, batch=1000):
total = 0
while True:
with db:
cur = db.execute(
"DELETE FROM urls WHERE rowid IN ("
"SELECT rowid FROM urls "
"WHERE expires_at IS NOT NULL AND expires_at <= ? LIMIT ?)",
(now.isoformat(), batch),
)
total += cur.rowcount
if cur.rowcount < batch:
return total
if __name__ == "__main__":
db = sqlite3.connect(":memory:")
db.executescript(SCHEMA)
t0 = datetime(2026, 11, 26, 10, 0, tzinfo=timezone.utc)
create_custom(db, "spring-sale", "https://example.com/sale", t0, timedelta(hours=1))
print(resolve(db, "spring-sale", t0)) # (302, 'https://example.com/sale')
print(resolve(db, "spring-sale", t0 + timedelta(hours=2))) # (410, None)
try:
create_custom(db, "spring-sale", "https://example.com/other", t0)
except AliasTaken:
print("alias still taken until purged")
print(purge_expired(db, t0 + timedelta(hours=2))) # 1
create_custom(db, "spring-sale", "https://example.com/other", t0 + timedelta(hours=2))
print(resolve(db, "spring-sale", t0 + timedelta(hours=2))) # (302, 'https://example.com/other')Note that create_custom never calls a separate "exists" query. The insert is the check.
The resolve flow
Expiry and the cache
A cache hit skips the expiry check in the diagram above, so the cache entry must not outlive the link. Set the cache TTL to the smaller of your normal TTL and the time remaining until expires_at, as cache_ttl does. Without this, a link that expired a minute ago keeps redirecting until the cache entry ages out.
Two related points:
- Negative caching. You can cache 404 and 410 answers for a short time (30 to 60 seconds) to protect the database from repeated requests for dead codes. Keep the time short so a newly created alias becomes visible quickly.
- Extending a link. If a user extends an expiry, you must delete or update the cache entry. Otherwise the old, shorter TTL still applies.
Expiry and redirect semantics
A 301 is cached by browsers, often indefinitely. A browser that has followed a 301 once may go straight to the destination and never ask your server again, so your expiry has no effect for that user. For links with an expiry, use 302 (or 307), possibly with a short Cache-Control: max-age no longer than the remaining lifetime.
Common errors
- Check-then-insert for aliases, which allows duplicate claims under concurrency.
- Forgetting reserved words, so a user shadows
/apior/login. - Cache TTL longer than the link's remaining life, so expired links keep working.
- Using 301 on expiring links, so browsers never see the expiry.
- Purging with one huge
DELETE, which stalls the database and lags replicas. - Comparing local times or mixed formats, so expiry fires hours early or late.
- Letting aliases claim the whole short namespace, with no per-user limits. Apply the rate limits from the abuse chapter.
Exercise
A user creates the alias promo with a one-hour expiry. Your cache TTL is normally 24 hours. Describe what goes wrong if you cache the entry with the default TTL, and give the TTL you should use when 20 minutes of the hour remain.
Show answer
The cache entry would live for 24 hours, so promo would keep redirecting for up to 23 hours after it expired, because cache hits skip the expiry check. Use the smaller of the default TTL and the remaining lifetime. With 20 minutes left that is 1,200 seconds.
Exercise
Two requests try to claim the alias launch at the same moment. Explain why a "SELECT, then INSERT if empty" approach is unsafe, and what the database-level fix is.
Show answer
Both requests can run the SELECT before either INSERT happens, so both see no row and both try to insert. Without a uniqueness guarantee, both appear to succeed. The fix is to rely on the PRIMARY KEY on short_code. Run only the INSERT, and when the database raises a uniqueness violation, return 409 Conflict to the loser.