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.
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.
- 1Client
Creates links or clicks short URLs
- 2Load balancer
Spreads traffic over stateless API servers
- 3API service
Create and redirect endpoints
- 4Redis cache
Hot code-to-URL mappings
- 5Key-value DB
Durable code to long URL store
- 6Analytics stream
Click events to Kafka, then warehouse
- Browser to API server: GET /aZ3kP91GET /aZ3kP9
- API server to Redis: GET code aZ3kP92GET code aZ3kP9
- Redis to API server: Miss3Miss
- API server to Database: Lookup long URL4Lookup long URL
- Database to API server: https://example.com/...5https://example.com/...
- API server to Redis: Cache mapping with TTL6Cache mapping with TTL
- API server to Browser: 302 Location: long URL7302 Location: long URL
- User to API server: POST long URL1POST long URL
- API server to ID allocator: Need IDs (only when block runs out)2Need IDs (only when block runs out)
- ID allocator to API server: Block 1000–19993Block 1000–1999
- API server to Database: Save code → long URL4Save code → long URL
- API server to User: 201 short link5201 short link
- 1CDN / edge
Optional: cache the hottest redirects worldwide
- 2Load balancer
Spreads traffic across app servers
- 3App servers
Stateless; easy to add more
- 4Redis cache
Answers most redirects in about 1 ms
- 5Key-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
- Browser remembers the answer
- Later clicks may skip your server
- Cheaper to serve
- Weaker click analytics
- 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.
- 1Redirect request
Code looked up
- 2Drop an event
Small click event onto Kafka
- 3Reply at once
302 sent, user moves on
- 4Workers consume
Read events at their own pace
- 5Update reports
Counts in a data warehouse
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Clarify requirements and estimate scale~35m
- 2Design the API~35m
- 3Generate short IDs without collisions~35m
- 4Design storage, redirects and caching~35m
- 5Add 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
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 decadesAPI, 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.
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.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- 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.
- 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.
- 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.