Design a TinyURL-like service
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-12-01
Problem Statement
Design and implement the core low-level components of a URL shortening service (similar to TinyURL/Bitly). The system should generate short, unique URLs for long URLs, support efficient lookups, and handle concurrency safely.
Functional Requirements (FR)
1.URL Shortening
•Input: A long URL.
•Output: A shortened URL with a unique identifier (e.g., https://tiny.ly/abc123).
2.URL Redirection
•Input: A short URL.
•Redirect the user to the corresponding long URL.
3.URL Management
•Prevent duplicate short URLs for the same long URL (configurable).
•Support custom short codes (e.g., tiny.ly/mycode).
•Expiration feature for temporary links (optional).
4.Analytics (Optional/Bonus)
•Track the number of times a short URL is visited.
•Track user details like browser, location, timestamp.
Non-Functional Requirements (NFR)
•Scalability → Should handle millions of URLs.
•Performance → Redirection must be fast (O(1) lookup).
•Reliability → Must avoid collisions in generated keys.
•Concurrency → Handle concurrent shorten requests safely.
•Extensibility → Support analytics, expiration policies later.
Core Entities & Attributes
URL
•urlId
•longUrl
•shortCode
•createdAt
•expiryAt (optional)
•hitCount
User (optional if authentication required)
•userId
•username
•urlsCreated[]
Core Components
Encoder/Decoder
•Converts numeric IDs into short alphanumeric strings (Base62 encoding).
•Decodes back from short code to ID.
Repository / Storage
•Map shortCode → longUrl.
•Map longUrl → shortCode (for duplicates handling).
URL Service
•shortenUrl(longUrl, userId, customCode)
•getLongUrl(shortCode)
•deleteUrl(shortCode)
Analytics Service (Optional)
•incrementHitCount(shortCode)
•getStats(shortCode)
APIs / Operations
•POST /shorten → Shorten a given URL.
•GET /{shortCode} → Redirect to original URL.
•POST /shorten/custom → Create a short URL with a custom code.
•GET /stats/{shortCode} → Retrieve analytics.
LLD Design Goals
•Class Diagram → UrlService, Encoder, UrlRepository, AnalyticsService, Url.
•Design Patterns:
•Singleton → For central UrlService.
•Factory/Strategy → For different encoding schemes (Base62, hash-based).
•DAO Pattern → For storage abstraction.
•Concurrency Handling → Synchronization for generating unique codes.