Design a URL shortener with base62 codes

Backend Live Coding November 13, 2026 python

Requirements: far more reads than writes (e.g.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# ======================================================================
# Q: Design a URL shortener.
#
# Requirements: far more reads than writes (e.g. 100:1), low redirect latency,
# unique short codes. Code: base62 of the auto-increment id (short, collision-
# free, but predictable) or a random 7-character code with a unique constraint
# and retry. Storage: PostgreSQL with a unique index on the code. Read path:
# Redis cache (code -> URL), 301 or 302 (302 allows analytics). Analytics:
# clicks are not written synchronously to the database. They go to a queue and
# are batch inserted. Other concerns: link expiry, rate limiting on creation,
# checking for malicious URLs.
# ======================================================================

ALPHABET = string.digits + string.ascii_letters      # 62 characters

def base62(n: int) -> str:
    s = []
    while True:
        n, rem = divmod(n, 62)
        s.append(ALPHABET[rem])
        if n == 0:
            return ''.join(reversed(s))