Case Study: URL Shortener

The classic warm-up: base62 encoding, counter vs hash collisions, 301 vs 302 redirects, read-heavy caching.

Intermediate9 min read
Language
Theme
long URLexample.com/very/long/pathbase62 codecounter / hash / KGSsdv.ly/x7Kp2301/302long URLRedis cachehot codesKV storecode -> URL301 = browser caches (less load, no analytics). 302 = every click counted
Key idea at a glance

The problem, stated properly

Take a long URL, give back a short code (bit.ly/a9x2Kq), and redirect anyone who hits that code to the original URL. Tiny product, big lessons: it is the most read-heavy system you will ever design, the key-generation question has at least four legitimate answers, and one HTTP status code decision (301 vs 302) quietly determines whether your analytics business exists at all.

Scale first: read-heavy by two orders of magnitude

Assume 100 million new short URLs per month and a 100:1 read-to-write ratio (typical; links are shared and clicked far more than created).

  • Writes: 100M / (30 x 86,400 s) is roughly 40 new URLs/sec. Trivial for any database.
  • Reads: 100 x 40 = 4,000 redirects/sec average, 5-10x that at peak, so plan for ~40K QPS.
  • Storage: a row is roughly 500 bytes (short code, long URL, owner, timestamps, expiry). 100M/month x 500 B x 5 years is about 30 TB. Fits comfortably in a sharded SQL or any NoSQL store.
  • Cache: following the 80/20 rule, 20% of links serve 80% of traffic. Caching the hot 20% of daily writes (100M x 20% x 500 B is about 10 GB/day) in Redis kills most database reads.

The core design decision: where does the short code come from?

Four real strategies, and interviewers expect you to compare at least two:

  1. Hash + truncate: MD5 or SHA-256 of the long URL, take the first 7 chars. Collision risk is real: with 62^7 (about 3.5 trillion) possible codes, the birthday paradox gives you a 50% collision chance near sqrt(3.5T) which is roughly 1.9 million codes. You must check for collisions on every write and re-hash with a salt or appended counter. Deterministic (same URL gives same code) which some products want and some forbid.
  2. Counter + Base62: a single auto-increment ID, encoded to Base62 (a-z, A-Z, 0-9). Zero collisions, shortest possible codes, but the counter is a single point of contention and codes are sequential, so competitors can enumerate your links and infer your growth rate.
  3. Distributed ID generator (the production answer): a ZooKeeper/Redis-based range allocator gives each app server a block of IDs (server A gets 1M-2M, server B gets 2M-3M). No coordination per request, no collisions, scales horizontally. This is what most real systems do.
  4. Pre-generated Key Generation Service (KGS): an offline worker pre-fills a table of random 7-char codes; servers pull batches of unused keys and mark them used. Zero collision checking on the write path, no sequential leakage, at the cost of one extra moving part that itself needs replication.

301 vs 302: the status code that is actually a business decision

  • 301 (permanent): browsers cache the redirect forever. Repeat clicks never touch your servers, which slashes load, but you lose all click analytics after the first visit and can never edit the destination. TinyURL-style.
  • 302 (temporary): every click hits your server first. Full analytics (count, referrer, geography, device) and editable destinations, at the cost of owning 100% of redirect traffic forever. Bitly-style. If analytics is the business model, it is 302, and the extra load is the price of the data.

API and data model

  • POST /api/shorten body: long_url, optional custom_alias, optional expiry. Returns the short URL. Rate-limit hard: link shorteners are spammer magnets.
  • GET /{code} returns 301/302 with Location header. This endpoint must be pure read: no writes, no joins, cache first.
  • Schema: url_mapping(code PK, long_url, user_id, created_at, expires_at) plus a separate clicks table for analytics, written asynchronously through a queue so analytics writes never sit in the redirect path.

Production failure modes

  • Custom-alias squatting and abuse: without a reservation system and content scanning, short links become phishing infrastructure. Real services run every long URL through a blocklist (Google Safe Browsing API) before accepting it.
  • Cache stampede on a viral link: a link in a viral tweet expires from cache and 50K requests hit the DB simultaneously. Defense: request coalescing (single-flight) or a mutex on cache miss.
  • KGS key exhaustion: if the pre-generation worker silently stalls, writes fail at 3 AM. Monitor the unused-key pool like you monitor disk space.
  • Expired-link ambiguity: returning 404 vs a friendly page vs redirecting to a "this link expired" page is a product decision, not an afterthought.

Common interview traps

  • Jumping to "hash the URL" without discussing collisions or the read/write ratio.
  • Designing for writes. This system is 99% reads; the redirect path is where all the engineering rigor goes.
  • Forgetting rate limiting on creation. Without it, one script fills your keyspace with garbage.
  • Never mentioning expiry. Links live forever in toy designs and cost real money in real ones.

Interview Q&A

Q: Base62 or Base64 for codes?
A: Base62. Base64 includes '+' and '/' which are reserved characters in URLs and force ugly percent-encoding. Base62 (10 digits + 26 lowercase + 26 uppercase) is URL-safe with no escaping. Seven Base62 chars give about 3.5 trillion codes, enough for 100M/month for almost 3,000 years.

Q: How do you handle a hot link doing 10K redirects/sec on its own?
A: It is one key, so it lives in one Redis slot. Redis handles ~100K ops/sec per shard, so a single hot key is fine on cache. The failure to plan for is the cache miss: use single-flight so one request repopulates the cache while the rest wait, and consider replicating the hot key across cache nodes so no single Redis box eats all 10K QPS.

Key takeaways

Interview pointer

TinyURL looks easy, which is exactly why interviewers use it to test structured thinking. Estimate scale, present the three generation strategies with tradeoffs, and justify the redirect code.