Tiny URL Shortening System
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2024-07-09
Problem Statement
Design a URL shortening service (like Bitly or TinyURL) that takes a long URL and generates a short, unique alias. The system must handle billions of URLs, support redirection with low latency, and ensure high availability and scalability.
Functional Requirements
1.Shorten URL
•Input: A long URL.
•Output: A short URL (e.g., tiny.url/abcd12).
2.Redirect URL
•Given a short URL → redirect to the original long URL in real-time (<50ms latency).
3.Custom Alias
•Support user-provided aliases (tiny.url/myblog).
4.Analytics (Optional/Extended)
•Track number of clicks per short URL.
•Track geographic location, device, referrer.
5.URL Expiry (Optional/Extended)
•Ability to set expiration time for short URLs.
Non-Functional Requirements
•Scalability → Must support billions of short URLs and high QPS lookups.
•Low Latency → Redirection must be near-instant.
•Availability → Service should be globally available with minimal downtime.
•Consistency → Short URL must always resolve to the correct original URL.
•Fault Tolerance → Handle server crashes without losing data.
Design Considerations
•ID Generation
•Base62 encoding of incremental IDs or UUID-based hashing.
•Avoid collisions with distributed ID generators (Snowflake, Zookeeper, etc.).
•Database
•Write-heavy (shortening) vs. Read-heavy (redirect).
•Possible choices:
•Relational DB (MySQL/Postgres) with sharding.
•NoSQL (Cassandra, DynamoDB) for scalability.
•Redis cache for hot URLs.
•Caching
•Frequently accessed URLs should be cached (Redis, Memcached) for faster lookup.
•Redirection Flow
•User hits short URL → Service queries DB/cache → Redirects with HTTP 301/302.
•Analytics Storage (Optional)
•Asynchronous logging to Kafka, processed into analytics DB (ClickHouse, BigQuery).
Example HLD Components
•API Gateway → Handles shortenURL() and redirectURL().
•Application Service → Encodes/decodes short URLs.
•Key Generator → Generates unique short keys.
•Database → Maps short key ↔ long URL.
•Cache Layer → Stores hot mappings for fast access.
•Analytics Pipeline (Optional) → Collects clickstream events for reporting.