Search code examples
urlshort-url

how to generate short, unique urls


I am trying to generate unique, short urls for items on my site. For example, a user might add an item and the resulting url would be something like:

http://example.com/item/abc

I was hoping for the unique identifier to be made up of 3 or 4 characters, where the characters are letters and numbers. I thought instead of randomly generating the strings and then making sure they are unique and haven't been used yet, I could generate them all ahead of time and store them in a database. Then when a user adds an item I could just select the next shortened url string from the database and assign it to that item. Is this a good way to solve this? Are there better ways? I thought it would make it simpler since they are already generated. However, I could also see a potential race issue with two items being assigned the same identifying string, and I'm not sure if LOCK TABLES would be the best solution or not.

Also, without using LOCK TABLES, could something like this guarantee no race conditions in MySQL?

update ids set item_id=1 WHERE id=(SELECT id FROM ids WHERE item_id IS NULL LIMIT 1);

And then I could select the id for item that has id 1? During that query would no other query be able to claim it?


Solution

  • For anyone who finds this question later, I followed the process suggested in the link that @Swapnil suggested:

    How to code a URL shortener?

    There were some implementations listed there for various languages, but I am using perl and that wasn't listed there and I couldn't seem to find a perl one that already existed elsewhere. So if it helps anyone in the future, I wrote this perl module to help with url shortening:

    Short::URL

    Thanks to @Swapnil for pointing me to the right place.