Generating Short Codes for a URL Shortener: Base62, Hashing and Counters
Compare short code strategies: hashing with collision handling, random codes, auto-increment counters with Base62, Snowflake IDs and pre-generated key ranges...
Published November 27, 2026
The heart of a URL shortener is turning each new link into a short, unique code like aZ3kP9q. There are several ways to do it, each with a different mix of simplicity, collision risk, coordination cost and guessability. This article compares them and shows working code for each.
The concept
Base62 encoding is the building block for most approaches. It uses the characters 0-9, a-z and A-Z: 62 symbols that are all URL-safe. Encoding a number in base 62 gives a short string: one billion needs only 6 characters, and 7 characters cover about 3.5 trillion values.
The real question is where the number (or bytes) comes from. You can hash the URL, generate random bits, use a global counter, or combine a machine ID with a timestamp. Hashing and random approaches need collision checks. Counters never collide but need coordination and produce predictable sequences unless you scramble them.
Strategies compared
| Approach | Collisions | Coordination | Guessable? | Notes |
|---|---|---|---|---|
| Hash (MD5/SHA-256) + truncate | Possible: check and retry | None | No | Same URL → same code (dedup for free) |
| Random 7 chars | Rare: check and retry | None | No | Simplest; retry rate grows as space fills |
| DB auto-increment + Base62 | Never | Single DB sequence | Yes (sequential) | Bottleneck at very high write rates |
| Counter ranges (key service) | Never | Lease a range occasionally | Yes unless scrambled | Each server hands out its own block |
| Snowflake-style IDs | Never | Unique machine IDs | Partially (time-ordered) | Longer codes (~11 chars) |
Counter ranges avoid a hot sequence
Base62 encoding
Repeatedly divide by 62 and map each remainder to a character. Decoding reverses it.
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out))
def decode(s: str) -> int:
n = 0
for ch in s:
n = n * 62 + ALPHABET.index(ch)
return n
print(encode(125), encode(3_500_000_000_000)) # 21 ZCpdjxe (7 chars)Random codes: collisions vs fill level
Practical examples
Random codes with a uniqueness retry
Use a cryptographically secure generator so codes are not predictable.
import secrets
def new_code(n=7):
return "".join(secrets.choice(ALPHABET) for _ in range(n))
def create(db, long_url):
for _ in range(5):
code = new_code()
if db.insert_if_absent(code, long_url): # conditional insert
return code
raise RuntimeError("could not allocate code")Hash-based codes
Take 41 bits of a SHA-256 hash (2^41 < 62^7, so the code always fits in 7 Base62 chars). Add a salt to resolve collisions.
import hashlib
def hash_code(url: str, salt: int = 0) -> str:
digest = hashlib.sha256(f"{url}#{salt}".encode()).digest()
n = int.from_bytes(digest[:6], "big") >> 7 # 41 bits
return encode(n).rjust(7, "0")Scramble sequential IDs
Multiply by a large odd constant modulo 62^7 so consecutive IDs give unrelated-looking codes (reversible with the modular inverse).
M = 62 ** 7
A = 1_580_030_173 # odd, coprime with M
def scramble(n): return (n * A) % M
print(encode(scramble(1000001)), encode(scramble(1000002)))Common mistakes
- Truncating a hash without handling collisions; with billions of links they will happen.
- Using Math.random or a non-cryptographic PRNG for codes that should be unguessable.
- A single global auto-increment sequence on the critical path of every write at very high scale.
- Exposing raw sequential IDs that reveal how many links exist and let anyone enumerate them.
- Including easily confused characters (0/O, l/1/I) when codes are meant to be typed by humans; consider a reduced alphabet.
Key takeaways
- Base62 turns numbers into short URL-safe strings; 7 characters cover ~3.5 trillion values.
- Random and hash-based codes need a collision check, ideally a conditional insert.
- Counter ranges give collision-free codes without a central bottleneck.
- Scramble sequential IDs if codes must not be guessable.
FAQ
Is MD5 OK for hashing URLs here?
Yes. This is not a security use; you only need a well-distributed number. The collision handling is what matters.
Which approach do large shorteners use?
Many use a key generation service that pre-generates or leases ranges, combined with random or scrambled encoding, because it avoids both collisions and hot spots.
Why not Base64?
Standard Base64 includes + and /, which are not URL-safe. URL-safe Base64 uses - and _, which works but looks less clean in links; Base62 avoids punctuation entirely.