Menu

Wednesday, 18 December 2024

UUID v7 in .NET 9

 

About


.NET 9 comes up with so many excited features as discussed in earlier posts. This post, we are focusing on UUID v7 feature.
Please refer the following links for other .NET 9 LINQ features

The earlier versions of .NET, we've used Guid.NewGuid() (version 4) method generate UUIDs. It simply generates unique identifier which being used in our projects.

The present .NET 9 version supports UUID v7 format of code like Guid.CreateVersion7(). This generated UUID incorporated timestamp already in it. So, This is really very helpful when we stored this UUID in database level to Sort it  based on creation time.

The structure of UUID format is as follows.

 48-bit timestamp || 12-bit random ||    62-bit random

48-bit timestamp: It represents the number of milliseconds since Unix epoch. so, It provides info about creation time.
12-bit random: It adds randomness to ensure uniqueness in within same millisecond.
62-bit random: It also ensures overall uniqueness by offering randomness of entropy.

Code Examples

Before .NET 9

var guid = Guid.NewGuid(); // v4 UUID

.NET 9

var guidv7 = Guid.CreateVersion7(); // v7 UUID
var guidv7 = Guid.CreateVersion7(); // v7 UUID
This by default inherits UtcNow timeformat.

Lets explore about Sort feature by creating multiple UUIDs custom way.

//Just added the guid by adding different time provider by add/subtract minutes to current Utc time.

var guidList = new List
{
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow()),
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow().AddMinutes(-10)),
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow().AddMinutes(10)),
    Guid.CreateVersion7(TimeProvider.System.GetUtcNow().AddMinutes(-20))

};
//write the guids in whatever list contains.
foreach (var v7guid in guidList)
{
    Console.WriteLine(v7guid.ToString());
}

Console.WriteLine("=====================");
//Order the guidlist and then write list.
//The result you can identify guids are ordered based on creation time.
var sortedList = guidList.OrderBy(x => x).ToList();
foreach (var v7guid in sortedList)
{
    Console.WriteLine(v7guid.ToString());
}

Screenshots









Summary


We have explored UUID v7 feature in .NET 9and its advantages of inbuilt timestamp which can be really helpful to order created UUIDs in database level. So, lets start use in our project and get benefitted.

Stay tuned for more articles. Thanks for reading!!



No comments:

Post a Comment