DEV Community

Cover image for UUID v7 Now in .NET 9
Islam nabil
Islam nabil

Posted on

UUID v7 Now in .NET 9

In NET 9 (preview 7), developers can use the new feature: UUID v7. This upgraded UUID version incorporates a timestamp into the typically random UUID, delivering substantial advantages for databases and other systems needing sortable unique identifiers.

What is UUID v7?

UUIDs (Universally Unique Identifiers) are designed to help developers create unique identifiers that ensure uniqueness without needing to coordinate with other systems. These identifiers are especially useful in distributed systems, where records are created across multiple systems and databases. While using a UUID as a primary key may seem like a good idea, it can significantly harm database performance if used incorrectly.

Different UUID versions

Below is an overview of the different UUID versions and how they function.

UUIDv1

UUID version 1 is known as time-based. Some parts of the UUID are derived from the timestamp and device details, making it possible to trace it back to the source device. However, this could potentially raise privacy concerns in certain situations.

UUIDv2

UUID version 2 uses the user identifier instead of the reduced time portion, which can lead to an increased likelihood of duplicate values. This version is not commonly used due to redundancy issues.

UUIDv3 and UUIDv5

These versions operate in a deterministic manner by using namespace and name values to generate a unique UUID. Version 3 uses the MD5 algorithm, while version 5 uses SHA-1.

UUIDv4

Version 4 heavily relies on randomness, resulting in a temporally disorganized UUID that is difficult to track.

UUIDv6 and UUIDv7

Versions 6 and 7 are sequential editions. UUIDv6 follows the same basic structure as UUIDv1 with some modifications that emphasize the timing aspect, while UUIDv7 uses the Unix Epoch timestamp and is a better choice for performance due to its chronological ordering.

How UUID v7 Works

UUID v7 consists of three segments: a 48-bit timestamp, a 12-bit random segment, and a 62-bit random segment.

  • The 48-bit timestamp represents the number of milliseconds since the Unix epoch.
  • The 12-bit random segment adds randomness to ensure uniqueness within the same millisecond,
  • while the 62-bit random segment ensures overall uniqueness, offering 122 bits of entropy.

This is particularly useful for databases where insertion order is important and can help in performance optimizations.

ET9 and UUIDv7

In .NET 9, UUIDv7 support was introduced which provides a way to generate ordered UUIDs based on timestamp. Developers can use the Guid.CreateVersion7() function to generate UUIDv7 with timestamp customization support.

Guid uuidV7 = Guid.CreateVersion7(); // Use DateTime.UtcNow

Enter fullscreen mode Exit fullscreen mode

Top comments (0)