Course contentsShow
← System Design
Lesson 1512 of 1,91937. Real-World System: URL ShortenerFree lesson

Random String Generation

Generate random Base62 strings and check for existence in the database, with retry logic for rare collisions.

Random String Generation

What you'll learn: How to safely generate short URLs by creating random Base62 strings and handling the rare case when two URLs collide.

The Core Idea

Instead of hashing long URLs or coordinating distributed ID counters, we can simply generate random Base62 strings and check if they already exist in our database. If we hit a collision (extremely rare), we retry with a new random string.

For a 7-character Base62 string, we have 62^7 ≈ 3.5 trillion possibilities. With even millions of URLs stored, collision probability remains vanishingly small—but we still need retry logic for safety.

How It Works

When a user submits a long URL:

  1. Generate a random 7-character string from the Base62 alphabet ([A-Za-z0-9])
  2. Check existence in the database with a quick lookup
  3. If collision detected, generate a new random string and retry
  4. Insert the new short URL mapping once unique

Think of it like picking lottery numbers: with trillions of combinations and only millions occupied, you'll almost never pick a duplicate—but you still verify before claiming your ticket.

Advantages

  • No coordination needed between servers
  • Stateless: each server generates independently
  • Simple implementation: just random number generation + DB check
  • Predictable failure mode: retry loop handles edge cases

Retry Logic

maxRetries = 3
for attempt in 1 to maxRetries:
    shortCode = generateRandom(7)
    if not existsInDB(shortCode):
        return shortCode
throw "Unable to generate unique code"

After 3 collisions in a row (astronomically unlikely), we fail gracefully.

Key Takeaway: Random Base62 generation with collision checking offers a stateless, simple approach to short URL creation—trading extremely rare retries for zero coordination overhead.