Designing a URL shortener like TinyURL or Bitly is a rite of passage in system design interviews. The core idea, turning a long, unwieldy URL into a short, shareable alias, seems trivial, but scaling it to handle billions of requests per month exposes deep engineering challenges. This problem perfectly tests your grasp of database scaling, distributed ID generation, caching strategies, and concurrency. Let us build a production-ready URL shortener from the ground up.
Requirements (functional and non-functional)
Before jumping into architecture, we must lock down the scope. Interviewers often leave requirements intentionally vague to see if you will ask the right clarifying questions.
Functional Requirements
- Shortening: Given a long URL, the system returns a unique short alias (e.g.,
curebugs.com/x7y9Z). - Redirection: When a user clicks a short link, they are redirected to the original long URL.
- Custom Aliases (Optional but good to discuss): Users can pick their own custom short link (e.g.,
curebugs.com/my-post). - Expiration: Links should expire after a default timespan, or users can specify an expiration date.
Non-functional Requirements
- High Availability: Redirection is the critical path. If the service goes down, millions of links across the internet break.
- Low Latency: URL redirection should happen in real-time with minimal delay.
- Scalability: The system must handle a massive volume of read requests compared to write requests.
- Unpredictability: Short links should not be easily guessable to prevent malicious scraping (though standard Base62 is often accepted unless strict security is requested).
Capacity estimates
Let us assume a conservative scale to ground our design in concrete numbers.
Assumptions:
- New URLs (Writes): 100 million per month.
- Read/Write Ratio: 10:1. This means 1 billion redirects (Reads) per month.
- Data Retention: We will keep URLs for 10 years.
QPS (Queries Per Second) Calculations:
- Write QPS: 100,000,000 / (30 days * 24 hours * 3600 seconds) ≈ 40 writes/second.
- Read QPS: 1,000,000,000 / (30 * 24 * 3600) ≈ 400 reads/second.
- Peak QPS: Assuming a 5x multiplier for peak traffic, Peak Write QPS = 200, Peak Read QPS = 2,000.
Storage Calculations:
- Total Records: 100 million/month * 12 months * 10 years = 12 billion records.
- Record Size: Let's assume each database row takes roughly 500 bytes (Long URL, Short URL hash, created_at, expiration_date, user_id).
- Total Storage: 12 billion * 500 bytes = 6 Terabytes (TB).
6 TB is a moderate amount of data. A single modern RDBMS can hold this, but for high availability and read throughput, a distributed NoSQL database or a sharded SQL database is highly preferable.
API design
We will expose two primary RESTful endpoints.
1. Create a short URL
POST /api/v1/urls
Request Body:
{
"long_url": "https://www.curebugs.com/learn/system-design-case-studies",
"custom_alias": "sys-design" (optional),
"expire_at": "2025-12-31T23:59:59Z" (optional)
}Response (201 Created):
{
"short_url": "https://cb.gs/x7y9Z"
}2. Redirect a short URL
GET /{short_alias}
Response:
Returns an HTTP 301 or 302 redirect status code with the Location header pointing to the long URL.
Data model
We need to store the mapping between the short alias and the long URL.
Database Choice: SQL vs NoSQL
Given that our data is highly relational-independent (just a massive dictionary of key-value pairs) and we need to scale reads heavily, a NoSQL Key-Value store like Amazon DynamoDB, Cassandra, or Redis (with persistent storage) is an excellent fit.
However, a relational database (MySQL/PostgreSQL) is also perfectly viable if we use the short alias as the primary key and shard the database when storage exceeds a single node's capacity.
Schema
| Column Name | Data Type | Description |
|---|---|---|
alias (PK) | VARCHAR(10) | The short URL identifier (e.g., 'x7y9Z') |
long_url | VARCHAR(2048) | The original URL |
created_at | TIMESTAMP | When the link was created |
expires_at | TIMESTAMP | When the link should expire |
user_id | BIGINT | ID of the user who created it (optional) |
High-level architecture
Here is the high-level flow of our URL shortener system.
Write Flow (Shortening):
- Client sends a
POSTrequest with the long URL. - The Load Balancer routes the request to an available Application Server.
- The App Server requests a unique ID from the Distributed ID Generator.
- The ID is converted to a Base62 string (the short alias).
- The App Server saves the
(alias, long_url)mapping in the Database. - The short URL is returned to the client.
Read Flow (Redirection):
- Client visits the short URL.
- The App Server extracts the alias and checks the Redis Cache.
- If found (Cache Hit), it immediately returns the long URL.
- If not found (Cache Miss), it queries the Database, updates the Cache, and returns the long URL.
Deep dives
Let us explore the hardest parts of this system: how to generate the short alias, how to ensure uniqueness at scale, and the nuances of HTTP redirection.
1. URL Shortening Logic: Hashing vs Base62
How do we convert a long URL into a 7-character string? There are two main approaches.
Approach A: Cryptographic Hashing (MD5/SHA-1) We could hash the long URL using MD5, which yields a 128-bit hash (32 hex characters). We then take the first 7 characters. Trade-off: Hashing can result in collisions (two different long URLs producing the same first 7 characters). We would have to query the DB to check for collisions, append a salt, and re-hash, which is slow and expensive.
Approach B: Base62 Encoding (The Standard)
Instead of hashing the URL, we generate a unique, auto-incrementing integer ID for every new request, and then convert that base-10 integer into a Base62 string.
Base62 uses 62 characters: [0-9, a-z, A-Z].
How many URLs can a 7-character Base62 string hold?
62^7 = 3.5 trillion URLs.
This is more than enough for our 12 billion records.
Here is how you implement Base10 to Base62 conversion:
def encode_base62(num):
if num == 0:
return "0"
chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
base62 = []
while num > 0:
remainder = num % 62
base62.append(chars[remainder])
num //= 62
# Reverse the list to get the correct order
return "".join(base62[::-1])2. Generating Unique IDs at Scale
If we use Base62, we need a system that guarantees every URL gets a strictly unique integer ID. In a distributed environment with multiple app servers, we cannot just rely on a simple in-memory counter.
Option 1: Database Auto-Increment
We could use a single SQL database with an AUTO_INCREMENT primary key.
Problem: A single database becomes a massive write bottleneck and a single point of failure.
Option 2: Twitter Snowflake Snowflake generates 64-bit IDs based on timestamps, worker machine IDs, and sequence numbers. Problem: Snowflake IDs are very large (usually 18+ digits). When converted to Base62, the resulting string will be much longer than our desired 7 characters.
Option 3: ZooKeeper Range Allocation (Recommended) We use a coordination service like Apache ZooKeeper (or etcd). ZooKeeper maintains a central counter. Instead of an app server asking ZooKeeper for an ID on every request, the app server requests a range of IDs (e.g., 1 to 100,000).
- App Server 1 asks ZooKeeper for a range. ZooKeeper gives it
1 - 100,000and updates its internal counter to100,001. - App Server 1 keeps this range in memory and increments it locally for every new URL.
- App Server 2 asks for a range and gets
100,001 - 200,000. - If App Server 1 exhausts its range, it asks ZooKeeper for a new one.
- If App Server 1 crashes, we lose the unused IDs in that range. Since we have 3.5 trillion possible IDs, losing a few thousand is perfectly acceptable.
This approach guarantees uniqueness, eliminates the database write bottleneck, and provides incredibly fast, in-memory ID generation.
3. HTTP Redirection: 301 vs 302
When the server finds the long URL, it must return an HTTP redirect status code. The interviewer will almost certainly ask: "Should we use a 301 or a 302 redirect?"
- 301 (Moved Permanently): This tells the browser that the short URL has permanently moved to the long URL. The browser will cache this response. The next time the user clicks the short link, the browser will bypass our server and go directly to the long URL.
- Pros: Significantly reduces load on our servers.
- Cons: We cannot track click analytics (who clicked, when, from where) because the traffic bypasses our system.
- 302 (Found / Moved Temporarily): This tells the browser that the redirection is temporary. The browser will not cache the response and will hit our server every single time the link is clicked.
- Pros: Perfect for analytics, click tracking, and A/B testing.
- Cons: Increases the read load on our servers.
Verdict: If the business requires deep analytics (like Bitly does for its premium users), use 302. If the goal is purely to save server costs and latency, use 301.
Bottlenecks and trade-offs
No system is perfect. Here are the trade-offs we made and potential bottlenecks:
Caching Strategy
Since 20% of URLs (viral tweets, popular news articles) will likely generate 80% of the traffic, caching is vital. We should use Redis with an LRU (Least Recently Used) eviction policy. When the cache is full, the least recently accessed URLs are dropped to make room for new hot links. Trade-off: Memory is expensive. We must monitor cache hit rates and scale Redis clusters accordingly. If the cache goes down, the database could be overwhelmed by a "thundering herd" of read requests.
Database Sharding
Even with 6TB of data, querying a single database table with 12 billion rows will eventually slow down. We must shard (partition) the database. We can shard based on the first character of the short alias (e.g., all aliases starting with 'a' go to DB 1, 'b' to DB 2). Trade-off: Hash-based sharding makes it very difficult to query all links created by a specific user. If we need a "User Dashboard" feature, we might need a secondary index or a separate database optimized for user-centric queries.
Malicious Links and Rate Limiting
URL shorteners are heavily abused by spammers to hide phishing links. Mitigation: We must implement a Rate Limiter (using a sliding window algorithm in Redis) to prevent a single IP from generating thousands of links per minute. We should also integrate with third-party APIs (like Google Safe Browsing) to asynchronously scan long URLs and disable malicious aliases.
Questions an interviewer will ask next
1. How do you handle custom aliases?
Users might want cb.gs/my-custom-link. We must check the database to ensure the custom alias isn't already taken. If it is, we return an error. Custom aliases bypass the Base62 ID generator entirely. We must ensure the maximum length of a custom alias is capped (e.g., 50 characters) to prevent database bloat.
2. How do you delete expired URLs?
Actively scanning a 12-billion row database for expired links is too heavy. Instead, we use Lazy Cleanup. When a user tries to access an expired link, we check the expires_at timestamp. If it is in the past, we delete the record and return a 404. Additionally, a low-priority background Cron job can run during off-peak hours to sweep and delete expired rows in batches.
3. How would you implement click analytics? Writing analytics data to the primary database on every click would destroy our read latency. Instead, the App Server should push a lightweight event (Alias, Timestamp, IP, User-Agent) to a message queue like Kafka. A separate stream processing service (like Apache Flink or Spark Streaming) can consume these events, aggregate them, and store them in an OLAP database (like ClickHouse or Amazon Redshift) designed for heavy analytical queries.