Search code examples
pythonuuid

How to generate a unique ID which is time-like sortable?


Is there a way to generate a universally unique ID that has always increasing values by the "time" it is generated? We can assume UTC timezone only for this problem.

What I specifically mean with time-like sort-ability is:

from time import sleep

id1 = generate_unique_id()
sleep(1)

id2 = generate_unique_id()
sleep(1)

id3 = generate_uniqueid()

assert id1 < id2
assert id2 < id3

So id1 could be "abcdefgh-ksfn-123", id2 could be "abcdefgh-ksfn-231" etc.

I do not really wish to use UTC timestamps directly as an ID since that does bear a bit of information I wish not to expose to the users with this ID. We can also assume that this ID will be generated concurrently, i.e. there is a chance that time parameters are identical for 2 separate executions (a tiny chance, but it is there), yet the ID should be different.

Does anything like that exist already in Python/3rd party modules? If not what would be the best approach? Is it even possible to generate ID like this?


Solution

  • Yes, there is. You can use uuid and then the uuid1() function provides exactly what you want:

     uuid.uuid1(0, 0)
    

    will supply a UUID type 1, with node ID of 0 and clock sequence of 0. The remaining 60 bits will be a monotonically increasing time sequence, that will be therefore sortable.

    You can use a different node ID for each process, if you want (then, the sorting will happen in node order: first all UUIDs of node A, then all UUIDs of node B), or the PID as clock sequence to ensure that no two processes will get the same UUID (in that case, when sorting, the UUIDs will be sorted in time order, then in PID order):

    So to speak,

    UUID  = NODENODE-NODE-CLOCKCLOCKCLOCKCLOCK-SEQSEQ