Theory
URL Shortener: TinyURL Design
📋 Overview
A URL shortener (like TinyURL or Bitly) is a system that maps long, complex URLs to short, unique aliases. This problem is a classic system design favorite because it touches on ID generation, encoding, caching, and massive read-write scalability.
🏗️ Core Principles & Characteristics
- Base62 Encoding: Converting a large numeric ID into a string using
[a-z, A-Z, 0-9]. A 7-character Base62 string provides $62^7 \approx 3.5$ trillion unique combinations. - Redirection Logic: Using HTTP 301 (Permanent Redirect) for SEO or HTTP 302 (Temporary Redirect) for better analytics tracking.
- Persistent Mapping: Storing the
{short_code: long_url}pair in a high-performance NoSQL database (like Cassandra or DynamoDB) for horizontal scale. - Read-Heavy Nature: Redirections (reads) will typically outnumber shortenings (writes) by 100:1 or more.
⚖️ Trade-offs: Pros & Cons
Pros
- UX/Branding: Cleaner links for social media, print ads, and SMS.
- Analytics: Centralized point to track click counts, geographic data, and referral sources.
- Efficiency: Reduces characters in length-constrained environments (like X/Twitter or SMS).
Cons
- Link Rot: If the shortening service goes down, all links become "broken."
- Security Risk: Shortened links hide the final destination, making them ideal for phishing attacks.
- Performance Gap: Adds an extra network hop (DNS + Redirect) before the user reaches the final site.
🌍 Real-World Implementation
- Bitly: Commercial-scale shortener with deep analytics and custom domains.
- Twitter (t.co): Automatic shortening for security scanning and analytics.
- Firebase Dynamic Links: Specialized shorteners for deep-linking into mobile apps.
- Custom Branded Shorteners: e.g.,
amzn.to(Amazon),buff.ly(Buffer).
💡 Interview "Gotchas" & Tips
- Hashing vs. Base62: Don't just use MD5/SHA-256 on the URL (collisions are rare but possible). Use a Unique ID Generator and then encode that ID to Base62.
- 301 vs. 302: Explain the trade-off. 301 is better for latency (browser caches it), but 302 is better for tracking (every click hits your server).
- Data Expiration: Mention a "Cleanup" strategy for old, unused links to prevent the database from growing indefinitely.
- Custom Aliases: How to handle users choosing their own
tinyurl.com/my-cool-link. (Check for existence in DB before saving).
📐 Suggested Architecture Primitives
- Snowflake ID Generator: For generating unique 64-bit integers.
- NoSQL (Cassandra/DynamoDB): To store the billions of mappings.
- Redis: To cache the "Hot" URLs to achieve sub-millisecond redirection.
- Load Balancer: To distribute redirection traffic across a fleet of stateless web servers.
Canvas