URL Shortener (Scale & Build)

A URL shortener looks simple: store a long URL, return a short code, redirect. At scale, the hard parts are ID generation, redirect latency, cache correctness, and abuse. The redirect is a public, unauthenticated endpoint that anyone can hit, and it is the path that must keep working when everything else is degraded.

This chapter is written as a build runbook. It focuses on the flows, invariants, edge cases, and recovery steps. Code is optional; the decisions are not.

Scope

In scope for v1

  • POST /links with a long URL → short code.
  • GET /{code} → 301/302 redirect.
  • Custom aliases (optional).
  • Expiry and manual disable.
  • Click analytics (aggregate, not per-click real-time).
  • Basic abuse controls: rate limits, target validation, blocklists.

Out of scope for v1

  • Full analytics dashboards and funnels.
  • Teams, roles, billing, and per-seat permissions.
  • Malware scanning at scale (use a provider initially).
  • Internationalised short domains.
  • A public API with OAuth scopes.

Actors and journeys

Actor Goal What can go wrong
Creator Turn a long URL into a short one Collision, invalid URL, rate limit, duplicate create
Clicker Reach the destination quickly and safely Dead link, expired link, phishing, wrong target
Abuser Create many links or scan codes Resource exhaustion, reputation damage
Operator Keep redirects fast and safe Cache poisoning, database outage, hot link
Analyst Count clicks and referrers Lost events, bot traffic, double counting

The critical journey is click → redirect. Creating links is important, but it can degrade before redirects do.

Invariants

These must hold even during a partial failure:

  1. A code maps to at most one active destination. Codes are unique; custom aliases cannot overwrite existing links.
  2. A disabled or expired link never redirects from cache. Cache entries are invalidated or checked against an authoritative state.
  3. Every redirect target is validated at creation and again before use if the URL can change or DNS can be rebound.
  4. Analytics never blocks the redirect. Losing a click event is acceptable; losing the redirect is not.
  5. Codes are URL-safe and case-sensitive by policy, or explicitly case-insensitive with a single canonical form.
  6. Creation is idempotent for a given request key, so a client retry does not create two codes.
  7. The redirect path has a bounded latency budget and degrades to a safe response, not an unbounded wait.

Estimates

Assume 100M new links/day and 10B redirects/day. Adjust the ratio for your product, but keep the read/write asymmetry visible:

writes:  100M/day  ≈ 1,160 RPS average, ~3,500 RPS peak
reads:   10B/day   ≈ 115,000 RPS average, ~350,000 RPS peak
storage: 100M × (500 B target + 100 B metadata) ≈ 60 GB/day raw
indexes: one code lookup per redirect, one owner listing query per creator
code space: 62^7 ≈ 3.5 trillion → 7 base62 chars is enough for decades

The redirect path is roughly 100× the write path. Cache aggressively, but do not let the cache become the source of truth for expiry and disablement.

End-to-end flows

client
  → API: POST /links { longUrl, customAlias?, expiresAt? }
  → auth + rate limit (IP, account, ASN)
  → validate URL (scheme, host, length, credentials, blocklists)
  → resolve DNS and reject private/loopback/link-local/metadata ranges
  → allocate code (random or custom)
  → insert with unique constraint
  → if collision: retry N times, then fail with 409/503
  → cache the new code (optional warm)
  → enqueue safety scan (async)
  → return { code, shortUrl, expiresAt }

Failure branches:

  • Invalid URL: return a field-level error; do not echo the raw URL into logs without redaction.
  • Private target: reject with a generic message; do not confirm whether an internal service exists.
  • Custom alias taken: return 409, not a silent fallback to a random code.
  • Collision on random code: retry a bounded number of times. If retries exhaust, fail and alert; do not loop forever.
  • Database write timeout: the client may retry. Use an idempotency key so a timed-out insert does not create a second link.
  • Safety scan pending: the link may be created in a pending state. Redirects to a pending link should show an interstitial or return 404/403 according to policy, not silently redirect.

2. Redirect

client
  → edge / CDN
  → local LRU
  → Redis
  → database
  → validate: exists, not expired, not disabled, not blocked
  → respond 301/302/307
  → emit click event (fire and forget)

Define the cache layers explicitly:

Layer TTL Invalidation Notes
Browser 0 for analytics-sensitive links Cache-Control: no-store or short max-age 301 may be cached for a long time
CDN/edge seconds to minutes purge by URL on disable Hot links benefit most
App local LRU seconds TTL + explicit evict Per-instance; can be stale
Redis minutes delete on disable/expiry Shared, survives app restarts
Database authoritative transaction Must remain reachable for misses

301 vs 302 vs 307:

  • 301 is permanent and cacheable by browsers. It reduces load but makes click counting and destination changes unreliable.
  • 302 is temporary. Most shorteners use it to keep control and count clicks.
  • 307 preserves the HTTP method. For a redirect endpoint, 302 is usually enough; use 307 only if non-GET clients are expected.

State the product decision. “We use 302 so analytics and revocation work” is a valid choice. “We use 301 for speed” is also valid if the product accepts cached redirects.

operator/user
  → update database: disabled=true, updated_at=now
  → delete Redis key
  → publish invalidation event to app instances and edge
  → verify: next redirect returns 410/404
  → keep the tombstone long enough to prevent code reuse

Rules:

  • Do not reuse a code after deletion. A recycled code can redirect old links to a new destination, which is a phishing vector.
  • If the edge cache cannot be purged synchronously, serve a short-TTL cache and document the maximum stale window.
  • A disabled link should return 410 Gone (or 404 if you do not want to reveal existence). It must not redirect.

4. Expiry

Expiry is a state transition, not a background cleanup only.

  • Check expires_at on the redirect path against a trusted clock.
  • Cache entries must include the expiry and be invalidated at or before it.
  • A sweeper can delete or archive expired rows, but the redirect path must not depend on the sweeper having run.
  • If a link expires mid-request, the request that observed a valid state may complete; the next request must fail. Document this boundary.

5. Analytics ingestion

redirect
  → append event to local buffer / queue (bounded)
  → worker batches events
  → aggregate per link/day/country/referrer
  → write rollups
  → raw events expire
  • Never write one database row per click on the primary.
  • Use a bounded queue. If the queue is full, drop analytics before dropping redirects.
  • Deduplicate obvious bot traffic and repeated refreshes with a coarse policy; do not promise exact counts.
  • If analytics is delayed, show “updated N minutes ago” rather than pretending it is real-time.

6. Custom aliases

  • Validate character set, length, reserved words, and profanity/trademark lists.
  • Treat aliases as case-insensitive or case-sensitive consistently; do not allow both Promo and promo to resolve differently unless the product explicitly supports it.
  • Reserve routes such as /api, /admin, /health, /static, and anything that could collide with infrastructure.
  • Enforce uniqueness in the database, not only in application code.

Data model and state

A minimal schema is enough:

CREATE TABLE links (
  id          bigserial PRIMARY KEY,
  code        text NOT NULL UNIQUE,
  long_url    text NOT NULL,
  owner_id    uuid,
  status      text NOT NULL DEFAULT 'active', -- pending | active | disabled
  created_at  timestamptz NOT NULL DEFAULT now(),
  expires_at  timestamptz,
  disabled_at timestamptz,
  custom      boolean NOT NULL DEFAULT false,
  version     bigint NOT NULL DEFAULT 1
);

CREATE INDEX links_owner_created_idx ON links (owner_id, created_at DESC);
CREATE INDEX links_expiry_idx ON links (expires_at) WHERE status = 'active';

Why code is the primary lookup key: the redirect path is a single point lookup. The owner index supports listing. Keep the redirect query covered by the unique index.

State machine:

pending → active → disabled
   │         │
   └─────────┴──→ expired (derived from time, or a background transition)

expired can be computed rather than stored. If it is stored, a lagging transition must not allow redirects after the expiry time.

Edge cases

Case Expected behavior Why it matters
Same long URL submitted twice Two codes, or one if dedupe is a product rule Dedupe changes ownership and analytics
Same custom alias requested concurrently Exactly one wins; the other gets 409 Application-only checks race
URL with javascript:/data:/file: scheme Reject XSS and local file access
URL with embedded credentials Reject or strip Credential leakage in logs
Redirect target is a private IP Reject at create and at redirect SSRF
Target DNS resolves to a private IP after creation Re-resolve or block at use DNS rebinding
Target redirects to another private IP Follow-chain validation or refuse to follow Open redirect/SSRF chain
Target returns 404/500 Redirect still works; destination owns the error Do not hide the destination’s state
Target is very long (>2–8 KB) Reject with a clear limit Storage and header limits
Target contains Unicode/IDN Normalise and display the punycode form Homograph phishing
Code looks like a reserved route Reject at creation Routing conflicts
Code uses ambiguous characters Prefer a Crockford-like alphabet Human transcription errors
Expired while cached Cache invalidated at expiry; never serve Correctness
Disabled while cached Invalidate all layers; return 410 Safety/legal
Link deleted, code requested later Never reuse the code; return 404/410 Old links must not change meaning
HEAD request Same status/headers, no body Proxies and crawlers
Client retries create after timeout Idempotency key returns the same code Duplicate links
Bot scans millions of codes Negative cache + rate limit + WAF Database meltdown
Analytics queue full Drop/sample events, keep redirects Redirect is the priority
Clock skew across regions Use a single time source for expiry decisions Early/late expiry

Failure modes and recovery

Failure User-visible behavior Detection Mitigation Recovery
Redis down Redirects fall back to DB; latency rises Redis errors, DB QPS spike Local LRU, DB QPS cap, load shedding Restore Redis, warm hot keys
DB primary down New links fail; cached redirects work Primary health, write errors Serve cached reads; queue writes Fail over; reconcile queued writes
Read replica lag Recently disabled link still resolves Replica lag metric Disable via primary/cache invalidation Evict cache, wait for lag, audit
Analytics queue down Clicks are dropped or buffered Queue depth, consumer lag Bounded local buffer, sampling Replay from durable buffer if available
Hot link One shard/CPU saturates Per-key QPS, CPU skew Edge cache, per-key rate limit, shard by code Add cache capacity; consider dedicated hot-link tier
Cache stampede after purge DB/QPS spike Miss ratio, DB load Single-flight, jittered TTL Warm cache gradually
Malicious scanning DB/CPU load, error rate 404 rate, per-IP QPS Negative cache, rate limits, WAF Block ASN/IP, add proof-of-work if needed
Code collision storm Create errors Collision counter Larger code space, retry budget Investigate entropy source
Poisoned cache entry Wrong destination Synthetic checks, user reports Validate on write, signed cache entries Purge key, audit write path
Region outage Local latency/errors Regional health Multi-region read replicas, DNS failover Fail traffic over; reconcile state

Degraded-mode rules:

  1. Prefer redirects over creation.
  2. Prefer cached reads over database reads, but never serve a known-disabled link.
  3. Prefer dropping analytics over delaying redirects.
  4. Prefer a safe 503 over an unbounded wait.

Abuse, security, and privacy

  • SSRF: block loopback, link-local, RFC1918, metadata endpoints, and IPv6 equivalents. Resolve DNS and pin the result for the request; re-check on redirect if the target can change. Do not follow redirects into private ranges.
  • Open redirect: the service is a redirector by design, so treat every target as untrusted. Show an interstitial for new or suspicious destinations if the product allows it.
  • Phishing/malware: scan asynchronously, quarantine, and provide a takedown path. Keep an audit trail of who created what.
  • Enumeration: random codes should be unguessable; private links should use signed tokens or access controls.
  • Rate limits: separate create, redirect, and analytics budgets. Limit by IP, account, ASN, and destination reputation.
  • Logging: redact full URLs, query strings, tokens, and IPs where policy requires. Keep enough data for abuse investigations.
  • Privacy: define retention for click events; aggregate early; support deletion requests.

Operating process

Before launch

  • Load test the redirect path at target peak with a realistic cache hit ratio and a 0% hit-ratio run.
  • Test failover: kill Redis, kill the primary, add 30 seconds of replica lag, purge the CDN.
  • Run an SSRF test suite against IPv4, IPv6, decimal/octal IPs, DNS rebinding, and redirect chains.
  • Seed a blocklist and confirm quarantined links cannot redirect.
  • Write the top three runbooks: Redis down, DB failover, abuse spike.

Deploy process

  1. Apply backward-compatible schema changes first.
  2. Deploy code that can read both old and new shapes.
  3. Backfill asynchronously; keep the old path until the backfill is complete.
  4. Switch reads, then writes.
  5. Remove the old path in a later release.

Incident process

  • Detect: redirect 5xx, p99 latency, cache hit ratio, DB QPS, queue depth, abuse rate.
  • Triage: is the redirect path degraded, or only creation/analytics?
  • Contain: shed creation, raise cache TTL, block abusive ASNs, fail over the primary.
  • Recover: warm caches, reconcile queued writes, verify a sample of codes across all layers.
  • Learn: update the runbook and add a regression test.

Testing strategy

  • Unit: code alphabet, URL validation, expiry math, cache key construction.
  • Property-based: generated URLs and codes; uniqueness and round-trip properties.
  • Integration: create → redirect → disable → redirect, with cache layers real.
  • Race tests: concurrent custom alias creation; concurrent create/disable.
  • Security: SSRF matrix, scheme allowlist, header injection, open redirect chains.
  • Load: redirect at peak with 0%, 80%, and 99% cache hit ratios.
  • Chaos: Redis kill, DB failover, queue pause, clock skew, CDN purge.
  • Analytics: duplicate events, delayed events, queue overflow, bot traffic.

Milestones and acceptance criteria

Milestone Build Accept when
1. Create + redirect Schema, code generation, POST /links, GET /{code} A created link redirects; collisions retry; invalid targets are rejected
2. Correct invalidation Disable + expiry + cache eviction A disabled link cannot be served from any cache layer
3. Durable reads Redis + local LRU + negative cache Redirect works with Redis down and with the primary down for cached codes
4. Safe creation Rate limits, SSRF checks, idempotency Replayed create returns one code; private targets are blocked
5. Analytics Async queue + rollups Redirect is never blocked by analytics; loss is bounded and visible
6. Abuse controls Blocklists, quarantine, takedown Suspicious links cannot redirect and have an audit trail
7. Scale Load test + failover drills p99 within budget at peak; 0% hit ratio does not take down the DB

Review questions

  • What happens on a code collision, and how many retries before you fail?
  • How do you prevent SSRF at creation and at redirect time?
  • Can a disabled/expired link still resolve from any cache? How do you prove it?
  • What is the cache hit ratio, and what happens at 0%?
  • Which failure do you prefer: dropped analytics or a delayed redirect?
  • How do you stop enumeration and scanning without hurting legitimate users?
  • What is the stale window after a disable, per cache layer?
  • How do you reconcile a create that timed out after the database committed?
  • What is the retention policy for click data, and how do you delete it?

Checklist

  • Codes are random, unique via constraint, and URL-safe.
  • Custom alias creation is atomic and never overwrites.
  • Redirects validate existence, status, expiry, and target safety.
  • 301 vs 302 is a deliberate product decision.
  • Every cache layer has a TTL, invalidation path, and stale-window limit.
  • Analytics is asynchronous, bounded, and allowed to drop.
  • Creation is rate-limited and SSRF-safe, including DNS rebinding.
  • Delete/disable never reuses a code.
  • Redis/DB/queue failures have tested degraded modes.
  • The redirect path has a latency budget and a load test at 0% cache hit.
  • Top failure modes have runbooks and alerts.
  • Click-data retention and deletion are defined.