When should I use uuid.uuid1() vs. uuid.uuid4() in python?

rocketmonkeys picture rocketmonkeys · Nov 23, 2009 · Viewed 98.9k times · Source

I understand the differences between the two from the docs.

uuid1():
Generate a UUID from a host ID, sequence number, and the current time

uuid4():
Generate a random UUID.

So uuid1 uses machine/sequence/time info to generate a UUID. What are the pros and cons of using each?

I know uuid1() can have privacy concerns, since it's based off of machine-information. I wonder if there's any more subtle when choosing one or the other. I just use uuid4() right now, since it's a completely random UUID. But I wonder if I should be using uuid1 to lessen the risk of collisions.

Basically, I'm looking for people's tips for best-practices on using one vs. the other. Thanks!

Answer

Georg Schölly picture Georg Schölly · Nov 23, 2009

uuid1() is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the uuid and the computer, as the mac address gets used to make it unique across computers.

You can create duplicates by creating more than 214 uuid1 in less than 100ns, but this is not a problem for most use cases.

uuid4() generates, as you said, a random UUID. The chance of a collision is really, really, really small. Small enough, that you shouldn't worry about it. The problem is, that a bad random-number generator makes it more likely to have collisions.

This excellent answer by Bob Aman sums it up nicely. (I recommend reading the whole answer.)

Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.