Search code examples
javadatabaserandomuuiduniqueidentifier

Is it a good idea to combine the ideas of version 1 and version 4 UUIDs?


I want to generate time-based UUIDs, but I don't want any part of the UUID value to be based on the machine they are generated on.

Version 1 UUIDs are time-based (with the first 64 bits representing time, and the second 64 bits representing the MAC address of the machine they are generated on).

Version 4 UUIDs are not time-based, but are generated from random numbers.

In my case, I want to be able to generate multiple time-based UUIDs for the same timestamp, on the same machine - and I want those UUIDs to be unique. The UUIDs must still be time-based, so that sorting them lexicographically gives an ordering consistent with the timestamps used to create them.

Is there any good reason not to generate UUIDs with my own scheme - where the first 64 bits would represent the timestamp (like version 1) and the second 64 bits would be randomly generated (like version 4)?


Solution

  • ULIDs meet your requirements pretty much exactly. You may need to generate them application-side since it looks like native database support seems lacking, but it's a drop-in for a 128bit UUID so you simply need to encode it as hex to insert into any UUID type column.