Skip to main content
01

Design a URL shortener (like bit.ly)

MediumHashingKey generationCachingRead-heavy

Design a URL shortener like bit.ly or TinyURL: users submit a long URL and get a short link such as https://sho.rt/aZ3kQ9x; anyone opening the short link is redirected to the original URL.

A typical framing: "100 million new links per month, and reads outnumber writes 100 to 1. Redirects must be fast everywhere in the world. Links can have a custom alias and an expiry, and we want click analytics."

TL;DR

It's a read-heavy key-value lookup: short code → long URL. The interesting choices are how to generate codes and how to serve redirects fast.

Generate codes by base62-encoding a unique number from a distributed ID source (a counter handed out in ranges to each server, or Snowflake-style IDs), or by hashing the URL and resolving collisions. Seven base62 characters give 62⁷ ≈ 3.5 trillion codes. Store mappings in a horizontally scalable key-value store sharded by code. Serve redirects through CDN and cache layers (most traffic goes to a small set of hot links) and return 302 if you need analytics, 301 if you want browsers to cache. Send click events asynchronously to a queue for analytics, so the redirect path stays a single cache lookup.

1. Requirements and estimates

Functional

  • Create a short URL for a long URL, optionally with a custom alias and an expiry.
  • Redirect a short URL to the original.
  • Click analytics per link (counts, referrers, countries).

Non-functional

  • Redirect latency in the low milliseconds, high availability (a broken link breaks someone's campaign).
  • Codes are not guessable in sequence (optional, but usually wanted).
  • Durable: links must not disappear.

Estimates

  • Writes: 100M / month ≈ 40 per second (peaks maybe 10×).
  • Reads: 100× → ≈ 4,000 redirects per second, peaks of tens of thousands.
  • Storage: ~500 bytes per link × 100M × 12 months × 5 years ≈ 3 TB. Large but easy to shard.
  • Codes: 6B links in 5 years; 62⁷ ≈ 3.5T, so 7 characters are plenty.

2. API

http
POST /v1/links      { longUrl, alias?, expiresAt? }   -> 201 { code, shortUrl }
GET  /{code}                                         -> 302 Location: <longUrl>   (404 or 410 if expired)
GET  /v1/links/{code}/stats?from=&to=
DELETE /v1/links/{code}

3. Data model

text
links (key-value, partitioned by code)
  code        PK   "aZ3kQ9x"
  long_url         "https://example.com/very/long/path?utm=..."
  owner_id
  created_at
  expires_at       nullable

clicks (append-only, analytics store)
  code, timestamp, country, referrer, user_agent_hash

A key-value or wide-column store (DynamoDB, Cassandra) fits naturally: every access is by primary key and there are no joins. A relational database sharded by code also works fine at this size.

4. High-level architecture

Loading diagram...
  • Redirect service: stateless; looks up the code in the cache, then the database, and responds with the redirect. Separate from the write path so a spike in creations can't slow redirects.
  • Link service: validates the URL, generates a code, writes the mapping.
  • Click events go to a queue (Kafka) and are aggregated by workers into an analytics store (ClickHouse, BigQuery).

5. Deep dives and scaling

Generating codes

ApproachHowProsCons
Counter + base62A unique integer encoded as base62No collisions, short codesNeeds a distributed counter; sequential codes are guessable
Range allocationEach server reserves a block (e.g. 1M ids) from a coordinator (ZooKeeper, a DB row)No coordination per requestA crashed server wastes the rest of its block (harmless)
Hash (MD5/SHA) + truncateFirst 7 characters of the hash's base62Same URL → same code (dedupe for free)Collisions: check and retry with a salt
Random7 random base62 charactersUnguessableCollision check on insert (a conditional put)

A common answer: range allocation for uniqueness, and shuffle the number (a reversible bit permutation or a small block cipher) before base62 encoding, so codes don't look sequential. Custom aliases are inserted with a conditional write ("only if not exists"), and a 409 if taken.

Fast redirects

  • Link popularity follows a power law: caching the top few percent of links in Redis serves the vast majority of requests. Use LRU eviction.
  • Cache at the CDN edge too, for the hottest links.
  • 301 vs. 302: 301 is permanent, so browsers and caches may never ask again, which loses analytics and makes edits or expiry impossible to enforce. Most shorteners use 302 (or 307).
  • Negative caching: briefly cache "not found" for codes that don't exist, so bots scanning random codes don't reach the database.

Expiry and cleanup

Check expires_at on read and return 410 Gone. Delete expired rows lazily or with a TTL feature of the store (DynamoDB and Cassandra support TTL).

Abuse

Shorteners are used for phishing and spam. Check submitted URLs against blocklists (e.g. Google Safe Browsing), rate-limit creation per user and IP, and support taking links down.

Common follow-ups

  • "Same long URL submitted twice: same code?" Optional. Per user it's nice (a lookup by hash(longUrl, userId)), but globally it leaks information and breaks per-link analytics.
  • "How do you shard?" By code (hash partitioning). Every redirect touches exactly one shard.
  • "How would analytics stay accurate under load?" The redirect never waits on analytics; events are buffered and counted asynchronously, accepting a short delay in the stats.

What interviewers look for

  • Back-of-the-envelope estimates that drive the design (read-heavy, code length, storage).
  • A reasoned code-generation strategy and how collisions or guessability are handled.
  • Caching layers and the 301 vs. 302 trade-off.
  • Separating the redirect path from writes and analytics.
  • Expiry, custom aliases and abuse prevention.

Was this helpful?