Case study: URL shortener

Topic 1 of 15 in Week 7: Classic case studies14 min readIntermediateFree course

Overview

A URL shortener turns https://example.com/very/long/path?with=params into https://sho.rt/aZ3kP9q and redirects visitors back. It’s the classic warm-up design question because it’s small enough to finish in 45 minutes but still touches ID generation, caching, storage choice and analytics.

Try the exercise first: set a 45-minute timer and design it yourself, then read on.

1. Requirements

Functional

  • Create a short link for a long URL, optionally with a custom alias and an expiry date.
  • Visiting a short link redirects to the long URL.
  • Owners can see click counts.

Out of scope: link editing, user management details, QR codes.

Non-functional

  • Redirects are fast (p99 under ~50 ms server-side) and highly available (99.99%); a broken link is very visible.
  • Short codes must never collide, and should be hard to enumerate.
  • Read-heavy: about 100 redirects per link created.

2. Estimates

Text
writes : 100M links / month ≈ 100M / 2.6M s ≈ 40 / s   (peak ~100 / s)
reads  : 100 × writes ≈ 4,000 / s                       (peak ~10,000 / s)
storage: 100M × 12 months × 5 years = 6 billion links
         × ~500 bytes ≈ 3 TB  (plus replicas)
codes  : base62, 7 chars → 62^7 ≈ 3.5 trillion  (plenty)

Conclusions: the write rate is tiny; the read path matters most; 3 TB fits in a modest distributed key-value store.

3. API

Text
POST /v1/urls
  {"long_url": "https://…", "alias": "spring-sale", "expires_at": "2027-01-01"}
  → 201 {"code": "aZ3kP9q", "short_url": "https://sho.rt/aZ3kP9q"}

GET /{code}
  → 301 or 302, Location: https://…     (404 if unknown, 410 if expired)

GET /v1/urls/{code}/stats → {"clicks": 1234, "by_day": [...]}

4. Data model

Text
links: code (PK) | long_url | owner_id | created_at | expires_at
clicks (aggregated): code | day | count

The main query is a lookup by code, so a key-value or wide-column store (DynamoDB, Cassandra) or a sharded relational table keyed by code all work. Store long_url as given; optionally keep a hash of it to return an existing code for repeat submissions.

5. High-level design

URL shortener high-level design. A client calls the load balancer and stateless API. To create a link, the API gets a unique ID from a key service that hands out ranges of IDs, then writes the code and URL to a key-value URL store. To redirect, the API reads the cache, which maps codes to URLs, and falls back to the URL store on a miss. POST /urls gets a unique ID, base62-encodes it into 7 characters (about 3.5 trillion codes) and stores code to URL. GET /{code} checks the cache, then the store, returns a 301 or 302 redirect and logs a click event asynchronously. Because reads far outnumber writes, cache hot codes, replicate the store and put redirects behind a CDN if allowed.

  • Create: the API validates the URL, obtains a unique numeric ID, encodes it in base62, writes code → long_url to the store and returns the short URL.
  • Redirect: the API looks up the code in Redis; on a miss it reads the store and fills the cache. It returns a redirect and publishes a click event to a queue.

6. Deep dives

Generating short codes

Options:

  1. Hash the URL (MD5/SHA) and take 7 characters: simple, but different URLs can collide, so you must check and retry, and the same URL always gives the same code (not always wanted).
  2. Random code + uniqueness check: generate 7 random base62 characters and insert with “only if absent”. Collisions are rare at first but grow as the space fills; each create may need a retry.
  3. Counter + base62 (recommended): a unique 64-bit ID encoded in base62. No collisions by construction. To avoid a single counter bottleneck, a key service hands each API server a range of IDs (for example 1,000,000 at a time) stored in a small strongly consistent store; servers allocate from their range in memory. A Snowflake-style generator (unique ID case study) also works.

Sequential codes are guessable (aZ3kP9q, aZ3kP9r…). If enumeration matters, shuffle the ID with a reversible permutation or add random bits.

Custom aliases are inserted with a conditional write (“create only if the code doesn’t exist”), and reserved words (api, admin) are blocked.

301 vs 302

  • 301 (permanent): browsers and proxies cache it, so repeat visits may never reach you. Lower load, but click counts become inaccurate and you can’t change the destination.
  • 302 (temporary): every visit hits your service. Accurate analytics, more traffic.

Most commercial shorteners use 302 (or 307) for analytics; mention the trade-off.

Caching the redirect path

Link popularity is very skewed: a small fraction of links get most clicks. A Redis cache with LRU eviction and a hit rate above 90% removes most database reads. Expired links need care: store expires_at in the cached value and check it, or set the cache TTL to the remaining lifetime. Extremely hot links can also be cached at the CDN edge with a short TTL.

Analytics

Never update a counter in the database on every redirect; that turns a read path into a write path. Publish click events (code, time, referrer, country, device) to Kafka; a stream job aggregates counts per code per day into an analytics store. Approximate real-time counts can live in Redis.

Abuse

Short links hide destinations, so they attract phishing and malware. Rate-limit creation per user and IP, check URLs against safe-browsing lists at creation and periodically, allow reporting, and be able to disable a code instantly (delete it from cache and store).

7. Trade-offs and bottlenecks

  • The store is the main dependency of the redirect path: replicate it across zones; the cache absorbs most reads.
  • The key service must not become a single point of failure: ranges let servers keep working through brief outages.
  • Strong consistency matters only for creation (no duplicate codes); redirects can be eventually consistent.

8. Follow-up questions

  • Traffic grows 10×? Add cache nodes and API servers; the store scales horizontally by code.
  • A link goes viral? Hot-key handling: local in-process cache on each server, CDN edge caching.
  • Delete expired links? A background job scans by expiry and deletes in batches; lazy checks on read.
  • Same long URL submitted twice? Optionally look up by URL hash per user and return the existing code.

Recap

A URL shortener is a read-heavy key-value lookup with a small write path. Generate collision-free codes from unique IDs encoded in base62 using pre-allocated ranges, serve redirects from a cache in front of a replicated store, choose 301 or 302 based on analytics needs, record clicks asynchronously, and guard against abuse.

Exercise

Design it yourself (45 minutes)

Before reading the lesson, set a 45-minute timer and design a URL shortener. Assume 100 million new short links per month, a 100:1 read-to-write ratio, optional custom aliases, optional expiry, and click counts per link. Work through the framework in the starter, then compare with the model answer.

Text
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates (QPS, storage):
5. API:
6. Data model:
7. High-level design:
8. Deep dives (code generation, caching, analytics):
9. Trade-offs and bottlenecks:

Summary

  • The system is extremely read-heavy: optimise the redirect path with caching and a simple key-value lookup.
  • Generate codes without collisions: base62-encode IDs from a distributed counter or pre-allocated ranges; 7 characters give ~3.5 trillion codes.
  • 301 redirects are cached by browsers (fewer requests, lost analytics); 302 keeps every click visible.
  • Record clicks asynchronously through a queue so analytics never slows redirects.
  • Plan for abuse: rate limits, malicious-URL scanning, and expiry cleanup.