Developer Guide
UUID Best Practices for Modern Applications
Choosing between UUID v4, v7, and alternatives like NanoID, database index performance, and collision probability explained.
UUID v4 vs v7: Why Time Ordering Matters
UUID v4 generates purely random IDs that scatter across the key space. In a B-tree index (the default for most databases), random inserts cause page splits and index fragmentation, slowing down writes over time. UUID v7 encodes the current Unix timestamp in milliseconds as the first 48 bits, producing chronologically-sorted IDs. This eliminates index fragmentation and makes UUIDs usable as primary keys in high-write systems.
Collision Probabilities in Practice
UUID v4 has 122 random bits. The birthday paradox gives a 50% collision probability after ~2.7 x 10^18 IDs. To reach this, you would need to generate 100 million IDs per second for 873 years. For any practical application, collisions are not a concern. UUID v7 uses 74 random bits (48 bits are timestamp), so collision probability is slightly higher but still negligible for normal use.
When Not to Use UUIDs
For short-lived session tokens, use a crypto library (48-64 random bytes) instead of UUIDs. For user-facing IDs that should be short (like YouTube-style IDs), use NanoID with a custom alphabet and sufficient entropy. For simple single-server applications, auto-increment integers remain the most efficient choice for primary keys.