uuid icon indicating copy to clipboard operation
uuid copied to clipboard

Method 1 and method 3 for UUID v7

Open vlad-khramov opened this issue 9 months ago • 3 comments

Method 1 and Method 3 for UUID v7

Background/Problem

The raw implementation of UUID v7 uses a 12-bit random value in the rand_a slot (see RFC):

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           unix_ts_ms                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          unix_ts_ms           |  ver  |       rand_a          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var|                        rand_b                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                            rand_b                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

There are three methods to achieve monotonicity for UUID v7. The current implementation uses Method 2 (Monotonic Random).

Sometimes, projects may require microsecond precision in UUID v7. Method 3 allows for this.

Proposal/Solution

I propose adding additional methods for generating UUID v7:

  • Method 3 – Adds microsecond precision. Since PHP can only provide microsecond precision, 2 additional bits could be used as a counter.
  • Method 1 and raw UUID v7 – Include for a complete implementation.

I propose adding an additional method parameter to Uuid::uuid7, with a default value of METHOD2 for backward compatibility.

Additional Context

Other implementations:

  • PostgreSQL – Method 3: 10-bit microseconds + 2-bit random or 12-bit nanoseconds, depending on the platform. Time is always increasing: if 2 UUIDs are generated within 1 microsecond, the next microsecond is used.
  • Python 3 – Method 1. Method 3 is not suitable as it may run on platforms without microsecond precision.
  • Google/UUID (Go) – Method 3: 12-bit nanoseconds.

I can implement this if you approve the idea.

vlad-khramov avatar Mar 25 '25 19:03 vlad-khramov

This idea sounds good to me. For the $method parameter, what values are you planning to use for the different methods?

ramsey avatar May 26 '25 04:05 ramsey

What do you think about fixed, random seed and milliseconds?

i3or1s avatar Sep 16 '25 07:09 i3or1s

FYI, symfony/uid v7.4 switched to method 3 (microsecond-level timestamps) in https://github.com/symfony/symfony/pull/60898

nicolas-grekas avatar Sep 16 '25 07:09 nicolas-grekas