TExcelTAD
Home › System Design › Design a URL Shortener

Design a URL Shortener

A URL shortener turns https://shop.example.com/products/2026/spring-sale?utm_source=newsletter&utm_campaign=april into https://sho.rt/3fZk9Qa and redirects anyone who opens the short link. It's the classic first system design problem: small enough to finish, but it touches estimation, id generation, caching, databases and analytics.

1. Requirements

Functional

  • Create a short link for a long URL (optionally with a custom alias and an expiry date).
  • Opening a short link redirects to the long URL.
  • Basic click counts per link.

Non-functional

  • Redirects are the hot path: very low latency (p99 < 20 ms at the edge) and very high availability (99.99%).
  • 100 million new links per month; links never collide and are hard to guess in sequence.
  • Read-heavy: about 100 redirects per created link.

2. Estimates

python · try it yourself
links_per_month = 100_000_000
reads_per_link = 100
seconds_per_month = 30 * 86_400
years = 10
record_bytes = 500              # short code, long URL (~200 B), owner, timestamps, indexes

write_qps = links_per_month / seconds_per_month
read_qps = write_qps * reads_per_link
total_links = links_per_month * 12 * years
storage_tb = total_links * record_bytes / 1e12

print(f"writes: {write_qps:,.0f}/s avg   reads: {read_qps:,.0f}/s avg, ~{2 * read_qps:,.0f}/s peak")
print(f"links in {years} years: {total_links:,}")
print(f"storage: {storage_tb:.1f} TB (before replication)")

# How long must the code be? Base62 alphabet: 0-9, a-z, A-Z
for length in [6, 7, 8]:
    print(f"{length} base62 characters -> {62 ** length:,} codes ({62 ** length / total_links:,.0f}x what we need)")
writes: 39/s avg   reads: 3,858/s avg, ~7,716/s peak
links in 10 years: 12,000,000,000
storage: 6.0 TB (before replication)
6 base62 characters -> 56,800,235,584 codes (5x what we need)
7 base62 characters -> 3,521,614,606,208 codes (293x what we need)
8 base62 characters -> 218,340,105,584,896 codes (18,195x what we need)

Seven characters give 3.5 trillion codes, almost 300 times what ten years need (six would be cutting it close). The data (6 TB) fits a sharded key-value store or a few database shards easily; the hard part is serving ~7,700 redirects per second at peak (and far more during viral spikes) with low latency everywhere in the world.

3. High-level design

text
create:  client -> API -> id generator -> encode base62 -> store (code -> long URL)
redirect: client -> CDN/edge -> redirect service -> cache (Redis) -> store
                                      |
                                      +--> click event -> queue -> analytics workers

API

text
POST /api/links   {"url": "https://...", "alias": null, "expires": "2027-01-01"}
  -> 201 {"code": "3fZk9Qa", "short_url": "https://sho.rt/3fZk9Qa"}
GET /3fZk9Qa      -> 301/302 Location: https://...

301 or 302? A 301 Moved Permanently is cached by browsers, so repeated clicks never reach us: cheaper, but we lose click counts and can't change the target. A 302 Found (or 307) keeps every click visible. Most shorteners with analytics use 302.

4. Generating short codes

Three common options:

Option How Pros Cons
Hash the URL base62(md5(url))[:7] Same URL → same code Collisions must be detected and retried
Counter + base62 A unique 64-bit id (Snowflake, or ranges from a ticket server) encoded in base62 No collisions, no lookups Sequential codes are guessable unless shuffled
Random code 7 random base62 characters, insert-if-absent Unguessable Needs a uniqueness check on every insert

Here's the counter approach, with a reversible shuffle (multiply by a large odd constant modulo 62^7) so consecutive ids don't produce consecutive codes:

python · try it yourself
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
SPACE = 62 ** 7
MULTIPLIER = 1_963_741_851_003      # odd and not a multiple of 31: coprime with 62^7, so a bijection
INVERSE = pow(MULTIPLIER, -1, SPACE)

def encode(n, length=7):
    chars = []
    for _ in range(length):
        n, r = divmod(n, 62)
        chars.append(ALPHABET[r])
    return "".join(reversed(chars))

def decode(code):
    n = 0
    for ch in code:
        n = n * 62 + ALPHABET.index(ch)
    return n

def id_to_code(link_id):
    return encode(link_id * MULTIPLIER % SPACE)

def code_to_id(code):
    return decode(code) * INVERSE % SPACE

for link_id in [1, 2, 3, 1_000_000]:
    code = id_to_code(link_id)
    print(f"id {link_id:>9} -> {code} -> back to {code_to_id(code)}")
id         1 -> yzvKGhl -> back to 1
id         2 -> 791vmyG -> back to 2
id         3 -> FIxg2Q1 -> back to 3
id   1000000 -> qw6lWBG -> back to 1000000

Ids come from range allocation: each API server reserves a block of, say, 10,000 ids from a central counter (one database row updated with UPDATE ... SET next = next + 10000), then hands them out locally. The counter is touched once per 10,000 links, so it's never a bottleneck; a crashed server just wastes the rest of its block.

5. The redirect path

Redirect traffic is extremely skewed: a few links (a viral tweet) get most clicks. A cache in front of the store absorbs them. Let's model it with a seeded Zipf-like workload and an LRU cache:

python · try it yourself
import random
from collections import OrderedDict
from itertools import accumulate

rng = random.Random(42)
N_LINKS = 100_000
CUM = list(accumulate(1 / (k ** 1.1) for k in range(1, N_LINKS + 1)))   # popularity ~ 1/k^1.1

def simulate(cache_size, requests=200_000):
    cache, hits = OrderedDict(), 0
    for link in rng.choices(range(N_LINKS), cum_weights=CUM, k=requests):
        if link in cache:
            hits += 1
            cache.move_to_end(link)
        else:
            cache[link] = True
            if len(cache) > cache_size:
                cache.popitem(last=False)
    return hits / requests

for size in [1_000, 10_000, 50_000]:
    print(f"cache {size:>6} links ({size / N_LINKS:4.0%} of all): hit ratio {simulate(size):.1%}")
cache   1000 links (  1% of all): hit ratio 66.3%
cache  10000 links ( 10% of all): hit ratio 83.1%
cache  50000 links ( 50% of all): hit ratio 86.4%

Caching just 1% of the links already serves most redirects from memory. Popular links can also be cached at the CDN edge with a short TTL.

Click counting must not slow the redirect down: the redirect service emits a small event to a queue and returns immediately; workers aggregate counts per link per minute and write them in batches.

6. Data model and storage

text
links:  code (PK) | long_url | owner_id | created_at | expires_at

The only query on the hot path is "get by code", a perfect fit for a key-value store (DynamoDB, Cassandra) or a sharded SQL table partitioned by code. A secondary index on owner_id serves the "my links" page.

Trade-offs and extensions

Decision Choice Why
Code generation Counter ranges + shuffle No collisions, no lookup on insert
Redirect status 302 Keeps analytics and lets owners edit the target
Store Key-value, partitioned by code Single-key reads, horizontal scaling
Analytics Async via a queue Redirect latency unaffected

Extensions to discuss: custom aliases (check uniqueness, reserve offensive words), expiry (a TTL index or a background cleanup job), abuse (scan new URLs against malware lists, rate-limit creation per user), and multi-region active-active redirects.

Test yourself

Why do many URL shorteners return 302 instead of 301?

  1. 302 is faster
  2. Browsers cache 301 permanently, so later clicks bypass the service and can't be counted
  3. 301 is deprecated
  4. 302 responses are smaller

How many distinct codes do 7 base62 characters allow?

  1. About 62 million
  2. About 3.5 billion
  3. About 3.5 trillion
  4. About 62 trillion

What does range allocation of ids achieve?

  1. Codes become shorter
  2. Servers hand out ids locally and contact the central counter only once per block
  3. Ids become random
  4. It removes the need for a database