The user wants a system design for a URL shortening service like Bitly.
This is a classic system design interview question. I need to follow a structured approach to answer this effectively.
1. Clarify Requirements (Functional & Non-Functional)
- Functional:
- Input: Long URL -> Output: Short URL.
- Input: Short URL -> Output: Redirect to Long URL (301 vs 302).
- User accounts? Custom aliases? Analytics? (Let's assume basic core functionality first, add user accounts/analytics as "nice to haves" or secondary features to show depth).
- Deletion/Expiration? (Keep it simple for now).
- Non-Functional:
- High Availability (The service must be up).
- Low Latency (Redirections must be fast).
- Scalability (Handle millions/billions of URLs).
- Reliability (Data loss is bad, but maybe not critical for new links if we have retries).
- Uniqueness (Short URLs must be unique).
2. Capacity Estimation (Back-of-the-envelope)
- Traffic: Assume 100M new URLs/month. Read:Write ratio is high (100:1).
- Storage: 100M * 10 years = 12B URLs. Each entry is small (~500 bytes). Total ~6TB.
- Bandwidth: 100M writes/month ~ small. 10B reads/month ~ significant.
- Memory: Cache 20% of hot URLs (LRU).
3. System API Design (REST)
createURL(api_dev_key, original_url, custom_alias=None, user_name=None, expire_date=None)
deleteURL(api_dev_key, short_url)
- Key return format: JSON with the short link.
4. Database Design
- Schema:
URL table (Hash/ID, OriginalURL, CreationDate, Expiration, UserID).
- Choice: NoSQL (Cassandra/DynamoDB) vs SQL (MySQL/Postgres).
- Reasoning: High read volume, simple schema, need horizontal scalability. NoSQL is a good fit, though SQL with sharding works too. Let's stick to NoSQL (Key-Value store) for speed and scale, or a sharded relational DB.
5. Core Algorithm - The "Magic" Part
- How do we map
https://verylongurl.com/... to bit.ly/xyz?
- Option A: Encoding actual URL (MD5/SHA256).
- Pros: Deterministic.
- Cons: Long output (needs truncation), potential collisions.
- Option B: Counter-based (Distributed Sequence).
- Use a distributed unique ID generator (like Zookeeper or a range-based allocator).
- Convert ID to Base62 (a-z, A-Z, 0-9).
- Pros: Guaranteed unique, fits in 6-7 chars easily.
- Cons: Single point of failure (the generator) unless designed well.
- Option C: Random generation.
- Generate random string, check DB. If exists, retry.
- Pros: Simple.
- Cons: Collisions increase over time.
- Selection: Option B is usually the standard interview answer because it's robust. I will explain the Base62 conversion of a unique ID.
- 7 characters in Base62 = 627≈3.5 trillion combinations. Sufficient.
6. High-Level Architecture
- Client -> Load Balancer -> API Server -> Database.
- Cache (Redis/Memcached) is crucial for reads.
7. Detailed Component Design
- Write Path:
- User sends long URL.
- Server checks if URL exists (optional optimization).
- Server gets a unique ID (Key Generation Service - KGS).
- Server converts ID to short string.
- Save to DB.
- Read Path:
- User requests short URL.
- Load Balancer sends to server.
- Server checks Cache.
- Hit: Return 301 Redirect immediately.
- Miss: Query DB. Update Cache. Return 301 Redirect.
8. Key Generation Service (KGS) Deep Dive
- We need to generate IDs without two servers getting the same ID.
- Use a dedicated service (KGS) that maintains a counter in a DB (e.g.,
current_max_id).
- Optimization: KGS pre-allocates ranges (e.g., 1-1000 to Server A, 1001-2000 to Server B). This reduces load on the master KGS database.
9. Data Partitioning & Replication
- Since we expect billions of rows, sharding is needed.
- Range based: Bad for indexing (hot spots).
- Hash based: Hash the short link or the ID. This distributes load well.
10. Cache Eviction
- LRU (Least Recently Used) is appropriate here.
11. Analytics (Bonus)
- Use a separate stream (Kafka) to write click events asynchronously so the main read path isn't slowed down.
12. Summary/Refinement
- Did I mention 301 vs 302?
- 301 (Permanent): Browser caches it. Good for server load, bad for analytics (won't hit server next time).
- 302 (Temporary): Browser asks server every time. Bad for server load, good for analytics.
- Decision: Bitly uses 301 usually, but for analytics tracking, they might track via scripts or use 302s if they prioritize analytics over latency. Usually, for a generic "URL shortener" design, 301 is the standard "correct" HTTP behavior, but mention the trade-off. Actually, strictly speaking, Bitly uses 301s but wraps the analytics in the initial redirect logic before sending the 301. Wait, if browser caches it, analytics stop. So, usually, 301 is "correct" for the definition of the resource, but 302 allows analytics. Most modern designs suggest 301 but rely on JavaScript tracking pixels or accept the analytics loss on repeated clicks or use 302. Let's stick to: Use 301 for performance, but if Analytics is a hard requirement, we need 302 or JS tracking. I'll mention 301 is standard but 302 allows real-time analytics.
Structure of the Answer:
- Problem Statement & Requirements: Define scope (Functional/Non-functional).
- Capacity Estimation: Storage, Traffic, Memory.
- System APIs: Interface definition.
- Database Design: Schema and DB choice.
- Hashing/Encoding Algorithm: Base62 conversion.
- System Architecture: Diagram description (Load Balancer, Cache, App Server, DB).
- Key Generation Service (KGS): Handling concurrency.
- Data Partitioning: Scaling the DB.
- Cache: Handling the heavy read load.
- Analytics & Telemetry: The "Bitly" specific part.
Let's refine the "Key Generation".
- Distributed Key Generator (KGS).
- Pre-generate keys? KGS can generate keys in batches and put them in a queue. App servers consume from the queue. This decouples generation from serving.
Let's refine the "301 vs 302".
- If we want to track every click, we cannot let the browser cache the redirect. So 302 is better for analytics. 301 is better for reducing load. Usually, these services prioritize the link working forever, so 301 is semantically correct, but for a service selling analytics, 302 is better. I will explain this trade-off.
Let's write the response.
Designing a URL shortening service like Bitly is a classic system design interview question. It tests your ability to handle high read/write ratios, unique ID generation, and scalability.
Here is a comprehensive system design for a URL shortener.
1. Requirements & Scope
Functional Requirements
- Shorten URL: Given a long URL, return a short, unique alias.
- Redirect: Given a short URL, redirect the user to the original long URL.
- Custom Aliases: Users should optionally be able to pick a custom alias (e.g.,
bit.ly/my-custom-name).
- Expiration: (Optional) Links can expire after a specific timeframe.
Non-Functional Requirements
- High Availability: The system must be up 24/7. If the shortener is down, all links break.
- Low Latency: Redirections must happen extremely fast (milliseconds).
- Scalability: Handle millions of URL generations and billions of redirections per month.
- Reliability: Data loss is unacceptable; once a link is created, it must work forever.
Estimation & Constraints (Back-of-the-envelope)
- Traffic: Assume 100 Million new URLs per month.
- Read/Write Ratio: Shorteners are read-heavy. Assume 100:1 (10 Billion redirections/month).
- Storage: Assume we store links for 10 years.
- 100M * 12 months * 10 years = 12 Billion URLs.
- Each URL object ≈ 500 bytes.
- Total Storage ≈ 6 TB.
- Bandwidth: 10B reads * 500 bytes ≈ 5 PB/month outgoing traffic.
2. System APIs
We can define RESTful APIs.
1. Create Short URL
POST /api/v1/shorten
- Parameters:
long_url (string), custom_alias (optional), expire_date (optional).
- Returns: JSON containing the short URL.
2. Redirect
GET /{short_code}
- Returns:
301 Redirect to the long_url.
3. Database Design
We need to store the mapping between the short code and the long URL.
Schema:
- PK:
id (Auto-increment BigInt or UUID)
- Hash:
short_code (String, Unique Index) - The 7 character key.
- OriginalURL:
long_url (String)
- CreatedAt:
timestamp
Choice of Database:
- NoSQL (Cassandra/DynamoDB): Excellent for high write throughput and horizontal scaling. Since we don't need complex joins, a Key-Value store is ideal.
- Relational (PostgreSQL/MySQL): Good for ACID compliance, but scaling writes requires sharding.
- Decision: NoSQL (e.g., DynamoDB or Cassandra) is preferred for the sheer scale of reads/writes, but MySQL/Postgres is acceptable if the dataset fits within a sharded cluster.
4. The Core Logic: Generating the Short URL
This is the most critical part. How do we turn https://google.com/... into bit.ly/xyz7?
Option A: Encoding Actual URL (MD5/SHA256)
We could hash the long URL (e.g., MD5) and take the first 7 characters.
- Pros: Deterministic (same URL always gets same short link).
- Cons: Collisions are possible (two URLs might result in the same hash). Resolving collisions is messy.
Option B: Counter-Based (Base62 Conversion) - Recommended
We treat the short string as a number representation.
- Maintain a global unique ID (1, 2, 3, ... 100,000).
- Convert this ID from Base10 to Base62 (a-z, A-Z, 0-9).
- 7 characters in Base62 gives us 627≈3.5 trillion unique IDs.
Example:
- ID:
125
- Base62:
27 (represented as characters 2 and 7)
How to handle the Global ID?
If we use a database auto-increment ID, it becomes a bottleneck. We use a Distributed Key Generator (KGS) or a Zookeeper/Redis Range allocator.
- Pre-allocate ranges of IDs (e.g., Server A gets IDs 1-1,000,000; Server B gets 1,000,001-2,000,000).
5. High-Level Architecture
- Client: User sends request.
- Load Balancer: Distributes traffic to API servers.
- API Server: Handles logic.
- Cache (Redis): Stores hot URLs (Read-through cache).
- Database: Persistent storage.
Write Flow (Shortening)
- User sends
POST request with long URL.
- API server generates a unique ID (from a pre-allocated range or KGS).
- Convert ID to Base62 string (e.g.,
w9Xc2).
- Save
{short_code: 'w9Xc2', long_url: '...'} to Database.
- Return short URL to user.
Read Flow (Redirection)
- User clicks
bit.ly/w9Xc2.
- API server checks Cache (Redis).
- Hit: Return Long URL immediately.
- Miss: Query Database for
w9Xc2.
- Update Cache with result.
- Return
HTTP 301 (Moved Permanently) to the client with the Long URL in the Location header.
6. Detailed Component Design
Caching Strategy
Since the read ratio is 100:1, caching is mandatory.
- Use LRU (Least Recently Used) cache policy.
- Cache size: If 20% of URLs are hot, we need to cache 20% of 12 Billion ≈ 2.4 Billion items.
- 2.4B * 500 bytes ≈ 1.2 TB of RAM. We can use a distributed cache cluster (Redis Cluster).
Redirection Status Codes
- 301 Moved Permanently: Browser caches this. Subsequent clicks go directly to the long URL without hitting our server.
- Pros: Reduces server load.
- Cons: We cannot track analytics for that user anymore.
- 302 Found (Temporary): Browser always asks our server first.
- Pros: Perfect for analytics/tracking.
- Cons: Higher server load.
- Decision: Bitly uses 301 for performance, but for a design requiring analytics, we might choose 302 or serve 301 and rely on client-side JS beacons for tracking.
Data Partitioning (Sharding)
Since 6TB fits on a single modern server, we might not need sharding initially. However, to scale writes:
- Range Based Partitioning: Store URLs starting with 'a' on shard 1, 'b' on shard 2. (Can cause hot spotting).
- Hash Based Partitioning: Hash the
short_code to determine the shard.
- shardid=hash(short
7. Analytics (The "Bitly" Feature)
Bitly isn't just a redirector; it's a data platform. We need to track:
- Number of clicks.
- Geo-location of the user.
- Referrer (Facebook, Email, etc.).
- Browser/Device.
Architecture:
Analytics should never block the redirection path (Critical Path).
- When a read request comes in, the API server publishes an event (Click Data) to a message queue (Kafka/Kinesis).
- The API server immediately returns the redirect.
- Background workers consume the Queue and write aggregates to a Data Warehouse (e.g., ClickHouse, Hadoop, or Redshift).
8. System Diagram (Conceptual)
[ User ]
|
[ Load Balancer ]
|
+------+------+
| |
[API Server] [API Server]
| |
+----+--------+
|
+----+-----------------+
| |
[ Cache ] [ Message Queue ] ---> [ Analytics Workers ]
(Redis) | |
[ Database ] [ Data Warehouse ]
(NoSQL/Sharded)
Summary of Trade-offs
- Base62 vs Hash: We chose Base62 with a counter because it guarantees uniqueness and results in the shortest possible string. It requires coordination (KGS), but avoids the collision management overhead of hashing.
- 301 vs 302: We prefer 301 for performance but acknowledge that analytics require a more complex solution (JavaScript beacons or sacrificing 301 performance).
- Consistency: We accept "Eventual Consistency" for analytics, but require "Strong Consistency" for the URL mapping (a link must work immediately after creation).