We use UUIDs for our primary keys in our db (generated by php, stored in mysql). The problem is that when someone wants to edit something or view their profile, they have this huge, scary, ugly uuid string at the end of the url. (edit?id=.....)

Would it be safe (read: still unique) if we only used the first 8 characters, everything before the first hyphen?

If it is NOT safe, is there some way to translate it into something else shorter for use in the url that could be translated back into the hex to use as a lookup? I know that I can base64 encode it to bring it down to 22 characters, but is there something even shorter?

EDIT I have read this question and it said to use base64. again, anything shorter?

Comments

Are you hoping that all but the first 8 characters of the UUID are superfluous? They're there to make it unique. Either way, if it's 8 instead of 22 characters, you really think that will make a friendlier user experience? I wouldn't spend time worrying about that. I've seen crazier URIs in the location bar and it certainly doesn't affect the site's usability.

Written by webbiedave

i was thinking something similar to how an md5 hash can be shortened ( read this somewhere but can't remember where) because the characters have a uniform distribution for a certain substring.

Written by helloandre

I see. Crypto hash functions are expected to have acceptable levels of collision occurrence and truncating the output string merely increases that chance. Your situation cannot afford any chance of "collision" (one id pointing to numerous records).

Written by webbiedave

Accepted Answer

Shortening the UUID increases the probability of a collision. You can do it, but it's a bad idea. Using only 8 characters means just 4 bytes of data, so you'd expect a collision once you have about 2^16 IDs - far from ideal.

Your best option is to take the raw bytes of the UUID (not the hex representation) and encode it using base64. Or, just don't worry much, because I seriously doubt your users care what's in the URL.

Written by Nick Johnson
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki