Let us apply all the system design concepts we have learned to design a real-world system: a URL Shortener like bit.ly or tinyurl.com.
POST /shorten - Takes a long URL, returns a short URL.GET /{shortCode} - Redirects to the original long URL (HTTP 301 or 302).A 7-character string using Base62 encoding (a-z, A-Z, 0-9) gives 62^7 = 3.5 trillion possible unique codes.
Approach 1: Hash-Based Hash the long URL using MD5 or SHA-256, take the first 7 characters. Risk of collision (two different URLs producing the same hash). Must check for and resolve collisions.
Approach 2: Counter-Based (Preferred) Use a globally unique counter (like a distributed ID generator or Twitter's Snowflake) to generate a unique integer. Convert the integer to a Base62 string. Guaranteed uniqueness.
Use an LRU cache. When a redirection request arrives:
A key-value NoSQL database (DynamoDB, Cassandra) is ideal because:
shortCode -> longURL). No complex JOINs needed.Log every redirection event asynchronously to a message queue (Kafka). A separate analytics service consumes these events to compute click counts, geographic data, and referrer statistics without impacting the real-time redirection performance.