Start Debugging

Is Guid.CreateVersion7() sequential in .NET? Why two v7 GUIDs compare out of order

Guid.CreateVersion7() puts a millisecond timestamp in the top 48 bits and random data everywhere else, so two values created in the same millisecond come out in random order. Measured on .NET 11.0.0: 50% of back-to-back pairs are out of order, SQL Server sorts v7 values as if they were random, and EF Core only uses v7 by default on Npgsql. How to get a strictly monotonic UUIDv7 and how to opt in per EF Core provider.

This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process

No, not strictly. Guid.CreateVersion7(), added in .NET 9 and unchanged in .NET 11, writes the current Unix time in milliseconds into the first 48 bits and fills the remaining 74 non-version bits with random data. Values created in different milliseconds sort by time; values created in the same millisecond sort randomly. In a tight loop on .NET 11.0.0 almost every value shares its millisecond with its neighbour, and 49.98% of consecutive pairs compared as “older” than the one before. If you need strict ordering, keep a per-process counter in the 12-bit rand_a field (RFC 9562, section 6.2, method 1), and if your database is SQL Server, know that uniqueidentifier ordering ignores the timestamp entirely, so v7 is no better than Guid.NewGuid() there.

The rest of this post shows the measurements, explains the four orderings that disagree with each other, and covers what EF Core 11 actually generates for a Guid key on SQL Server, SQLite, and PostgreSQL.

Where the question comes from

Two Stack Overflow questions keep coming up. In the first, someone calls Guid.CreateVersion7() twice and expects guid2.CompareTo(guid1) to always return 1. It does not: sometimes it returns -1. In the second, someone upgrading to EF Core 9 wants every Guid key generated with Guid.CreateVersion7() and asks whether a custom value generator plus a model convention is the right way. Both questions rest on the same assumption, that “version 7” means “sequential”, and both answers depend on which ordering you mean and which database you store the value in.

What CreateVersion7 actually writes

The implementation in System.Private.CoreLib is short. This is the .NET 11 source, identical to the .NET 9 version:

// dotnet/runtime, release/11.0, src/libraries/System.Private.CoreLib/src/System/Guid.cs
public static Guid CreateVersion7() => CreateVersion7(DateTimeOffset.UtcNow);

public static Guid CreateVersion7(DateTimeOffset timestamp)
{
    Guid result = NewGuid();

    long unix_ts_ms = timestamp.ToUnixTimeMilliseconds();
    ArgumentOutOfRangeException.ThrowIfNegative(unix_ts_ms, nameof(timestamp));

    Unsafe.AsRef(in result._a) = (int)(unix_ts_ms >> 16);
    Unsafe.AsRef(in result._b) = (short)(unix_ts_ms);

    Unsafe.AsRef(in result._c) = (short)((result._c & ~VersionMask) | Version7Value);
    Unsafe.AsRef(in result._d) = (byte)((result._d & ~Variant10xxMask) | Variant10xxValue);

    return result;
}

It starts from a random v4 GUID, overwrites the first 48 bits with the timestamp, and patches the version and variant bits. There is no counter, no “last value” state, and no sub-millisecond precision. That matches the RFC 9562 layout for UUIDv7 (unix_ts_ms, ver, rand_a, var, rand_b), with rand_a and rand_b both random. The RFC lists monotonicity within a millisecond as something an implementation MAY add in section 6.2; .NET chose not to. The API docs say the same thing in one line: the method “seeds the rand_a and rand_b sub-fields with random data”.

You can see it in two consecutive values from the test run below. The first 12 hex digits are the same millisecond, the rest is random:

01a23bcb-7c2c-7385-9d20-734bbc90634c   Version=7
01a23bcb-7c2c-7815-a43d-4766334dac60

Measuring how often v7 values come out of order

The test program generates one million values in a loop and counts how many consecutive pairs are “backwards” under five different orderings. It also generates values with a 2 ms sleep in between, and runs the same checks on EF Core’s SequentialGuidValueGenerator and on a monotonic generator shown later in this post. Environment: .NET SDK 11.0.100, runtime 11.0.0, macOS 27.0.1 on Apple silicon, Release build, EF Core 11.0.0, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0.

// .NET 11.0.0, C# 15, net11.0 console app
using System.Data.SqlTypes;

static void Report(string name, Guid[] g)
{
    int cmpBack = 0, strBack = 0, leBytesBack = 0, beBytesBack = 0, sqlBack = 0;
    Span<byte> x = stackalloc byte[16], y = stackalloc byte[16];
    for (int i = 1; i < g.Length; i++)
    {
        if (g[i].CompareTo(g[i - 1]) < 0) cmpBack++;
        if (string.CompareOrdinal(g[i].ToString(), g[i - 1].ToString()) < 0) strBack++;

        g[i].TryWriteBytes(x); g[i - 1].TryWriteBytes(y);                 // same bytes as ToByteArray()
        if (x.SequenceCompareTo(y) < 0) leBytesBack++;

        g[i].TryWriteBytes(x, bigEndian: true, out _);                    // same bytes as ToByteArray(true)
        g[i - 1].TryWriteBytes(y, bigEndian: true, out _);
        if (x.SequenceCompareTo(y) < 0) beBytesBack++;

        if (new SqlGuid(g[i]).CompareTo(new SqlGuid(g[i - 1])) < 0) sqlBack++;  // SQL Server order
    }
    double pct(int n) => 100.0 * n / (g.Length - 1);
    Console.WriteLine($"{name}: Guid.CompareTo {pct(cmpBack):F2}%, ToString {pct(strBack):F2}%, " +
        $"LE bytes {pct(leBytesBack):F2}%, BE bytes {pct(beBytesBack):F2}%, SqlGuid {pct(sqlBack):F2}%");
}

var v7 = new Guid[1_000_000];
for (int i = 0; i < v7.Length; i++) v7[i] = Guid.CreateVersion7();
Report("CreateVersion7, tight loop", v7);

var spaced = new Guid[2_000];
for (int i = 0; i < spaced.Length; i++) { spaced[i] = Guid.CreateVersion7(); Thread.Sleep(2); }
Report("CreateVersion7, one per ~2 ms", spaced);

Results from one run (percent of consecutive pairs where the newer value sorts before the older one):

GeneratorGuid.CompareToToString() ordinalToByteArray() bytesToByteArray(true) bytesSqlGuid (SQL Server)
Guid.CreateVersion7(), tight loop, 1,000,000 values49.98%49.98%49.99%49.98%50.04%
Guid.CreateVersion7(), one per ~2 ms, 2,000 values0.00%0.00%1.00%0.00%50.33%
EF Core SequentialGuidValueGenerator, 1,000,000 values49.99%49.99%50.01%49.99%0.00%
Monotonic v7 (below), 1,000,000 values0.00%0.00%0.37%0.00%50.02%

In the tight loop, 999,725 of the 999,999 consecutive pairs shared a millisecond, so the comparison was decided by random bits, and half of them went “backwards”. With 2 ms between calls, every pair has a distinct timestamp and CompareTo never saw a regression. That is the whole answer to the first Stack Overflow question: v7 is time-ordered across milliseconds and unordered within one.

Real workloads sit between the two rows. A web API creating one order per request rarely produces two keys in the same millisecond. A batch import, an AddRange of 10,000 entities, or a message consumer draining a queue produces thousands per millisecond, and those keys are in random order relative to each other.

Four orderings, and only three of them agree

The table has more columns than the question needs because “sorted” means different things in different places.

Guid.CompareTo and ToString() agree. CompareTo compares _a as an unsigned 32-bit integer, then _b, _c, and the remaining eight bytes in order, which is exactly the order of the hex digits in the string form. So for v7, CompareTo, LINQ’s Order(), and an ordinal sort of the strings all put the timestamp first.

ToByteArray(bigEndian: true) also agrees. Big-endian bytes are the RFC 9562 wire format, so comparing them with SequenceCompareTo gives the same answer as CompareTo. This is the order PostgreSQL uses for its uuid type, which is why v7 helps B-tree indexes there.

ToByteArray() (no argument) does not agree. It writes _a, _b, and _c in little-endian order on every platform, so the first byte it emits is the least significant byte of the timestamp’s upper 32 bits. Comparing those arrays byte by byte gives the 1.00% and 0.37% regressions in the table even when CompareTo reports none. The accepted answer to the first question recommends comparing raw bytes via MemoryMarshal.AsBytes, which is the same little-endian layout. Use TryWriteBytes(span, bigEndian: true, out _) if you need a byte-wise comparison that matches the RFC.

SQL Server is the outlier. Its uniqueidentifier comparison treats the last six bytes as most significant, then the two bytes before them, and so on toward the front. Microsoft’s documentation on comparing GUID and uniqueidentifier values describes the rule, and System.Data.SqlTypes.SqlGuid.CompareTo implements it, which is what the last column uses. For a v7 value, those last six bytes are rand_b: pure randomness. The timestamp at the front is compared last. So a clustered index on a uniqueidentifier column filled with Guid.CreateVersion7() gets inserts at random positions, exactly like Guid.NewGuid(). Even values 2 ms apart came out 50.33% “backwards” under SQL Server’s rules.

What EF Core 11 generates for a Guid key

When an entity has a Guid primary key and you do not set it, EF Core generates the value client-side when the entity is added, before SaveChanges. Which generator runs depends on the provider. The test adds two entities to a context per provider and prints the keys and Guid.Version (available since .NET 9). No database connection is opened, because the value is generated by Add:

// .NET 11.0.0, EF Core 11.0.0, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0
public sealed class Order { public Guid Id { get; set; } }

public sealed class SqlServerCtx : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder o) => o.UseSqlServer("Server=.;Database=x");
    public DbSet<Order> Orders => Set<Order>();
}
// SqliteCtx and NpgsqlCtx are identical apart from UseSqlite / UseNpgsql

var a = new Order(); var b = new Order();
ctx.Add(a); ctx.Add(b);
Console.WriteLine($"{a.Id} v{a.Id.Version}  {b.Id} v{b.Id.Version}");

Output:

SqlServer  d18eba88-09ed-4b25-0c37-08df5135b887 v4  04d6be56-027a-4a59-0c38-08df5135b887 v4
Sqlite     6b70f087-dd55-4fcc-b88d-287df5f86233 v4  094641b5-0632-46a4-9d5f-ff2281410812 v4
Npgsql     01a23bcb-97df-7bd9-85b5-e85d36816692 v7  01a23bcb-97e0-7a05-bf8b-71275cb81d74 v7
  • SQL Server uses SequentialGuidValueGenerator. It takes Guid.NewGuid() and overwrites bytes 8 to 15 with an incrementing counter seeded from DateTime.UtcNow.Ticks, arranged so SQL Server’s comparison sees an increasing value (note 0c37 then 0c38 with the same tail). The version nibble stays 4. Under Guid.CompareTo these look random; under SqlGuid they were 0.00% out of order across a million values. This is the right default for SQL Server, and switching it to v7 makes index locality worse, not better.
  • SQLite (and any provider without its own selector) uses GuidValueGenerator, which is just Guid.NewGuid().
  • PostgreSQL with Npgsql’s provider uses NpgsqlSequentialGuidValueGenerator, which since Npgsql EF 9.0 is a one-line call to Guid.CreateVersion7(). Note that the two keys above are in different milliseconds (97df and 97e0); within one AddRange most keys share a millisecond and inherit the random intra-millisecond order measured above.

So the second Stack Overflow question already has a partial answer: on Npgsql 9 and later you get v7 for free. On SQL Server you should not want it. On SQLite and other providers, opt in explicitly.

Opting in to v7 keys per property or for the whole model

A value generator is a small class:

// .NET 11.0.0, EF Core 11.0.0
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ValueGeneration;

public sealed class GuidV7ValueGenerator : ValueGenerator<Guid>
{
    public override bool GeneratesTemporaryValues => false;
    public override Guid Next(EntityEntry entry) => Guid.CreateVersion7();
}

For one property, HasValueGenerator is enough:

protected override void OnModelCreating(ModelBuilder b)
    => b.Entity<Order>().Property(e => e.Id).HasValueGenerator<GuidV7ValueGenerator>();

With that configuration the SQLite context printed 01a23bcb-97f1-76ef-bd24-93e19cefe957 v7. For every Guid key in the model, the IModelFinalizingConvention from the question works, and so does a loop at the end of OnModelCreating:

// .NET 11.0.0, EF Core 11.0.0
protected override void OnModelCreating(ModelBuilder b)
{
    // ... entity configuration ...

    foreach (var property in b.Model.GetEntityTypes()
                 .SelectMany(t => t.GetProperties())
                 .Where(p => p.ClrType == typeof(Guid) && p.ValueGenerated == ValueGenerated.OnAdd))
    {
        property.SetValueGeneratorFactory((_, _) => new GuidV7ValueGenerator());
    }
}

Avoid the ValueConverter approach from the accepted answer to that question (a Guid-to-Guid converter that swaps Guid.Empty for Guid.CreateVersion7() on the way to the database). The key generator runs in Add, before any conversion, so the converter never sees Guid.Empty. With that converter on SQLite, the key was v4 right after Add, and the row written by SaveChanges held the same v4 value; on SQL Server the key came from SequentialGuidValueGenerator as usual. The converter only does anything if value generation is turned off for the property, and then the entity and the row disagree: with ValueGeneratedNever() added, the entity still held 00000000-0000-0000-0000-000000000000 after SaveChanges while the row held 01A23BCD-70FC-71E6-A36D-DDD3801C40C9.

The model-wide loop above was checked on SQLite with two entity types: both keys came out v7 after Add.

One trap that bit the test program: EF Core caches the built model per context type. A context that takes a useV7 flag in its constructor and branches on it inside OnModelCreating builds the model once, for whichever instance comes first, and every later instance reuses it. The first version of the test printed v4 for the “v7” context for exactly that reason. Use a separate context type or an IModelCacheKeyFactory if the configuration really varies.

A strictly monotonic UUIDv7 in under 40 lines

If you need values that never go backwards within a process, for example because you page with WHERE id > @last or use the key as a cursor, implement RFC 9562 method 1: use the 12-bit rand_a field as a counter that restarts at a random value each new millisecond.

// .NET 11.0.0, C# 15 (System.Threading.Lock needs .NET 9+)
public static class MonotonicGuidV7
{
    private static readonly Lock Gate = new();
    private static long _lastMs = -1;
    private static int _counter;

    public static Guid Next()
    {
        long ms; int counter;
        lock (Gate)
        {
            long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            if (now > _lastMs)
            {
                _lastMs = now;
                _counter = Random.Shared.Next(0, 0x800); // seed in the lower half of 12 bits
            }
            else if (++_counter > 0xFFF)
            {
                _lastMs++;                               // counter exhausted: borrow the next millisecond
                _counter = Random.Shared.Next(0, 0x800);
            }
            ms = _lastMs; counter = _counter;
        }

        Guid g = Guid.CreateVersion7(DateTimeOffset.FromUnixTimeMilliseconds(ms));
        Span<byte> b = stackalloc byte[16];
        g.TryWriteBytes(b, bigEndian: true, out _);
        b[6] = (byte)(0x70 | (counter >> 8));             // version 7 + high 4 bits of the counter
        b[7] = (byte)counter;                             // low 8 bits of the counter
        return new Guid(b, bigEndian: true);
    }
}

It reuses Guid.CreateVersion7(DateTimeOffset) for the timestamp, version, variant, and the 62 random rand_b bits, then overwrites rand_a. In the test it produced a million values with zero regressions under CompareTo, and 800,000 values from 8 parallel threads with no duplicates. Plug it into the EF Core generator above by returning MonotonicGuidV7.Next() instead.

Three things to know before using it:

  • It is per process. Two instances of a service each have their own counter, so their keys interleave by millisecond and are not globally monotonic. Only a single writer, or the database itself, can give you a global sequence.
  • The clock can run ahead. If you sustain more than roughly 2,048 values per millisecond (the tight loop on this machine produced about 3,600), the counter overflows and the code borrows the next millisecond, so embedded timestamps drift ahead of wall-clock time until the load drops. If the system clock steps backwards, the same branch keeps the old timestamp, which is what the RFC recommends.
  • The lock is a serialization point. For most applications it is invisible next to an insert. If you generate keys from many threads in a hot loop, measure it.

Which one to use

  • PostgreSQL: Guid.CreateVersion7() is a good key. Npgsql already uses it. Add a monotonic generator only if you rely on strict ordering within a millisecond.
  • SQL Server: keep EF Core’s default SequentialGuidValueGenerator, or let the database assign NEWSEQUENTIALID() with HasDefaultValueSql("NEWSEQUENTIALID()"). A v7 value is random as far as uniqueidentifier ordering is concerned. If you want a v7 value for other reasons (an externally visible, time-sortable ID), store it in a non-clustered column or as binary(16) written with ToByteArray(bigEndian: true), where SQL Server compares bytes left to right.
  • In-memory ordering (sorting a List<Guid>, comparing two IDs): CompareTo and ToString() agree with time order across milliseconds. Do not sort raw ToByteArray() output.
  • Extracting the timestamp: the first six big-endian bytes are milliseconds since the Unix epoch, which is how the test counted same-millisecond pairs.

Sources

Comments

Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.