Curious TechieDev Toolbox
All Guides/Developer Tools8 min read

Comprehensive Guide to UUIDs (v4 vs v7)

Understand Universally Unique Identifiers (RFC 9562), 128-bit collision math, random UUID v4, and time-ordered UUID v7 for high-performance database indexing.

Key Takeaways
  • A UUID is a 128-bit label standardized by RFC 9562 (superseding RFC 4122) formatted as 32 hex digits with 4 hyphens.
  • UUID v4 is purely pseudo-random using 122 bits of CSPRNG entropy; collision probability is virtually zero (1 in 5.3 × 10^36).
  • UUID v7 embeds a 48-bit Unix millisecond timestamp at the beginning, making it natively time-sortable.
  • UUID v7 prevents database B-tree index fragmentation and write amplification compared to random UUID v4.

Distributed databases and microservices architectures require distributed primary keys that can be generated independently on separate servers without a central coordinating bottleneck. That standard is the Universally Unique Identifier (UUID / GUID).

1. The 128-Bit UUID Structure

Standardized by RFC 9562, a UUID consists of 16 octets (128 bits) represented as 32 hexadecimal characters grouped into five hyphen-separated blocks:

xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
M = Version number (e.g. 4 or 7) | N = Variant (typically 8, 9, a, or b)

2. Collision Mathematics & Safety

With 122 bits of pure randomness in UUID v4 (2^122 ≈ 5.3 × 10^36 possible IDs), you would need to generate 1 billion UUIDs every second for 85 years before having a 50% chance of a single collision.

3. UUID v4 (Random) vs UUID v7 (Time-Ordered)

While UUID v4 is completely random, the new standard UUID v7 places a 48-bit Unix millisecond timestamp in the most significant bits, followed by 74 bits of randomness. This guarantees that IDs naturally sort chronologically.

4. Database Indexing & B-Tree Fragmentation

Inserting random UUID v4 keys into primary key B-Trees causes random page splits and heavy cache eviction. UUID v7 inserts sequentially at the end of the index like an auto-incrementing integer, resulting in up to 10x faster insert performance in PostgreSQL, MySQL, and SQLite.