Design TinyURL
Before this, it helps to know: Numbers Every Beginner Should Know, Caching Basics, Replication & Sharding.
Read a little, play a little. No scary maths, and no rush.
The problem
Someone sends you a 200-character tracking link. It breaks in SMS, looks like spam, and nobody can type it. A URL shortener turns https://shop.example.com/products/summer-sale?utm_source=sms&utm_campaign=july into https://tiny.url/aZ3x9Qk. Open the short link and you land on the long one.
Interviewers like this question because it is small enough to finish in 45 minutes but touches APIs, ID generation, databases, caching and scale math. This lesson walks through it in the order a good interview answer takes. Each step starts with the basics; the Going deeper parts are what separates a mid-level answer from a senior one.
Step 1: Requirements
Before drawing anything, agree on what you are building. Write two short lists.
Try it first: what would you put on each list?
Functional (what it does):
- Create a short link from a long URL, optionally with a custom alias (
tiny.url/summer-sale). - Open a short link and get redirected to the long URL.
- Optionally, links expire after a date the creator picks.
Non-functional (how well it does it):
- Redirects are fast: well under 100 ms on the server side, because a person is waiting.
- Redirects almost never fail. Availability matters more than strict consistency: if a brand-new link takes a second to work everywhere, nobody is hurt.
- Short codes are unique. Two long URLs must never share a code.
- It scales to billions of links.
Say out loud what you are not building: user accounts, a link dashboard, spam detection. Naming what is out of scope keeps the 45 minutes on the core problem.
Step 2: Estimates
Use round numbers. The aim is to learn the shape of the system, not to be exact.
- Writes: 10 million new links a day ÷ ~86,400 seconds ≈ 120 per second, maybe 500 at peak.
- Reads: each link opened ~10 times ≈ 100 million redirects a day ≈ 1,200 per second, a few thousand at peak.
- Storage: ~500 bytes per row × 10 million a day ≈ 5 GB a day, about 2 TB a year.
- Code length: over 10 years that is ~36 billion links. Base62 (
0-9,a-z,A-Z) with 6 characters gives 62⁶ ≈ 57 billion codes; 7 characters give ≈ 3.5 trillion. Pick 7 for headroom.
The headline: reads outnumber writes about ten to one. This is a read-heavy system, so the redirect path must be cheap. That one observation drives most of what follows.
Step 3: Core entities and API
There is one main thing to store, a link:
links
short_code (primary key, e.g. "aZ3x9Qk")
long_url
created_at
expires_at (nullable)
And two endpoints:
POST /urls { "url": "https://long...", "alias": "summer-sale", "expires_at": null }
→ 201 { "short_url": "https://tiny.url/summer-sale" }
GET /{code} → 302 Found, Location: https://long...
→ 404 if unknown or expired
Rate-limit POST /urls per user or IP so one script cannot mint a billion links overnight. (That is its own design problem: see the rate limiter lesson.)
Step 4: High-level design
Start with the simplest thing that works, then improve it.
Creating a link: the service generates a short code (Step 5 is all about how), inserts the row, and returns the short URL. If the user asked for an alias, insert it as the code; the primary key rejects it if it is taken, and you return 409 Conflict.
Following a link: the service looks up the code, checks expires_at, and answers with a redirect.
301 or 302?
Both redirect, but they behave differently:
- 301 Moved Permanently: browsers cache it. Repeat clicks go straight to the long URL without touching your servers. Less load, but you cannot count those clicks, and you cannot change or expire the link for anyone who already cached it.
- 302 Found: not cached by default. Every click reaches you, so you can count clicks and expire links reliably. More traffic, which the cache in Step 6 absorbs.
There is no single right answer. Say which you pick and why: "302, because we want click counts and working expiry."
Step 5: Deep dive — generating short codes
This is the heart of the problem. Here are three options, from weakest to strongest.
Bad: hash the long URL and keep the first 7 characters. Hash with MD5 or SHA-256, encode in base62, truncate. The appeal is that the same URL always gets the same code. The problem is collisions: with tens of billions of links, different URLs sharing a 7-character prefix becomes routine (the birthday problem). So every insert needs a check, and a retry with a tweak, which is slower and more complex than it looked.
Good: a random 7-character code, checked for uniqueness. With 3.5 trillion possible codes and a few billion used, a clash is rare, and the database's primary key catches it; you retry with a new random code. Codes are unguessable, which is a nice property. The cost is that every write might retry, and the check gets more expensive as the table fills.
Great: a counter, encoded in base62. Keep a number that only goes up: 1, 2, 3… and convert it to base62. ID 125 becomes 21, ID 1,000,000 becomes 4c92. No collisions are possible, so no checks are needed. The question becomes: where does the counter live?
- One database sequence works at first, but every insert across every server waits on that one value. It becomes a hot spot.
- A Redis counter with
INCRis atomic and very fast. Better: each server grabs a block withINCRBY counter 1000, then hands out those 1,000 IDs from memory. The shared counter is touched once per thousand links. If a server crashes, it wastes the rest of its block, which is fine: gaps are harmless.
Going deeper: the costs a senior answer names
Guessability. Sequential codes are enumerable: if 4c92 exists, so does 4c93. Anyone can walk your whole archive, including links people assumed were private. If that matters, scramble the number before encoding it: a reversible bit-mixing step (a small block cipher or a multiplicative permutation over the ID space) maps 1, 2, 3 to codes that look random but still never collide.
No single counter at all. Snowflake-style IDs (a timestamp, a machine number and a per-machine sequence packed into 64 bits, which Twitter open-sourced in 2010) need no coordination per write. The trade-off is longer codes: a 64-bit ID is up to 11 base62 characters, not 7.
Losing the counter. If Redis restarts without persistence, the counter can go backwards and hand out codes that already exist. Persist it (AOF), or seed it at startup from the highest ID in the database. Make the primary key the final safety net either way.
Step 6: Deep dive — making redirects fast
At a few thousand redirects per second, one well-indexed database can keep up. The point of this step is headroom and latency.
Bad: always read from the database. It works, but every click pays a database round trip, and a viral link puts all of its load on one machine.
Good: cache in front of the database. Look up the code in Redis first; on a miss, read the database and store the result. Links almost never change, so a cached entry rarely goes stale. Set a TTL (say a day) and let Redis evict the least-used keys when memory fills (maxmemory-policy allkeys-lru). A small share of links gets most clicks, so a modest cache absorbs most reads.
Great: also cache at the edge. For the hottest links, a CDN or a small in-memory cache on each redirect server answers without touching Redis at all. This matters for the one thing a shared cache handles badly: a single hot key. A viral link is one key, and one key lives on one Redis node, however many nodes you have. Copies on many servers spread that load.
Going deeper: expiry and deleted links
If links can expire or be taken down (for spam, say), every cache layer must respect that. Store expires_at alongside the cached URL and check it on read, and set cache TTLs no longer than the time left on the link. For takedowns, delete the cache key when the row changes. This is also where 302 earns its keep: a 301 cached in browsers cannot be taken back at all.
Step 7: Scaling and the final design
Split creating and redirecting into separate services: they scale differently (a hundred writes a second against thousands of reads) and fail differently. Add read replicas for the database. When one database can no longer hold the data (around 2 TB a year adds up), shard by short code: lookups always know the code, so every read goes to exactly one shard.
What interviewers expect at each level
- Early career: gets to a working design with the API, a table and a sensible ID scheme, and can explain why reads dominate. Needs some steering on caching and scale.
- Mid-level (2–5 years): drives the estimates, compares two or three ID strategies with real trade-offs, adds a cache with a reason for its TTL and eviction, and knows the 301/302 difference.
- Senior: spots the hard parts unprompted: a shared counter as a hot spot and how to remove it, the hot-key problem in a sharded cache, codes that must not be guessable, and keeping expiry correct across every cache layer. Explains what they would measure first in production.
Remember this
- Read-heavy means: make the read path cheap, and protect the write path with rate limits.
- A counter encoded in base62 never collides. Hand out IDs in blocks so the counter is not a bottleneck.
- Sharding spreads keys; it does not fix one hot key. Copies at the edge do.
- 301 or 302 is a trade-off between less traffic and keeping control. Say which you pick and why.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Spotted a mistake or want a topic covered? Report an issue