I Made the World's First "Link Compressor"
Comments
Transcript
Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.
We've all used a link shortener. You enter a long link and out comes the short link. But in order to do this, the website you're using has to store the full link in a database. Who knows what they're doing with that information or how well it's secured. In many cases, by simply trying random combinations, it can be surprisingly easy to stumble upon someone else's link. Also, upkeeping that database costs them money, which is why many of these services run ads before redirecting you to the destination. And if you only have the shortened link, then once the company goes out of business, that link is effectively gone forever. Some of this also applies to online QR code generators. See, the denser the QR code, the harder it is to scan. Because of this, it makes sense to shorten the link before turning it into a QR code. But most online services require you to sign up or pay to use that feature. And even when you do, they use the wrong format, again making the QR code denser than it needs to be. It would be such an easy fix, but they simply don't care.
All of this made me wonder, is there a way to make a link shortener and QR code generator that doesn't use a database, keeps the link fully recoverable in case the service goes down, and generates actually optimal QR codes, all without ads or registration? The short answer is, yeah, kind of. If
you just want to try it for yourself, then here it is. Knock yourself out. Though, of course, the longer answer is a lot more nuanced than that. Think of it more as an experiment, not a consumer product. Though, it does at least do a pretty good job at QR codes, often matching or surpassing alternatives for reasons we'll get to pretty soon. This video is primarily about data encoding and compression. And yes, I know those sound like big words, but it's surprisingly satisfying once those concepts start to click. Here, let's start with a simple example. This is the link for the New York Times Wordle, and as you can see, it's quite long. But, honestly, most of the information here is redundant. This HTTPS part at the start is the protocol, which for websites can only be one of two things, either HTTP or HTTPS. If you
don't specify it, the browser will try both until one works. Then comes the www
prefix. This is kind of going out of fashion nowadays, so many websites are set up to function just fine without it, and browsers will automatically add it if necessary. Lastly, the index.html
segment at the end is once again redundant. If it's not present, many web servers will just add it back automatically. So, already, we've shortened the link by over 50% just by removing common fluff. But, savvy viewers will point out that this is a lossy transformation. By removing these elements, we might break some links that do depend on them. So, instead, we can compromise. Instead of writing HTTP or HTTPS in full, we can replace that with one bit. That's a zero or a one representing which of the two options it is. Then, for the www part, we can again use a single bit. This time denoting the presence of that prefix, zero if it's not present, and one if it is. We can do the same for the index suffix at the end. Though, this time I'll propose three common options. Zero if it's not present, one if it's index.html, and two
if it's the less common, but still prevalent index.php. At this point, you can also imagine adapting this technique for other parts of the link. For example, many websites end with .com. There's very little need to encode all three of those letters. In fact, there's a finite list of all possible top-level internet domains. So, instead of writing it out letter by letter, we can use one for dot com, two for dot net, three for dot org, and so on. And just in case, we can leave zero empty for new domains that get introduced in the future. The big idea is that if we keep this up, we might not even need a database because the compressed output would already be short enough as is. Of course, in reality, there's a limit to how much you can compress a link, and it has a lot to do with information theory and entropy, but long story short, there's a good reason why link shorteners use databases. That's just the correct approach for keeping outputs consistent. What we're doing here is mostly a gimmick, but if you want to find out how actual database-driven systems work, may I suggest boot.dev, the sponsor of this video. Look, I get it. Programming is intimidating, and learning programming sounds like a lot of work. And yeah, that's the point. It all depends on how much work you put in, and boot.dev knows this. Their job is to help you stay on track and make sure you've got the resources required to put in that work. You can get hands-on with programming in Python, Go, TypeScript, or yes, building databases with SQL. The courses are built by seasoned experts, as well as some fellow YouTube creators, all of whom know exactly what it takes to become a competent engineer. boot.dev puts you in good hands. The way it works is you're given a bit of theory and an assignment. Then, you complete that assignment either by writing code in the browser or by typing commands in a real Linux terminal. Your work is then checked. If everything goes well, you move on. If you get stuck, you can take a look at the example solution, or you can ask for help in the Discord server.
Or, depending on your ethical stance, you can also consult their AI mentor, but they don't shove that in your face. It's a simple idea, but thanks to the quality of the resources, it's very effective. You can try boot.dev right now for free. Though, if you intend to get serious about it, the premium plan is what unlocks the interactive lessons. And they have a generous 30-day no questions asked refunds policy, so there's literally no reason not to give it a shot. You can either click the link in the description or use the QR code on screen, which by the way is generated by the tool I made, and enter code portal runner to get 25% off when signing up for premium.
Okay, so we already talked about optimizing common or redundant parts of the link. But what about the rest? These
parts are certainly unique to the website, so this is where we have to zoom back out and take a look at those two fundamentals, encoding and compression. Encoding is the simpler one, so we'll start with that. If you take a closer look at a traditional shortened link, you'll notice that the unique part comes after the domain, usually preceded by a separating character such as a slash. Normally, this is the unique ID for the back-end database, but in our case, it will contain the encoded and compressed contents of the full input link. So, we'll call it the payload. There are 85 characters that are considered valid in this space, including uppercase and lowercase letters, numbers, brackets, and various other symbols. That is the alphabet of our payload, and the way it works is quite similar to number systems like hexadecimal or base 64. At the end of the day, all digital data is just a number, but instead of using only 10 digits, or two as in binary, we are using 85 digits. That might be a bit hard to visualize since most of us are not used to working with more than 10 digits, but the thing I want you to remember is that going from a smaller base to a bigger base reduces the written length of the number. For example, the domain, that is the part before the slash, only allows for one set of letters, numbers, hyphens, and dots. That is an alphabet of 38 characters, which is less than half of the payload's alphabet. By treating this string as a base 38 number and converting it to base 85, we can already save a few bits. Now, I'm sure some of you have run into a domain that isn't just letters and numbers, but that's because the web browser first converts it to the right character set before fetching the site. Under the hood, it is still letters, numbers, and hyphens. The important part is that by treating the payload as a number, rather than a bunch of symbols, we can pack in way more data. Then, if I need to read a binary value, I can just convert that base 85 number to base two, or binary. If I need to read a decimal value, I can convert it to decimal. If I need to read an English word, I can convert it to base 26, with one digit for each letter of the alphabet. This is still simplifying things a bit, so if you want to read the actual code behind all this, the link will be in the description.
When it comes to the part after the domain, this too tends to have varying character sets. For example, the ID of a YouTube video uses base 64. If our algorithm can spot that and adjust the number base for that specific fragment, we can potentially save a few characters. The way I do this is by splitting the path into parts and detecting the most optimal alphabet to use for each segment. For example, this part is just lowercase English letters, so we can easily encode that using base 26. This part is just a decimal number, so we can encode that with base 10. Basically, the idea is to find the smallest alphabet that fits the given segment and then prefix that segment with an index denoting the alphabet.
This, of course, means that there's a cost to being too specific. If there are eight possible alphabets, then every segment will start with a base eight digit. But, if we go overboard and make a hundred highly specific alphabets, then every segment has to start with a base 100 digit, which is less than ideal. It's a trade-off. So, I decided to stick with eight common categories, each targeting some realistic scenario. The way the path is separated is also kind of interesting. Website links can consist of up to four parts: the host, the file path, the query parameters, and the hash value. Each of these serves a specific purpose and has specific separating characters, but encoding those individually is a bit wasteful.
Instead, we can drop those separators and just mark where the segments change from one type to another. Now, in the best-case scenario, this system works perfectly. A link like this with many predictable character sets reduces nicely. But, what about more nuanced cases? Like, what if there's an uncommon character in the middle of a bunch of common ones? And so far, we've been assuming that the input is effectively random, but that's often not the case. Many blog or forum posts will have the title of the post in the link as plain English. And as many of you probably know, some English letters appear more often than others. What I'm getting at is some kind of system that can spot common patterns, and that is the job of
compression. There are many ways to implement compression, but for something as small as a link, the most sensible approach is a fixed dictionary. The idea is simple. We use fewer bits for more common characters and more bits for less common characters. For example, let's say we live in a world with only four letters, A, B, C, and D. In written words, let's say that A is by far the most common, while the others are respectively less common. If we were to encode a 10-letter word in binary using two bits per character, we'd end up with 20 binary digits. But, assigning the same amount of bits to all letters doesn't make sense when A is obviously so much more common. If we instead used this dictionary, we could encode the same message using only 17 bits. Reading the message is then just a matter of following the dictionary. The first bit is zero, and the only entry that starts with a zero is A. So, that's the first letter. The next bit is one, but there's more than one letter that starts with a one, so we keep going. The next bit is again a one, which is still ambiguous, and the bit after that is a zero, which finally confirms that we're looking at the letter C. After that, we have one, which again, too vague, followed by zero, which confirms the letter B. I think you get the idea. The only question now is, how do we get that dictionary? Clearly, there's some technique to it, because if the bits were just random, there would be too much ambiguity. The algorithm behind this is called Huffman coding. Here's how it works.
We start by pairing up the two least likely outcomes, which in our case are C and D. They get linked together, and their probabilities get summed. Then, we do the same with the next two. In this case, that's the letter B and the group with C and D. Then, we continue with the next two, which now just means connecting A to the group with the rest. And, once there are no more letters left, we're done. We've built a Huffman tree, and in order to get a dictionary from it, we assign zero to all left-facing branches and one to all right-facing branches. Then, to get the Huffman code for a specific letter, we walk down the tree picking up digits as we go. Still, careful viewers may have noticed that something's not quite right. The probability for the letter A was 55%, yet here A takes up the left
half of the tree, and half is 50%.
Likewise, the probability for B was 20%,
yet B takes up a quarter of the tree, and a quarter is 25%. The other letters also have mismatched values. So, what's going on? If we turn those percentages into fractions, it becomes a bit more clear. Those are powers of two, which makes sense because a Huffman tree is a binary tree. It's only ever fully accurate if the input distribution is split into powers of two. And, as you might have guessed, the English alphabet isn't.
Technically, there is a solution, which is to use arithmetic coding, but it's a lot harder to wrap your head around and even harder to implement. And that's not without a lack of trying. In the end, I figured the results just aren't worth it. By my own napkin math and some papers I found comparing the two algorithms, the difference in compression ratio would have been at most 15% in the absolute best-case scenario. And that's not even counting the rest of the link. Realistically, I don't think it would have made any difference. The efficiency of Huffman coding smooths out with a larger character set, and we've got 85 characters, which should be plenty.
So, that's how it works in theory, but in practice, we still need to actually determine the probability of each character showing up in a link. The easiest way to do this is to get a whole bunch of real-world links and count how many times each character shows up. I found this data set on GitHub of 100,000
links from a web crawler, which was an okay starting point, but realistically, these are not the kinds of links that people will be shortening. These are major sites like Google and Facebook on the very top of the web. I needed a more representative sample of the kinds of links that people actually share with other people. So, I found another data set. This time with 1 million links from all across Reddit. This did, of course, introduce a bit of bias. Links to Reddit were by far the most common on Reddit, who would have guessed, followed by some image sharing sites, which also makes sense. But, what I found way more interesting was that stuff like PC Part Picker and Magic: The Gathering was more common than Google. Needless to say, I did adjust the numbers just a bit, but I still think that this result is much better than a surface level crawl of the web. With this data, I could also make Huffman trees for common second level and top-level domains. This way, encoding .com takes only one bit due to
how abundant it is in real world data. Similarly, encoding Google or PC Part Picker also takes very few bits, as instead of encoding those names letter by letter, we can simply refer to a dictionary of the most common websites. Again, both the algorithm and the dictionaries used will be available on GitHub, along with a completely offline tool that lets you generate and decode these links. If Hammer ever does go down, that's the name of the website, by the way, then you can still recover the link as long as you have that tool.
Now, with all that said, how does it actually perform? Well, for most longish links, it does typically reduce the length, even if just by a few characters. But, the end result is also pretty ugly. So, I'm not sure you'd actually want to send this anywhere. And sometimes, the output may even contain more characters than the input. This is because we can only change the part after the domain, meaning that we're working against a 13-character deficit from the get-go. Technically, the URL
can have Unicode characters. Not natively, of course, but the browser makes it work by converting those characters to escape sequences within the allowed alphabet. And let me tell you, there are a lot of Unicode characters. So, if you remember how I said that converting from a smaller base to a bigger one saves on effective characters, then that same thing does apply here. The problem is that most Unicode characters are either special symbols you cannot type on a normal keyboard or letters from foreign languages. If I were to use this Unicode trick, it would have to be a subset that's common enough to be typeable for most people and big enough to be actually worth it.
Did you know that there are close to 4,000 emojis in the latest version of Unicode? Now, granted, some of these are a bit too fresh to be supported on every system, but even just the common ones reduce the effective length of the link by a lot. And depending on the output, you could reasonably remember and type some shorter links. Of course, this is still very much a gimmick. And just like the default encoding, it's still not very practical. Most of this is, as I said, just an experiment. But, I can't say the same for the QR codes. This is an area where I think Hammer might genuinely be useful.
The internet is full of free QR code generators, many of which require you to sign up and or route your input through a link shortener. But, almost all of the sites I've tried just do it wrong. See,
QR codes have four data modes for numbers, alphanumeric symbols, raw bytes, and Japanese kanji. Now, since links aren't just numbers and they usually aren't Japanese, either, that leaves us with the other two. Most online tools use the byte mode, which is convenient in that it lets you represent any binary data. But a byte is a base
256 digit. As we've already discussed, links are at most base 85. So, by using byte
mode for a link, they are wasting space on literally every character. And this isn't even a hard thing to fix. In many cases, all you have to do is just change the link to uppercase, and the QR code will automatically use the alphanumeric set. Sure, this doesn't always work because not all links work in uppercase, but they could have at the very least made their internal link shorteners use uppercase characters. But they don't. They're in lowercase, which forces them to use the much less efficient byte mode. For QR codes, Hammer switches its output to use the exact alphanumeric character set supported by QR codes. Depending on the input, Hammer's QR codes can actually be just as small or even smaller than the ones generated by other online tools with real link shorteners, simply because someone actually paid attention to how these things work instead of cloning an open-source tool and putting a subscription model on it.
Yes, I am a bit upset. What gave it away? The last thing I want to talk about is how I actually got the domain for this thing. Obviously, if you're building a link shortener, you want the base of the link to be as short as possible. Four-letter domains like this one are very hard to come across these days, especially for reasonable prices. My strategy was to sift through Cloudflare's domain rankings in reverse order, checking the availability of each one. The idea was that less popular domains probably won't have all their four-letter slots sold out yet. And after I found one that worked, I just had to come up with a memorable name that wasn't already taken. And I think Hammer is a pretty good fit for a website focused on aggressively compressing links.
In case you're curious about how far this idea can be pushed, a friend of mine actually made a small transformer model that compresses the links even more aggressively. Now, granted, this does require loading nearly 300 megabytes of model data and doing a little bit of compute client-side before you can decompress even a single link, but the results are far better than anything I could do by hand. So, if you want to check out that version or my project, then the links will be in the description. Down there, you'll also find a link to boot.dev. Seriously, if you have even a mild curiosity for coding or software engineering, go check them out. A bunch of their stuff is free for life, and even the premium plan is refundable within 30 days. So, there's no excuse to not at least try it out.
All right, I'll see you around. Thanks for watching.





