UUID Versions Explained
A UUID (Universally Unique Identifier) is a 128-bit number in the format 8-4-4-4-12 hex characters. There are 5 versions, each generated differently for different use cases.
UUID Versions at a Glance
- Version 1: time-based + MAC address. Contains creation timestamp. Used in Cassandra databases
- Version 4: fully random. Most commonly used. ~5.3 ร 10ยฒโถ possible values โ collision probability is negligibly small
- Version 5: namespace + SHA-1 hash. Deterministic โ same input always produces the same UUID
- Version 7 (modern): time-ordered random UUID โ designed for sortable database primary keys
When to Use UUIDs
- Database primary keys in distributed systems where sequential IDs conflict
- API resource identifiers that should be globally unique
- Session tokens, file names, or reference numbers
- Anywhere you need uniqueness across multiple systems without coordination
Can two UUIDs ever be the same?
Theoretically yes, but the probability is astronomically small. UUID v4 has 2ยนยฒยฒ possible values (about 5.3 ร 10ยณโถ). If you generated 1 billion UUIDs per second for 100 years, the probability of a collision would still be less than 1 in 10 billion. In practice, UUIDs are treated as globally unique for all engineering purposes.
Should I use UUID or ULID for database primary keys?
UUID v4 is random and causes index fragmentation in B-tree databases because new inserts can't be appended in order. ULID and UUID v7 solve this by embedding a timestamp prefix, making inserts sort naturally and improving index performance. For high-performance databases with heavy write loads, ULID or UUID v7 are preferred over v4.