I hope someone can answer this question.
How does the UuidCreateSequential method in the rpcrt4.dll class use to seed it's guids?
I know this much:
Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.
The reason behind the question is. If I use this function to generate sequential GUIDs in a web cluster, how can I ensure that the GUIDs are close to a range of GUIDs without the potential of the GUID being duplicated?
Best Answer
The Win32
UuidCreateSequential
creates aVersion 1
uuid.Here's some sample version 1 uuid's created on my computer using
UuidCreateSequential
:The first thing that's important to note that these uuid contain my machine's MAC address (
B8AC6FBE26E1
):So if you're hoping for different computers to generate guid's that are "close" to each other, you're going to be disappointed.
Let's look at the rest of the values.
Seven and a half bytes of the remaining 10 bytes are a timestamp; the number of 100ns intervals since 00:00:00 15 October 1582. Rearranging those timestamp bytes together:
You can see that guid's created on the same machine by
UuidCreateSequential
will be together, as they are chronological.The
1
you see is the version number, in this case meaning a time based uuid. There are 5 defined versions:UuidCreateSequential
)UuidCreate
)Giving:
The last word contains two things.
The lower 12 bits is the machine-specifc Clock Sequence number:
This machine-wide persistent value is incremented if:
So, again, any guid's created by
UuidCreateSequential
will (ideally) have the same Clock Sequence number, making them "near" to each other.The final 2 bits, is called a Variant, and is always set to binary
10
:So there you have it. Sequential guid's are sequential; and if you create them on the same machine they will be "near" to each other in a database.
But you want to know what actually happens with two sequential UUID's created on different computers.
Using our newfound knowledge of Version 1 guids, let's construct two guid's for the same timestamp from different machines, e.g.:
First let's insert a bunch of guid's with sequential timestamps. First create a temporary table to store our guid's in, and cluster by the guid:
Now insert the data:
Note: i insert them in random timestamp order, to illustrate that SQL Server will cluster them.
Get the rows back and see what order they're in sequential (timestamp) order:
Now lets insert guid's with:
Insert the new guids from a "different" computer:
And get the results:
So there you have it. SQL Server order's Node before Timestamp. Uuid created from different machines will not be clustered together. Would have been better if it hadn't done so, but whatcha gonna do.