System design of TinyURL
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-08-19
Problem Statement
Design a TinyURL system that allows users to shorten long URLs into compact, unique URLs, and retrieve the original URL when accessed. The system should handle high read/write throughput, avoid collisions, and be scalable and reliable.
Functional Requirements (FR)
URL Shortening
•Input: long URL.
•Output: a unique short URL (e.g., https://tiny.url/abc123).
•Generate short URLs using techniques like hashing, base62 encoding, or incremental IDs.
URL Redirection
•When a user visits the short URL, redirect to the original long URL.
Uniqueness
•Ensure that each short URL maps to only one long URL.
•Optionally, prevent duplicate short URLs for the same long URL.
Expiration (Optional)
•Support TTL for short URLs (e.g., delete after a month).
Analytics (Optional)
•Track the number of clicks, user information, and creation date.
Suggested Classes & Responsibilities
Class: URLShortener
•Attributes:
•storage → maps shortUrl → longUrl
•idCounter → for generating unique IDs (if using incremental ID method)
•Methods:
•shortenUrl(longUrl) → generates a unique short URL and stores the mapping
•getLongUrl(shortUrl) → retrieves the original URL for redirection
•deleteUrl(shortUrl) (optional) → removes a mapping
Class: Base62Encoder
•Methods:
•encode(integer) → converts integer ID to base62 string
•decode(string) → converts base62 string back to integer
Class: Storage
•Attributes:
•shortToLongMap → key-value map of short → long URLs
•longToShortMap (optional) → reverse lookup to avoid duplicate short URLs
•Methods:
•store(shortUrl, longUrl)
•get(shortUrl)
Data Flow (High-Level)
1.User calls shortenUrl(longUrl) → URLShortener generates a unique short URL.
2.Short URL stored in Storage → mapping shortUrl → longUrl.
3.User visits short URL → getLongUrl(shortUrl) retrieves original URL → redirect user.
4.Optional: Analytics module tracks usage metrics.
Key Design Considerations
•Uniqueness & Collisions: Use hash-based or incremental IDs with base62 encoding.
•Performance: Fast get and put operations using in-memory cache like HashMap; optionally persist to DB.
•Scalability: Handle high read/write throughput; shard by key space if needed.
•Thread-Safety: Ensure concurrent access to storage doesn’t lead to inconsistent mappings.
•Extensibility: Add features like URL expiration, analytics, custom short URLs.