1. Understand the Goal: The user wants a design for a URL shortener system (like TinyURL or Bitly) with a specific focus on handling collisions (when two different long URLs map to the same short URL).
-
Identify Key Requirements:
- Functional: Shorten long URL, redirect short URL to long URL, handle collisions, custom aliases (optional but good).
- Non-Functional: High availability, low latency (redirections must be fast), scalability (handle massive URLs), durability (data shouldn't be lost).
- Estimation: Read-heavy (100:1 ratio usually), unique ID generation.
-
Core Components of a URL Shortener:
- API: REST API (POST to create, GET to redirect).
- Database: Key-Value store is best (NoSQL like Cassandra/DynamoDB or Redis for caching).
- ID Generation Service: The brain of the operation. How do we generate the short string?
-
ID Generation Strategies (The "Collision" part):
- Approach 1: Random Generation. Pick a random string of length k. Check if it exists.
- Pros: Simple.
- Cons: Collision probability increases over time (Birthday Paradox). Read before write is expensive.
- Approach 2: Hashing (MD5/SHA256). Hash the long URL, take the first N characters.
- Pros: Deterministic (same URL always gets same short URL).
- Cons: Collisions are still possible if you truncate. To resolve, you need to append a seed/salt and re-hash.
- Approach 3: Counter/Range-based (Zookeeper/Database). Maintain a global counter
1, 2, 3.... Encode to Base62.
- Pros: No collisions guaranteed. Short IDs (numeric).
- Cons: Single point of failure (the counter). Scaling is tricky (need range allocation).
-
Selecting the Best Strategy for "Collision Handling":
- The prompt specifically asks for collision handling. This implies we should discuss strategies where collisions might happen and how to fix them, or strategies that avoid them entirely.
- Strategy A (Hashing + Resolution): Good for distributed systems. If hash collides, re-hash with appended sequence.
- Strategy B (Pre-generated Keys - KGS): A Key Generation Service generates random strings, checks uniqueness (once), and puts them in a DB/Queue. App servers just pick one. This is the most robust for high scale.
-
Structuring the Design:
- Phase 1: Requirements & Capacity Estimation (Standard system design intro).
- Traffic, Storage, Memory.
- Phase 2: API Design.
createURL(api_dev_key, original_url, custom_alias=None)
getURL(short_url) -> 301 Redirect.
- Phase 3: Database Schema.
- Table:
URL (Hash/PK, OriginalURL, CreatedAt, Expiration).
- Phase 4: The "Collision" Problem & ID Generation (The core answer).
- Option 1: Encoding Actual URL (Hashing). MD5 -> Base64. Truncation causes collisions.
- Resolution: If collision detected (DB lookup), append sequence to original URL and hash again.
- Option 2: Offline Key Generation (KGS). Pre-generate 6-char random strings. Check uniqueness. Load into two DBs (used/unused).
- Pros: No runtime collision handling needed!
- Option 3: Range-based Counter. Zookeeper hands out ranges (1-1M) to Server A.
- Phase 5: System Architecture (The Diagram).
- Client -> Load Balancer -> API Server -> (Cache) -> Database.
- Phase 6: Detailed Data Flow.
- Writing (Shortening).
- Reading (Redirecting).
-
Refining the "Collision Handling" aspect:
Since the user specifically asked for collision handling, I should focus on the Hashing + Re-hashing method versus the Pre-generated Unique Keys method.
- Hashing Method:
- Input:
long_url.
- Compute
hash = md5(long_url).
- Encode to Base62. Take first 7 chars (
short_key).
- Check DB if
short_key exists.
- Collision Case A: It exists and points to same
long_url. Return key. (Deduplication).
- Collision Case B: It exists but points to different
long_url (Hash Collision).
- Solution: Append a predefined seed/salt (e.g.,
long_url + "1") and re-hash.
- Repeat until free slot found.
-
Adding Detail to the Solution:
- Encoding: Base62 (a-z, A-Z, 0-9).
- Length: 7 characters gives 627≈3.5 trillion combinations. Good enough.
- Database: NoSQL is better for scale (key-value).
- Cache: Redis for hot URLs.
-
Review and Organize:
- Start with high-level overview.
- Address Capacity.
- Deep dive into the collision algorithms (Encoding vs. Generation).
- Explain the architecture.
- Discuss Purging/Telemetry.
-
Self-Correction/Refinement during drafting:
- Initial thought: Use a database auto-increment ID.
- Correction: In a distributed DB, auto-increment is hard (synchronization latency). Better to use a KGS (Key Generation Service) or Hashing. I will present the KGS approach as the "No Collision" approach and Hashing as the "Handle Collision" approach. The prompt asks for handling, so the Hashing + Re-hashing strategy is the most direct answer, but KGS is the "industry standard" optimization. I will present both.
-
Final Output Structure:
- System Goals (Functional/NF).
- Capacity Estimation.
- API & DB.
- Solution 1: Hashing with Collision Resolution (Focus on the prompt's specific request).
- Solution 2: Pre-generated Keys (KGS) (The robust alternative).
- Architecture Diagram (Text-based).
- Redirect flow.
Let's write the response. Ensure Base62 is explained (62n). Explain 301 vs 302 redirects (Analytics vs Speed).
Here is a comprehensive design for a scalable URL Shortener system with a specific focus on collision handling strategies.
1. System Requirements & Constraints
Before diving into the architecture, we define the scope:
- Functional: Users submit a long URL and receive a short URL. Users are redirected from the short URL to the original.
- Non-Functional: High availability (redirects must work), low latency, and scalability.
- Traffic Estimate: Assuming 100 million new URL generations per month.
- Read/Write Ratio: heavily read-oriented (100:1 ratio of redirects to creations).
2. The Core Problem: The Short Key
The short URL (e.g., tiny.url/Kx4f9) relies on a unique Key. We need a way to generate N unique keys.
- Character Set: 62 characters (a−z,A−Z,0−9).
- Length: With length 7, we can generate trillion unique IDs.
There are two main approaches to generating these keys, and collision handling differs significantly between them.
3. Strategy A: Hashing + Collision Resolution
This approach generates a hash of the original URL and resolves conflicts if they occur.
Algorithm
- Input:
Long_URL
- Hash: Compute
Hash(Long_URL + Salt) (e.g., MurmurHash3, SHA256).
- Encode: Take the first 7 characters of the hash and encode them in Base62.
- Check DB: Query the database to see if this Key exists.
Collision Handling (The Logic)
A collision occurs if two different Long URLs generate the same 7-character Key.
Scenario 1: The Key Exists, but the stored URL matches the Input URL.
- Action: This is not a true collision; it is a duplicate request.
- Result: Return the existing Key immediately.
Scenario 2: The Key Exists, but the stored URL is DIFFERENT.
- Action: A genuine hash collision.
- Resolution (Re-hashing):
- Append a predefined "seed" or "salt" string to the original URL (e.g.,
Long_URL + "a").
- Re-hash this new string.
- Generate a new Key.
- Check DB again. If occupied, change seed to
"b" and repeat until a free slot is found.
Pros & Cons
- Pros: The Key is deterministic (in theory, you don't need to store the mapping if you re-calculate it, though in practice you must to handle duplicates).
- Cons: Requires a database read/write lock or transaction for every generation to ensure atomicity. Performance degrades as the keyspace fills up.
4. Strategy B: Pre-Generated Keys (KGS - Key Generation Service)
This is the recommended industry standard for high scale.
Instead of hashing the URL, we generate random or sequential keys ahead of time, verify they are unique before a user even arrives, and store them in a "Key Pool".
Architecture
- Key Generation Service (KGS): A standalone service that generates random 7-character strings.
- Key DB (Unused): A database table
Unused_Keys containing millions of pre-verified unique keys.
- Key DB (Used): A table
Used_Keys.
Collision Handling
The collision handling happens offline, not during the user request.
- KGS generates 1 million keys.
- It performs a
BULK INSERT into the DB. The database enforces a UNIQUE constraint on the Key column.
- If the DB throws a constraint violation, the KGS catches the exception and discards the duplicates.
- Result: The
Unused_Keys table is guaranteed to contain only unique keys.
Workflow (User Request)
- User sends
Long_URL.
- API Server queries
Unused_Keys table: SELECT key FROM Unused_Keys LIMIT 1 FOR UPDATE.
- Server moves this key to
Used_Keys and associates it with the Long_URL.
- Return Key to user.
Pros & Cons
- Pros: Extremely fast O(1) for the user. No complex re-hashing loops. No collisions at runtime.
- Cons: Need to maintain the "pool" of keys.
5. Detailed System Architecture
We will use Strategy B (KGS) for the design, as it is more robust.
Components
- Client: Sends HTTP requests.
- Load Balancer: Distributes traffic.
- Web Server: Stateless application servers.
- Key Generation Service (KGS): Runs as a background worker to keep the Key Pool full.
- Database:
- NoSQL (Cassandra/DynamoDB): Best for high write throughput and horizontal scaling.
- SQL (PostgreSQL/MySQL): Acceptable if sharding is implemented.
- Cache (Redis): Stores mappings of "Hot" URLs (Key -> Long_URL) to reduce DB load.
Database Schema (NoSQL Document)
{
"_id": "Kx4f9aZ", // The Short Key (Partition Key)
"long_url": "https://example.com/very/long/link",
"created_at": "2023-10-27T10:00:00Z",
"expiration": "2024-10-27T10:00:00Z" // Optional
}
6. Workflow: URL Shortening (Write Path)
- Request:
POST /shorten { "url": "https://google.com" }
- Validation: Server validates URL format.
- Get Key: Server requests a key from a local buffer or the
Unused_Keys DB table.
- Optimization: Servers can "reserve" a block of keys (e.g., 100 keys) from the DB in memory. This prevents a DB hit for every request.
- Write to DB: Insert
{ Key: "abc123", LongURL: "https://google.com" } into the Main DB.
- Cache: Write the entry to the Redis Cache.
- Response: Return
http://tiny.url/abc123.
7. Workflow: Redirection (Read Path)
- Request:
GET /abc123
- Cache Check: Server queries Redis for key "abc123".
- Hit: Return Long URL immediately.
- Cache Miss: Query the Main Database.
- Found: Return Long URL. Update Redis with this mapping (Lazy loading).
- Not Found: Return 404 Error.
8. Summary of Trade-offs
| Feature | Hashing + Re-hashing | KGS (Pre-generated) |
|---|
| Collision Handling | Runtime: Must loop/retry if collision found. | Pre-runtime: Handled by DB constraints before use. |
| Latency | Unpredictable (might re-hash 5 times). | Constant time (O(1)). |
| Consistency | Same URL always gets same Key (if no salt). | Same URL gets different Keys every time. |
| Complexity | High (requires logic to handle loops). | Medium (requires maintenance of Key Pool). |
Recommendation: Implement the KGS (Key Generation Service) approach. It guarantees unique keys, offers consistent high performance, and separates the complexity of uniqueness from the user-facing API.