Skip to content
Visual explainer 3h to learn 5 steps

URL shortener

Design ID generation, redirects, caching and analytics for billions of links.

By Invicly Tech, , in System Design Deep Dive. About 9 minutes to read.

Topic 22 of 33

In short

A URL shortener maps short codes to long URLs and redirects billions of clicks. It is read-heavy, so the key choices are collision-free ID generation, a fast key-value lookup, aggressive caching and asynchronous analytics.

Explained simply

A URL shortener turns a long web address into a tiny one, like invic.ly/aZ3kP9. When someone opens the short link, the service looks up the long address and sends the browser there. Bitly and TinyURL work this way.

Think of it as a coat check. You hand over your coat (the long URL) and get a small ticket (the short code). Later, anyone with the ticket gets the same coat back. The service only has to do two jobs well: hand out tickets that never clash, and find the coat fast.

The tricky part is scale. A popular service might create a hundred million links a day but serve a hundred times more redirects. So the design is built around reading quickly: a fast lookup table, a cache in memory for popular links, and doing slow work like counting clicks in the background.

Press Play on a diagram to walk through it one step at a time.

FlowHigh-level architecture
  1. 1
    Client

    Creates links or clicks short URLs

  2. 2
    Load balancer

    Spreads traffic over stateless API servers

  3. 3
    API service

    Create and redirect endpoints

  4. 4
    Redis cache

    Hot code-to-URL mappings

  5. 5
    Key-value DB

    Durable code to long URL store

  6. 6
    Analytics stream

    Click events to Kafka, then warehouse

SequenceRedirect request
Browser
API server
Redis
Database
  1. 1GET /aZ3kP9
    Browser to API server: GET /aZ3kP9
  2. 2GET code aZ3kP9
    API server to Redis: GET code aZ3kP9
  3. 3Miss
    Redis to API server: Miss
  4. 4Lookup long URL
    API server to Database: Lookup long URL
  5. 5https://example.com/...
    Database to API server: https://example.com/...
  6. 6Cache mapping with TTL
    API server to Redis: Cache mapping with TTL
  7. 7302 Location: long URL
    API server to Browser: 302 Location: long URL
SequenceCreating a short link
User
API server
ID allocator
Database
  1. 1POST long URL
    User to API server: POST long URL
  2. 2Need IDs (only when block runs out)
    API server to ID allocator: Need IDs (only when block runs out)
  3. 3Block 1000–1999
    ID allocator to API server: Block 1000–1999
  4. 4Save code → long URL
    API server to Database: Save code → long URL
  5. 5201 short link
    API server to User: 201 short link
LayersWhere each request is answered
  1. 1
    CDN / edge

    Optional: cache the hottest redirects worldwide

  2. 2
    Load balancer

    Spreads traffic across app servers

  3. 3
    App servers

    Stateless; easy to add more

  4. 4
    Redis cache

    Answers most redirects in about 1 ms

  5. 5
    Key-value database

    Source of truth for code → URL

In depth

Making short codes that never clash

Every link needs a unique code. The simplest reliable approach is a counter: each new link gets the next number, and you convert that number to base 62 (digits plus lowercase and uppercase letters). Seven base-62 characters give about 3.5 trillion codes, which lasts decades.

One counter on one server becomes a bottleneck and a single point of failure. So each app server reserves a block of numbers at a time, say 1,000, from a small coordination service. It hands those out locally with no network call, and only asks for a new block when it runs out.

  • Counter + base62: short, unique, no collisions
  • Block allocation removes the single-counter bottleneck
  • Random codes need a collision check on every insert

The redirect path has to be fast

Most traffic is people clicking links, so the read path matters most. The request hits a load balancer, then a stateless app server, which first checks an in-memory cache like Redis. A cache hit answers in about a millisecond. On a miss, the server reads the key-value database, stores the result in the cache with an expiry time, and replies.

Because a small share of links get most of the clicks, even a modest cache absorbs the bulk of the load and keeps the database calm.

301 or 302?

A 301 redirect says "moved permanently", so browsers remember it and may skip your server next time. That is cheaper, but you stop seeing those clicks. A 302 says "moved temporarily", so every click comes back to you. Services that sell click analytics use 302.

  • 301: faster for users, fewer requests, weaker analytics
  • 302: every click counted, slightly more load
Compare301 vs 302 for a short link
301 Moved Permanently
  • Browser remembers the answer
  • Later clicks may skip your server
  • Cheaper to serve
  • Weaker click analytics
302 Found (temporary)
  • Browser asks again every time
  • Every click reaches your server
  • Every click can be counted
  • Slightly more load

Counting clicks without slowing anyone down

Writing to an analytics table on every redirect would make clicks slow and could take the redirect service down during a traffic spike. Instead, the server drops a small event onto a queue such as Kafka and replies immediately. Separate workers read the queue and update counts and reports in a data warehouse. If analytics falls behind, redirects keep working.

FlowCounting a click off the hot path
  1. 1
    Redirect request

    Code looked up

  2. 2
    Drop an event

    Small click event onto Kafka

  3. 3
    Reply at once

    302 sent, user moves on

  4. 4
    Workers consume

    Read events at their own pace

  5. 5
    Update reports

    Counts in a data warehouse

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Clarify requirements and estimate scale~35m
  2. 2
    Design the API~35m
  3. 3
    Generate short IDs without collisions~35m
  4. 4
    Design storage, redirects and caching~35m
  5. 5
    Add click analytics and discuss trade-offs~35m

Key points

  • Base62 with 7 characters gives about 3.5 trillion codes.
  • Generate IDs from a counter or ID ranges, then base62-encode, to avoid collisions.
  • Use 302 to count every click; 301 lets browsers cache and skip you.
  • Reads dominate, so cache hot codes and scale reads horizontally.
  • Log clicks asynchronously so analytics never slows redirects.

Key terms

Tap a card to flip it. 0/5 known

Examples

text
POST /api/links { "url": "https://...", "alias"?: "sale" }
  -> 201 { "code": "aZ3kP9" }
GET  /{code} -> 302 Location: long URL

Table links(code PK, long_url, user_id, created_at, expires_at)

Scale: 100M new links/day -> ~1,200 writes/s
  read:write 100:1 -> ~120,000 redirects/s
  500 bytes/link * 100M * 365 * 5 ≈ 90 TB
62^7 ≈ 3.5 trillion codes, enough for decades

API, schema and back-of-envelope math.

Turning a number into a short code

Say the next counter value is 125. In base 62, 125 = 2 × 62 + 1, so the digits are [2, 1]. Using the alphabet 0-9, a-z, A-Z, digit 2 is "2" and digit 1 is "1", giving the code "21". Bigger numbers simply produce longer codes, so we pad to 7 characters for a consistent look.

python
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))

print(encode(125))         # 21
print(encode(3_500_000_000_000))

Back-of-the-envelope sizing

Assume 100 million new links a day. That is about 1,200 writes per second. With a 100:1 read-to-write ratio, redirects run at about 120,000 per second. If each stored link takes 500 bytes, five years of links is 100M × 365 × 5 × 500 B ≈ 91 TB. These numbers tell you that reads need a cache and that storage must be spread across several machines.

Quick reference

  • Base62 alphabet: 0-9 a-z A-Z (62 characters)
  • 62^7 ≈ 3.5 trillion possible 7-character codes
  • 100M writes/day ≈ 1,200 writes per second
  • Read:write is often 100:1, so design for reads
  • 302 = count every click; 301 = cheaper, cached by browsers
  • Cache hot codes in Redis with a TTL
  • Send click events to a queue; never block the redirect

Common mistakes

  • Truncating MD5 hashes without handling collisions.
  • A single global counter becoming a bottleneck; use ranges instead.
  • Writing analytics synchronously on the redirect path.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why do app servers reserve a block of IDs instead of asking a central counter for every new link?

Question 2

2Which redirect status lets the service count every click?

Question 3

3Roughly how many unique codes do 7 base62 characters give?

Question 4

4Where should click analytics be written?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a function decode(code) that turns a base62 short code back into its number. Check that decode(encode(n)) == n for n = 0, 61, 62 and 999999.

  2. Exercise 2medium

    Design the database table for links. Include the columns, primary key, and one index, and explain how you would expire links after a chosen date.

  3. Exercise 3hard

    A celebrity tweets one short link and it gets 50,000 clicks per second. Explain what breaks first in a cache-plus-database design and how you would protect the system.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can two long URLs get the same short code?
Not with a counter-based design: every number is used once, so every code is unique. Random codes can collide, so they need a check before saving.
Should the same long URL always get the same short code?
It is optional. Reusing codes saves space but needs a lookup by long URL on every create. Many services create a new code each time so each one can have its own analytics.
Which database is best for a URL shortener?
Any store that does fast lookups by key and scales horizontally works: DynamoDB, Cassandra, or sharded PostgreSQL. The access pattern is simple key-value.
ShareXLinkedInWhatsApp