Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
System design walkthrough for a URL shortener: API, short code generation with Base62, database choice, caching, 301 vs 302 redirects and analytics.
Quick answer: A URL shortener stores a mapping from a short code to a long URL and redirects visitors. To create a link, the service generates a unique short code, commonly by taking a unique number and encoding it in Base62, and saves the code with the long URL in a database. To follow a link, it looks up the code, usually in a cache, and replies with an HTTP redirect. The system is extremely read-heavy, so the design centres on fast lookups, caching and a collision-free way to generate codes.
This is one of the most popular system design interview questions, because it is small enough to finish and still touches storage, caching, scaling and trade-offs.
Functional
Non-functional
Estimates guide the design. Suppose:
| Quantity | Assumption | Result |
|---|---|---|
| New links | 100 million per month | About 40 writes per second |
| Read to write ratio | 100 to 1 | About 4,000 redirects per second on average |
| Retention | 5 years | 6 billion links |
| Size per record | About 500 bytes | Roughly 3 TB |
Two conclusions: writes are easy, reads are the challenge, and the data is large enough to plan for partitioning but not exotic.
How long must the code be? Base62 uses a-z, A-Z and 0-9.
Seven characters comfortably cover 6 billion links with room to spare.
POST /api/links
{ "url": "https://example.com/a/very/long/path?with=params", "alias": "optional" }
201 Created
{ "short_url": "https://sho.rt/aZ3kP9x" }
GET /aZ3kP9x
301 Moved Permanently
Location: https://example.com/a/very/long/path?with=params
This is the heart of the design. Three approaches:
Hash the long URL (for example with SHA-256) and take the first 7 characters of its Base62 form.
Generate 7 random Base62 characters and check the database for a clash.
Give each new link a unique integer ID and convert it to Base62. ID 125 becomes 21; ID 1,000,000,000 becomes 15ftgG.
Ways to produce the IDs:
One drawback: sequential IDs make codes guessable. Anyone can walk through ...aZ3, ...aZ4, ...aZ5 and discover other people's links. Fix it by scrambling the number with a reversible function before encoding, or by adding random bits.
| Approach | Collisions | Predictable | Complexity |
|---|---|---|---|
| Hash and truncate | Possible; must check | No | Low |
| Random | Possible; must check | No | Low |
| Counter + Base62 | None | Yes, unless scrambled | Medium |
A fourth option, a key generation service that pre-generates random unused codes and hands them out, combines unpredictability with no runtime collisions.
Custom aliases are simply user-chosen keys: insert with a uniqueness constraint and return an error if it is taken.
The data model is one table:
| Column | Notes |
|---|---|
code | Primary key |
long_url | |
user_id | Optional |
created_at, expires_at |
Access is almost entirely "get by key", with no joins. That is an ideal fit for a key-value or wide-column store such as DynamoDB or Cassandra, which scale horizontally by key. A relational database also works well; at this size you would shard it by a hash of the code. The decision follows the reasoning in SQL vs NoSQL.
Redirects must be fast, and popular links are requested far more than others.
Because mappings almost never change, they cache extremely well, with long expiry times and least-recently-used eviction. This is the cache-aside pattern from caching strategies. Caching "not found" results briefly also stops repeated lookups for codes that do not exist.
| 301 Moved Permanently | 302 Found (temporary) | |
|---|---|---|
| Browser caches the redirect | Yes | Generally no |
| Later clicks reach your servers | Often not | Yes |
| Server load | Lower | Higher |
| Click analytics | Incomplete | Accurate |
A 301 tells browsers the move is permanent, so they may skip your service next time. That saves load but hides clicks. Services that sell analytics tend to use temporary redirects, or a 301 with caching disabled, so that every click is counted.
Do not write to the analytics database during the redirect; it would slow the hot path. Instead, publish a small click event to a message queue and return immediately. Separate workers consume the events and aggregate counts by time, country, referrer and device.
Shorteners hide destinations, which makes them attractive for spam and phishing.
Base64 includes + and /, which have special meanings in URLs. Base62 uses only letters and digits.
Either derive the code from a guaranteed-unique ID, or generate a candidate and enforce a uniqueness constraint in the database, retrying on conflict.
It is a product decision. Reusing codes saves space; issuing a new code each time lets different users track their own clicks separately.
Any store with fast key lookups. Key-value databases fit naturally; a relational database with a cache in front is perfectly adequate for most scales.
A URL shortener is a key-value lookup with a redirect on top. The interesting decisions are how to generate unique, non-guessable codes, how to keep the read path fast with caching, and how to count clicks without slowing redirects. Work through the requirements and estimates first, and the architecture largely follows from them.