Notes on UUID v7 in .NET 9

Jul 30, 2024

Introduction to UUID v7 in .NET 9

  • Presenter: Nick
  • Focus: New type of ID in .NET 9 intended to replace GUIDs and integers in database scenarios.

GUIDs and Their Limitations

  • GUID (Globally Unique Identifier) and its issues in relational databases.
  • Performance problems when used as primary keys.
  • Typically default to auto-incremented integers for better performance, which has its own set of challenges.

Introducing UUID v7

  • New ID type: UUID version 7 (UUIDv7).
  • Builds on existing knowledge of GUIDs but addresses performance issues.

Differences from GUID

  • GUID generally refers to UUID version 4 (UUIDv4).
  • UUIDv4 generates random values and is designed to minimize clashes but lacks order.
  • UUIDv7 uses Unix timestamp for order, solving database performance problems.

Implementation in C#

  • Creating a GUID in C#: Guid new Guid();
  • To create UUIDv7 in .NET 9: Guid create version 7; this will utilize the same method as GUID but incorporate the time component.
  • Supports passing DateTimeOffset to set the timestamp:
    timeProvider: system.getUTCTimeNow();
    
  • UUIDv7 is structured such that the first bits are time-stamped establishing ordering.

Performance Consideration

  • Comparison of UUIDv4 and UUIDv7 generation times:
    • UUIDv4: 37 nanoseconds
    • UUIDv7: 70 nanoseconds
  • UUIDv7 takes longer to generate (~40 nanoseconds slower) but has no memory allocation difference.
  • Despite a performance hit, the advantages of using UUIDv7 outweigh this delay, particularly for database keys.

Advantages of Using UUIDv7

  • More efficient in modern database systems where order and uniqueness are conflicting requirements.
  • Should not replace existing UUIDs in existing systems without due consideration of clashes but can be beneficial for new systems.
  • Flawlessly integrates into existing applications due to its mapping back to the GUID type.

Additional Information

  • Current promotions on courses related to this topic, including OpenTelemetry.

Conclusion

  • Call to action: Share thoughts and experiences regarding ID types in the comments.
  • Reminder to keep coding!