What is UUID?

UUID (Universally Unique Identifier) is a 128-bit globally unique identifier, formatted as 32 hexadecimal characters in 5 groups: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. UUIDs enable distributed systems to generate unique IDs without central coordination.

UUID Version Comparison

Version Method Sortable Collision Use Case
v1 Timestamp + MAC Time-based Extremely low Legacy systems
v4 Random (122 bit) No Extremely low Most common
v7 (RFC 9562) Timestamp + Random Sortable Extremely low Recommended

UUID v4 Details

UUID v4 has 2¹²² possible values, making collision probability negligible:

  • 1 trillion IDs → ~10⁻¹⁸ collision probability
  • 1 billion IDs/second → 10 billion years for collision

UUID v4 Limitations

  • Not sortable: Poor for DB primary keys
  • Index performance: Random inserts cause B+ tree page splits
  • Storage: 128-bit / 36-char string, larger than auto-increment

What is ULID?

ULID (Universally Unique Lexicographically Sortable Identifier) is a sortable globally unique identifier designed to solve UUID v4's ordering problem.

ULID Features

  • 128-bit: 26-char Crockford Base32 encoding
  • Sortable: Lexicographically ordered by timestamp
  • Millisecond precision: 48-bit timestamp
  • Case-insensitive: No special characters
  • URL-safe: No special characters needed

ULID Structure

01AN4Z07BY      79KA1307SR9X4MV3
│               │
│               └── Random (80 bit)
│
└── Timestamp (48 bit, ms Unix time)

UUID v7 (RFC 9562)

Standardized in May 2024, the best UUID v4 alternative:

  • First 48 bits: Unix millisecond timestamp
  • Remaining 74 bits: Random
  • Time-sortable for database indexing
  • No coordination needed for distributed generation

DB Primary Key Recommendations

Scenario Recommendation
New project, sortable UUID v7 or ULID
Legacy compatibility UUID v4
Internal, no distribution Auto-increment ID
Public API ULID or UUID v7

Security Notes

  • Use cryptographically secure RNG (CSPRNG) for UUID v4
  • Avoid Math.random() for UUID generation
  • Don't use UUIDs for security tokens