Case Study: URL Shortener

Design a TinyURL/bit.ly-style service end to end — requirements, estimates, key generation (base62, counters, hashing), the redirect path, caching, analytics and scaling.

Intermediate 3 min readLesson 16 of 20

A classic first system design problem: small enough to finish in 45 minutes, rich enough to show estimation, data modelling, key generation and caching.

1. Requirements

Functional

  • Given a long URL, return a short one (sho.rt/aZ3kP9q).
  • Visiting the short URL redirects to the long one.
  • Optional: custom aliases, expiry, click analytics.

Non-functional

  • Very read-heavy (redirects ≫ creations), so redirects must be fast (p99 under ~50 ms) and highly available.
  • Short codes must be unique and not easily guessable in sequence (optional).

2. Estimates

  • 100M new URLs/month ≈ 40 writes/s (peak ~200/s).
  • Read:write of 100:1 → 4,000 redirects/s (peak ~20k/s).
  • Storage: 100M × 12 months × 5 years = 6B URLs × ~500 bytes ≈ 3 TB.
  • Code length: 62⁷ ≈ 3.5 trillion — 7 base62 characters is plenty.

3. API

HTTP
POST /api/v1/urls        { "long_url": "https://...", "alias": "optional", "expires_at": "optional" }
→ 201 { "short_url": "https://sho.rt/aZ3kP9q" }

GET /aZ3kP9q
→ 301/302 Location: https://...

301 (permanent) lets browsers cache the redirect — less load, but you lose click analytics. 302 (temporary) sends every click through you. Choose 302 if analytics matter.

4. High-level design

UsersLoad balancerApp serversstatelessRedis cachecode → URLKV / SQL storesharded by codeID generator

5. Generating short codes

ApproachHowProsCons
Hash + truncatebase62(md5(long_url))[0:7]Same URL → same code; no coordinationCollisions: check and retry with a salt
Global counter + base62Unique integer ID → base62No collisions, short codesNeed a distributed counter; sequential codes are guessable
Counter rangesEach server leases a block of 1M IDs from a coordinator (ZooKeeper/DB)No per-request coordinationUnused IDs lost on crash (harmless)
Pre-generated key serviceOffline-generate random codes into a table; hand them outRandom, unique, fastExtra service and storage
Snowflake-style IDsTimestamp + machine ID + sequenceDecentralisedLonger codes (~11 chars)
Base62 encoding
static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

static String encode(long n) {
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    while (n > 0) { sb.append(ALPHABET.charAt((int) (n % 62))); n /= 62; }
    return sb.reverse().toString();
}

To make sequential IDs non-guessable, permute the ID first (multiply by a large odd constant modulo 62⁷, or a small block cipher) before encoding.

6. Data model

SQL
CREATE TABLE urls (
  code        VARCHAR(10) PRIMARY KEY,
  long_url    TEXT NOT NULL,
  user_id     BIGINT,
  created_at  TIMESTAMP NOT NULL,
  expires_at  TIMESTAMP
);

Access is a pure key lookup, so a key-value store (DynamoDB, Cassandra) or sharded SQL both work. Shard by code (hash), which spreads load evenly.

7. The read path

  1. GET /aZ3kP9q hits a stateless app server.
  2. Look up aZ3kP9q in Redis. URLs follow a power law — a small fraction gets most clicks — so a cache of the hot 20% absorbs most reads.
  3. On a miss, read from the database and populate the cache (cache-aside, with a TTL).
  4. Return 302 with the Location header; asynchronously publish a click event.
  5. Missing or expired codes return 404. Cache negative results briefly to stop repeated lookups for junk codes.

8. Analytics

Don't write to the database on every click. Publish click events (code, time, referrer, country, user agent) to Kafka, aggregate with a stream processor, and store counts in a columnar/analytics store.

9. Further concerns

  • Abuse: rate-limit creation, scan long URLs against malware/phishing lists.
  • Custom aliases: check uniqueness with a conditional insert.
  • Expiry: lazy deletion on read plus a background cleanup job.
  • Availability: replicate the DB, multi-region read replicas plus CDN/edge caching of redirects.
Key takeaways
  • Read-heavy: optimise the redirect path with caching; 7 base62 characters give 3.5 trillion codes.
  • Key generation: counter ranges + base62 (unique, no collisions) or hash + collision check.
  • 302 keeps analytics; 301 reduces load.
  • Simple key-value data model, sharded by code.
  • Clicks go through a queue to an analytics pipeline, not the primary DB.