Skip to content

Case Study: URL Shortener

The URL shortener is the most common warm-up design question. It looks trivial and has one genuinely interesting problem: generating short, unique, non-guessable identifiers at scale while serving redirects in milliseconds.

This page walks the System Design Interviews framework end to end.

Functional

  1. Given a long URL, return a short URL.
  2. Given a short code, redirect to the long URL.
  3. Optional: custom alias, expiry, click analytics.

Non-functional

  • Redirect latency < 100 ms p99. Redirects are the hot path.
  • 100:1 read:write ratio.
  • Codes are short (7 characters), URL-safe, and not trivially enumerable.
  • Redirects must survive a regional failure.
  • Analytics may be delayed by minutes.

Out of scope: user accounts, billing, malware scanning (mention it as a real requirement in production).

Writes: 10M new URLs/day → ~116/s, peak 3× → ~350/s
Reads: 1B redirects/day → ~11,600/s, peak 3× → ~35,000/s
Row: code(7) + url(500) + owner(8) + created(8) + metadata ≈ 600 bytes
Storage: 10M × 600B = 6 GB/day ≈ 2.2 TB/year
Cache: hot 20% of daily reads ≈ 200M entries × ~600B ≈ 120 GB
(or just cache with an LRU and let the working set find itself)
Bandwidth: 35,000 × 600B ≈ 21 MB/s outbound at peak

The conclusion that drives the design: reads dominate by 100×, so the entire architecture is a cache in front of a key-value lookup.

POST /v1/urls
{ "long_url": "https://example.com/a/very/long/path",
"custom_alias": "launch", // optional
"expires_at": "2027-01-01T00:00:00Z" }
201 { "code": "aB3xK9q", "short_url": "https://sho.rt/aB3xK9q" }
GET /{code}
302 Location: https://example.com/a/very/long/path
404 if unknown or expired

301 versus 302 is a real decision:

  • 301 Moved Permanently is cached by browsers, so repeat visits never reach you. Cheaper, but you lose analytics and cannot change the destination.
  • 302 Found sends every visit to you. More load, but you keep control and can count.

Most shorteners use 302 because analytics is the product. Say which you chose and why.

urls
code varchar(7) PK
long_url text
owner_id bigint NULL
created_at timestamptz
expires_at timestamptz NULL
INDEX (owner_id, created_at DESC)

The primary access pattern is SELECT long_url FROM urls WHERE code = ? — a single primary-key lookup. This is why a key-value store is a legitimate choice here, though a partitioned relational table works fine at this scale.

Analytics is a different workload and a different store:

clicks(code, ts, country, referrer, user_agent_class) -- append-only, partitioned by day

This is the deep-dive question. Options:

1. Hash the long URL (MD5/SHA, take 7 chars). Deterministic, so the same URL yields the same code (nice for dedupe). But collisions must be handled by probing, and the same URL from two users maps to one code, which breaks custom aliases and per-user analytics. Sequential probing adds a read before every write.

2. Random base62. 62^7 ≈ 3.5 × 10^12 combinations. With 10M writes/day, birthday collisions become a real probability after a few years. Handle with a unique constraint and retry: cheap, simple, and unguessable, which matters if URLs are private. Writes need a retry loop.

ALPHABET = [*"a".."z", *"A".."Z", *"0".."9"].freeze
def generate_code(length = 7)
Array.new(length) { ALPHABET[SecureRandom.random_number(ALPHABET.size)] }.join
end
def create_url(long_url)
5.times do
code = generate_code
begin
db.exec("INSERT INTO urls (code, long_url) VALUES ($1, $2)", [code, long_url])
return code
rescue PG::UniqueViolation
next
end
end
raise "could not allocate a code"
end

3. Counter + base62. A global counter is collision-free and short (1 → "b", 62 → "ba"). But it is guessable — competitors can enumerate your volume — and a single counter is a write bottleneck.

4. Key Generation Service (KGS). Pre-generate random codes in bulk, store unused ones in a table, and hand them out atomically. Writes never collide and never wait on a generator; the service can pre-mark blocks as “in use” for each app instance so it does not need a round trip per code. The cost is another service and the risk of burning a block on crash (acceptable — codes are plenty).

5. Snowflake-style distributed IDs. 64-bit id = timestamp + machine id + sequence. Collision-free across nodes without coordination, but the base62 encoding of a 64-bit number is 11 characters, not 7.

client → CDN/edge → LB → redirect service → Redis (code → long_url)
↓ miss
DB primary-key lookup → populate cache
  • Cache with a long TTL and an LRU eviction policy. A shortener’s data is effectively immutable, so invalidation is only needed for delete or expiry.
  • Negative-cache unknown codes briefly so a scanner cannot use 404s to hammer the database.
  • Cache-Control: private, max-age=0 on the redirect itself so browsers re-check but CDNs do not cache the redirect for everyone — unless you deliberately want edge caching of the Location, which is a valid optimisation for the hottest links.
  • Keep the redirect service stateless so it scales trivially.
POST → API → validate URL (scheme allow-list, block localhost/private IPs — SSRF!)
→ generate code → INSERT → return

That SSRF check is a real production requirement and a good thing to volunteer: a shortener fetches or redirects to user-supplied URLs, and a redirect to http://169.254.169.254/ is a live attack. At minimum, block private ranges and non-HTTP schemes, and warn on the interstitial page.

Do not write a click row synchronously on the redirect path; it triples the write load and adds a database dependency to a 100 ms budget.

redirect handler → append to an in-memory buffer or a queue (fire and forget)
→ batch consumer → columnar store (ClickHouse, BigQuery)

Accept loss of a small fraction of events. Analytics at “99% accurate, 5 minutes delayed” is fine; redirects at “100% available, 90 ms” is not negotiable.

Counters (clicks_total) can be a sharded Redis counter flushed periodically, or derived entirely from the event store at query time.

  • Reads: CDN for the hottest codes, Redis for the rest, read replicas behind that. At 35k rps with a 95% cache hit rate, the database sees ~1,750 rps.
  • Writes: shard by code hash if needed; a partitioned table handles this volume comfortably.
  • Regional failure: replicate the code table globally. A shortener is read-mostly and eventually consistent by nature, so multi-region active-active is easier here than in most systems — you only need to prevent code collisions, which random codes handle statistically.
  • Hot link: a link going viral is a single key at enormous QPS. Edge caching and local in-process caching for the top N codes handle it without a Redis hotspot.
  1. How do you guarantee no two users get the same code under concurrent writes?
  2. What changes if the requirement is “codes must not be guessable”?
  3. How do you expire links without a background job scanning the table?
  4. Where do you put the analytics write, and what do you lose by doing it?
  5. How would you detect and block a link to a phishing site?
  6. What happens when a hot link’s cache entry expires at 10,000 rps?
  • Designing only the write path. Reads are 100× the writes; the cache is the design.
  • Ignoring collisions. “Random is fine” needs a unique constraint and a retry, or it is a data corruption bug.
  • Writing analytics synchronously. It puts a non-essential dependency inside the latency budget.
  • Forgetting expiry. Expired links need filtering on read and eventual deletion, not a full table scan every night.
  • No abuse story. Public shorteners are spam and phishing infrastructure. Mention scanning and rate limits before you are asked.