Design: URL shortener
Give each long URL a short base62 key from a collision-free ID source, store key → URL in a sharded key-value store, serve redirects from cache, and log clicks asynchronously, off the redirect path.
Fundamentals you'll use
How it works
- Scale (assumed): ~1.2k writes/s against ~116k redirects/s, so the read path is the design.
- Keys come from a counter leased in blocks and base62-encoded: 7 characters give ~3.5 trillion keys.
- A hash cut to 7 base62 characters has a ~50% collision chance by ~2.2M links: insert conditionally and retry.
- Redirects read an in-process LRU, then Redis, then the KV store; clicks go async to Kafka.
- A 302 brings every click back for analytics; a 301 is cacheable, so repeat clicks may skip you.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your shortener answers with 301 and no cache headers. Product now sells per-click analytics, and customers report that repeat clicks from the same browser never show up. What do you change?
Go deeper
Full explanation
Requirements
Functional: create a short link for a long URL (optional custom alias and expiry), redirect GET /{key} to it, and count clicks per link. Non-functional: redirects in a few ms server-side, very high availability (a dead shortener breaks every place a link was pasted), and unguessable keys when links are private.
Scale (assumed): 100M new links/day ≈ 1.2k writes/s; at 100:1 reads ≈ 116k redirects/s; 5 years ≈ 180B links × ~500 B ≈ ~90 TB.
Questions I'd ask:
- Do we need click analytics, or only redirects? That decides 301 vs 302.
- Can links be edited or deleted after they are shared?
- Must keys be unguessable?
API and data model
POST /links {url, alias?, expires_at?} → {key} and GET /{key} → 302 Location: url. One table, links(key PK, url, owner_id, created_at, expires_at). Every read is a lookup by key, so a key-value store partitioned by key (DynamoDB, Cassandra) fits (SQL vs NoSQL).
Architecture
Write path: the API server takes an ID from its leased block, base62-encodes it and does a conditional insert. Read path: redirect service → in-process LRU → Redis → KV store, then 302. Each redirect drops a click event on Kafka; a stream job rolls up counts (Stream processing: windows, watermarks, state). The redirect never waits on analytics.
The hard parts
- Key generation: hashing needs collision checks; a counter needs coordination.
- The redirect code: a
301is cacheable by default (RFC 9110), so browsers may skip you on repeat clicks: cheaper, but you lose analytics and can't edit links. A302brings every click back.
Code Base62 keys from leased ID blocks, and the redirect
import string
ALPHABET = string.digits + string.ascii_letters # 62 URL-safe symbols
def base62(n: int, width: int = 7) -> str:
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out)).rjust(width, "0") # 62^7 ~ 3.5T keys
class IdLease:
"""Each API server leases a block of IDs: one DB write per million links."""
def __init__(self, db, block: int = 1_000_000):
self.db, self.block, self.next, self.end = db, block, 0, 0
def take(self) -> int:
if self.next == self.end: # block spent: one atomic increment
self.end = self.db.incr("link_counter", self.block)
self.next = self.end - self.block
self.next += 1
return self.next - 1 # a crash only leaves a gap, never a dup
def create_link(url: str, lease: IdLease, kv, private: bool = False) -> str:
n = lease.take()
# Sequential keys are enumerable: permute them for private links
key = base62(permute(n) if private else n)
kv.put(key, url, if_not_exists=True) # guard: a conflict means a bug
return key
def redirect(key: str):
url = local_lru.get(key) or redis.get(key) or kv.get(key) # fill-on-miss elided
if url is None: return 404, {}
clicks.send_async({"key": key, "ts": now()}) # never block the redirect
return 302, {"Location": url} # 302: every click returnsReal example
A campaign link sho.rt/aZ3k9Qx goes out in a push to 5M users at 9:00, and ~50k clicks/s hit one key. The first miss reads the KV store once; after that each redirect server answers from its in-process LRU (TTL 60 s), so no single Redis node takes the whole spike. Every response is a 302, and each click lands on Kafka as {key, ts, country, referrer}. A stream job rolls up per-minute counts: the dashboard trails by about a minute, and no redirect waited for it.
Trade-offs +3 · −3
+ You gain
- A redirect is one key lookup, mostly from cache: latency stays flat as links grow to billions.
- Leased counter blocks give unique keys with no per-write coordination and no collision checks.
- Async analytics: a Kafka outage loses click counts, never redirects.
− You pay
- A 302 sends every click to your servers: traffic a 301 would leave in browser caches.
- Counter keys are enumerable unless permuted; truly secret links need long random tokens.
- Blocks lost in crashes leave gaps, so key counts never equal link counts.
Use it when
Any service that hands out short, stable identifiers for long resources: share links, invite codes, QR codes, SMS links where every character counts.
Avoid it when
When the link is itself a secret (password reset, signed downloads): use long random tokens or signed URLs, not 7-character keys.
Numbers to know 5
- Writes: 100M links/day (assumed) ÷ 86,400 s ≈ 1.2k/s; at 100:1 reads ≈ 116k redirects/s average.
- Key space: 62^6 ≈ 56.8B, 62^7 ≈ 3.5T; at 100M/day, 6 characters last ~1.6 years, 7 last ~96 years.
- Storage: 5 years ≈ 180B links × ~500 B ≈ ~90 TB before replication.
- Hash truncated to 7 base62 characters: ~50% chance of a collision after only ~2.2M links.
- Snowflake IDs (41-bit time, 10-bit machine, 12-bit sequence) are 64-bit integers: up to 11 base62 characters.
Common pitfalls 4
- Truncating a hash without a collision check: two URLs share a key and one silently redirects to the other's target.
- Writing analytics synchronously in the redirect: that write becomes your p99 and your availability ceiling.
- Shipping 301s, then promising per-click analytics or editable links: browsers keep redirecting from their cache.
- No negative cache for unknown keys: scanners enumerating keys hit the database on every miss.
Interview questions 3
Answer out loud first, then reveal.
How do you generate keys across many servers without collisions?Show answer
A counter, not a hash, but never one hot counter. Each API server leases a block of about a million IDs with one atomic increment, then base62-encodes locally: no coordination per write and no collision check. A crash only wastes the rest of a block. If keys must not be guessable, I permute the ID with a keyed bijection before encoding, or use random keys with a conditional insert.
301 or 302 for the redirect?Show answer
It depends on whether I need every click. A 301 is cacheable by default, so a browser that saw it may never ask me again: less traffic, but I lose analytics and can't retarget the link. A 302 isn't cached by default, so every click reaches my edge. For a product that sells click analytics I use 302 and make the redirect cheap with caching; for vanity links, 301 is fine.
One link goes viral at 50k clicks/s. What breaks first?Show answer
Not the database: cache-aside reads it once. The weak spot is the single Redis node that owns that key. I put a small in-process LRU with a short TTL on every redirect server, which spreads the hot key across the fleet, and coalesce concurrent misses. Click events keyed by link would also pile onto one Kafka partition, so I add a random suffix to the partition key for hot links.
Deep dive 3
Key generation: counter vs hash
Counter: unique by construction, no collision check. One counter row is a bottleneck, so each API server leases a block of ~1M IDs with one atomic increment and spends it locally; a crash only leaves a gap. Sequential keys are enumerable, so permute the ID with a keyed bijection (a small block cipher) for private links. Snowflake-style IDs (41-bit ms timestamp, 10-bit machine, 12-bit sequence) skip the coordinator but, as 64-bit integers, take up to 11 base62 characters: too long. Hash (SHA-256 of the URL, first 7 base62 characters): the same URL dedups for free, but ~42 bits collide after ~2.2M links (birthday bound), so insert with if-not-exists and retry with a salt. I'd pick leased counter blocks.
Redirect path: 301 vs 302 and caching
RFC 9110 makes 301 and 308 heuristically cacheable, and 302 and 307 not. After a 301 a browser may never ask again: less traffic, but no per-click analytics and no way to retarget the link. Use 302, or a 301 with Cache-Control: no-store, when clicks or edits matter. The read path is cache-aside (Caching strategies): an in-process LRU with a short TTL absorbs hot keys, Redis holds the warm set, the KV store serves misses. Cache negative lookups too, or check a Bloom filter (Probabilistic data structures), so scanners guessing keys never reach the database. Check expiry on read and sweep expired rows in the background.
Analytics and abuse
Clicks are events, not writes inside the redirect: publish {key, ts, country, referrer} to Kafka partitioned by key and roll up per-minute counts in a stream job; count unique visitors with HyperLogLog. If Kafka is down, buffer locally and drop, never fail the redirect. Abuse is the real operational load: short links hide phishing and malware. Check targets against a URL-reputation service at creation and again for flagged domains, rate-limit creation per account and IP (Rate limiting), and show an interstitial warning for suspicious targets.