πŸ’¬
βœ‰οΈ
πŸ“Έ
▢️

Loading…

Design a URL Shortener (TinyURL): Interactive System Design

URL ShortenerGuided Mode

Step 2 β€” Generating Short Codes

How does the API Server produce a unique 6-character code for every URL?

Request Flow

1

Option A β€” Hash the URL

Take MD5/SHA256 of the long URL β†’ encode first 6 chars in base62 (0–9, a–z, A–Z). Same URL always produces the same code β€” natural deduplication.

hash = md5("https://long.com/url")  // 128-bit
code = base62(hash[:4])           // β†’ "xK3mP2"
2

Collision risk with hashing

Two different URLs can produce the same 6-char hash (birthday paradox). You must CHECK the Database for duplicates and retry on conflict.

3

Option B β€” Random ID

Generate a random 6-char base62 string. With 62⁢ = 56 billion possibilities, collisions are extremely rare. Check DB, re-roll on conflict.

function randomCode() {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let code = '';
  for (let i = 0; i < 6; i++)
    code += chars[Math.floor(Math.random() * 62)];
  return code;
}
4

Option C β€” Auto-increment counter (most scalable)

Maintain a global counter. With alphabet 0–9, a–z, A–Z, counter 1000 β†’ base62 β†’ "g8". Guaranteed unique while counter values are never reused and codes are not truncated.

// alphabet = 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
// counter = 1,000,000,000
base62(1_000_000_000)  // β†’ "15FTGg"
// Unique counter values produce unique, untruncated codes

Key Insight

Base62 with 6 characters gives 56 billion unique codes. Use a counter (not a hash) at scale β€” it's guaranteed unique and requires no collision checking.

Step 2 of 6