How does a URL shortener work?

Question

In this lesson, we utilize a URL shortening service to create an application. How does a URL shortener work?

Answer

A URL shortener is a service that generates a unique short URL, usually around ~10 characters long, which is mapped to a longer URL and leads to the same destination as the longer URL. The information is typically stored in a table or hash map in key-value pairs, where keys are the short URL, and the values are the original, longer URL.

For example, say you used the bit.ly URL shortening service to shorten some long URL that is 100’s of characters long. The service will generate a unique code comprised of alphanumerical characters (A-Z, a-z, 0-9) for the key. The short URL is typically the domain name, 'bit.ly', plus the generated code, like 'abc123', making the full URL 'bit.ly/abc123'. Then, the original, longer URL will be mapped to this shortened URL in the database. It will look something like the following,

TABLE:
short URL       long URL
bit.ly/abc123   example.com/verylongURL...
...

Now, when anyone goes to the short URL, it will direct them to the same destination as the long URL it is mapped to.

The uniqueness of short URL’s is usually guaranteed because of the sheer number of possible combinations of alphanumerical characters as codes. And, on the small possibility of a collision, the service would usually just regenerate a new code until it finds one that is not yet taken.

8 Likes

How long will the shortened URL be valid? Dose this depend on the company that converted it? e.g. https://goo.gl/ vs https://bitly.com/.

1 Like

You raise an interesting question. We have all seen platforms come and go. All the apps I ever built are gone now because the hosts were bought up or pushed out and I never followed the migration instructions. The stuff is plainly gone, now. My bad. Still really miss a couple of the apps and don’t have the motivation to ressurect them. Again, my bad.

Bottom line, shortened URLs have an immense value, and for the short term the major providers should be trusted to keep their DB alive through the interim.

2 Likes