SDE & MLE Prep

URL Shortener (TinyURL / bit.ly)

Requirements: shorten a long URL, redirect short → long with low latency, optional custom alias & expiry, analytics. Read-heavy (100:1).

Estimates: 100 M new URLs/day ≈ 1.2k writes/s; 10 B redirects/day ≈ 115k reads/s. 5 yrs × 100 M × 365 ≈ 180 B URLs × ~500 B ≈ 90 TB. A 7-char base62 code gives 62⁷ ≈ 3.5 × 10¹² codes — plenty.

API: POST /urls {longUrl, alias?, ttl?} → shortUrl, GET /{code} → 301/302 Location: longUrl.

            write path                                  read path
client -> API -> ID generator (ranges / Snowflake)   client -> LB -> redirect svc -> Redis (code -> url)
              -> base62(id) = "aZ3k9Q1"                                          | miss
              -> KV store {code: longUrl, owner, exp}                            v
                                                                            KV store (Cassandra/Dynamo)
                         analytics: redirect svc -> Kafka -> stream agg -> OLAP

Deep dives

  • Code generation: (a) hash(longUrl) → take 7 chars, handle collisions by retry/salt; (b) counter + base62 — no collisions; give each app server a pre-allocated ID range (from ZooKeeper / a ticket DB) so there's no per-request coordination. Add a random offset or shuffle if sequential codes must not be guessable.
  • 301 vs 302: 301 is cached by browsers (less load, loses analytics); 302 keeps every hit on your servers.
  • Storage: simple key → value lookups at huge scale → partitioned KV store keyed by code. Cache the hot 20% of URLs (Zipf distribution) in Redis.
  • Expiry: TTL in the store + lazy deletion on read + background cleanup.