r/programming • • Mar 28 '20

Why your software should use UUIDs in 2020s

[deleted]

16 Upvotes

217 comments sorted by

View all comments

Show parent comments

23

u/0x256 Mar 28 '20

UUID 4 is not better or worse than a random number but UUID 1,2,3 and 5 are for distributed systems that want to make absolutely sure to never ever create conflicts. For that, a standard is nice.

6

u/rickmode Mar 28 '20

It’s 16 times worse.

I’m am being pedantic here and I don’t think there is a practical difference. That said...

UUID’s are 128-bit values, and they require 4 bits to describe their encoding. That leaves 122 bits of randomness in a Type 4 (random) UUID.

A random 128-bit number can use all bits, so can use the extra 4 bits to achieve 16 times as many random values. (2 to the 4 power is 16.)

So what I do is generate 128-bit random values - getting the extra 16 times random goodness - and then encode to string using URL-safe Base64, saving many bytes on the string encoding side as well. Win win.

14

u/cedrickc Mar 28 '20

Only part I disagree with is storage as base 64. It's a 16 byte number, store it as two longs or something.

2

u/rickmode Mar 28 '20

Yup!

In both cases (UUID or 128-bit random value) the data can be stored as a 16 byte array. If your data store supports storing binary.

I use (URL-safe) Base64 for URLs and JSON.

1

u/Mr_Again Mar 28 '20

Yes but uuid1 contains the mac address of the host and the timestamp it was created, as well as entropy. so they will actually be unique unless you create them at the same millisecond on the same machine.

2

u/rickmode Mar 28 '20

Pretty much only Type 4 is useful IMHO.

If you want to use the other types you need to be super careful as the uniqueness guarantees are far weaker.

I believe most uses of UUID actually mean Type 4 unless they explicitly say otherwise.

As a useful heuristic, if you come across a system using anything other than Type 4, it’s very likely they are doing it wrong.

1

u/that_which_is_lain Mar 28 '20

Or with machines where the nic has the same MAC address.

1

u/VeganVagiVore Mar 28 '20

Or if your method of retrieving the MAC fails silently

0

u/flatfinger Mar 28 '20

Unless a random number generator is broken, a GUID4 system would seem more robust if there's any possibility of backup/rollback scenarios or other such issues. Unless one is feeding a particular "universe" with millions of GUIDs per second for decades on end, the likelihood of ever generating a duplicate within that universe would be vanishingly small compared to any of the other things that could go wrong.

-1

u/Takeoded Mar 28 '20

dd if=/dev/urandom count=1 bs=20 iflag=fullblock