Hash-Based Generation Approach
What You'll Learn
You'll learn how to generate deterministic short URLs by hashing the original long URL and encoding the result, ensuring the same input always produces the same short code.
Core Idea
Instead of generating random short codes or using auto-incrementing counters, the hash-based approach applies a cryptographic hash function (like MD5 or SHA-256) directly to the long URL. Since hash functions produce fixed-length outputs, you can then truncate the hash to your desired length and apply Base62 encoding to create a URL-safe short code.
The beauty here: given https://example.com/very/long/path, hashing always produces the same result—deterministic behavior without needing a database lookup first.
How It Works
- Hash the long URL: Apply MD5 (128 bits) or SHA-256 (256 bits)
- Truncate: Take the first N bits/bytes (e.g., first 43 bits for 7 Base62 characters)
- Encode: Convert to Base62 for a URL-friendly short code
Example flow:
Input: "https://example.com/article/12345"
↓ MD5 hash
→ "5d41402abc4b2a76b9719d911017c592"
↓ Take first 6 characters
→ "5d4140"
↓ Base62 encode
→ "aB3xK9"
Why This Matters
Determinism: Same URL always generates the same short code—no duplicates stored for identical links. This saves storage when many users shorten the same popular URL.
Simplicity: No coordination needed between servers; any node can generate the code independently.
Collision risk: Truncation increases collision probability (two different URLs producing the same short code). With 7 Base62 characters (≈3.5 trillion combinations), collisions are rare but possible—requiring collision detection and handling logic.
Key Takeaway: Hash-based generation creates deterministic short URLs by hashing and truncating the long URL, trading guaranteed uniqueness for stateless simplicity and deduplication benefits.