Ain't me in the photo. Just an Unsplash one...
As my next project, I decided to build a url-shortener. I Googled how other folks had done it and I started to read very complicated posts, which made me very confused. I decided to stop reading and plung into the code (like the one in the photo!). I put some thought on the architecture. I even draw some charts! Nothing too fancy, no worries. The architecture I went with is the follow, please give me feedback of any sort if you think I could do better!
- User types a url client side.
- I pass this url to the server in the body.
- The server grabs the body and stores it in a row of the database alongside a randomly generated string of characters.
- The server returns this random string to the client and it displays it back to the User (i.e. bit.ly/{whatever the random string}
- Cool, now the User can go and post it in places. Once someone hits domain.whatever/{randomly generated string} the following happens.
- domain.whatever is a React app. I use
useEffect()
and it has an API call to the server, passing the randomly generated string as url parameter. - The server grabs the parameter, looks it up in the database, fetches the real url, returns it to the client.
- The client redirects from domain.whatever/{randomly generated string} to the full url that is returned from the server.
Voilà! Please, give me feedback. Thanks for reading!
Top comments (5)
Nice approach. You didn’t shade light to how you’re going to ensure that the random string remains unique. Consider a scenario where you have a million requests per second, how do you ensure that no url is lost due to duplicate random string.
Great point, Chinedu. I am saving the new random string in the DB table alongside the long URL. If the next request generates the same short string and finds it in the DB when querying it, it will create a new one before returning it to the client. Thoughts?
Cool, I think that makes sense. You'd probably index the random string column to enhance the performance because for every new record, you'd search for a duplicate random string.
React seems to be huge overkill for such a simple thing
I know! I wanted to practise React after couple of months on Vanilla JS