Build TINY URL

chinmay rakshit
Sep 4, 2018 · 2 min read

Recently I thought of giving myself the challenge to replicate some standard designs and face the failure cases. This is my first implementation to solve the design of Tiny URL

Requirement:
1) The URL should be tiny :)
2) For same long URL, the respective tiny URL should not change, for any n numbers of requests.

To solve this, one approach can be to save the long URL and create a hash string of the long URL and save that along with the URL. But the issue is at a later point of time the read query will become too slow due to string comparison.

So Better approach will be to store an integer associated with the long URL in RDBMS and index it.

For this, I create a random 6 character string (a-zA-Z0–9) and convert 62 base to decimal value and save this decimal value in the database(I used MySQL).

6 random character string: i2yzaG (12yzaG)base 62 to decimal: 38633814622INSERT INTO `short_urls` (`hash_integer`, `long_url`, `created_at`, `updated_at`) VALUES (38633814622, ‘www.google.com', ‘2018–09–04 02:56:39’, ‘2018–09–04 02:56:39’) 

Now we have solved how to get the long URL from tiny URL. But there is a bug here. If also you try to request for the same URL n times, n different random 6 characters will be created.

To solve this, hash the long URL using any cryptographic hash algorithm, I used MD5 Hash and save the Hash and row id of the table in a in-memory storage(I used Redis) on create of row entry in DB. As read calls will be much higher than write calls.

Failure scenarios:
* Suppose for some reason the Redis crashes, and you don’t have master-child setup, the data can still be populated again from our DB by converting the decimal value to base62.
* Suppose DB is compromised, still it will be difficult to map tiny URL to the long URL if you don’t know the decoding algorithm(In my case base62 conversion)

That’s all folks. Let me know if you have any queries on chinmay.rakshit@gmail.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade