UUIDs in Practice: When to Use Them and What Could Go Wrong
UUIDs seem simple — generate a unique ID, use it everywhere. But there are surprising subtleties that affect database performance, URL aesthetics, and even debugging.
UUID Versions
UUID v4 (Random): 122 random bits. Practically unique — you would need to generate 1 billion per second for 85 years for a 50% collision chance. But random UUIDs fragment B-tree indexes because new values insert at random positions rather than appending to the end.
UUID v7 (Time-ordered): Starts with a timestamp, ends with random bits. Solves the index fragmentation problem — new UUIDs sort chronologically. Recommended for database primary keys.
Database Performance
I once debugged a slow PostgreSQL table with 50 million rows using UUID v4 primary keys. The random insertion pattern had fragmented the index across hundreds of pages. Switching to UUID v7 (which includes a timestamp prefix) improved insert performance by 40% and reduced index size by 25%. Current database versions increasingly support v7 natively.
When NOT to Use UUIDs
- For short-lived, low-volume data — an auto-increment integer is simpler and smaller
- In URL paths that users might type — UUIDs are long and unfriendly
- When you need sortability by creation time without an extra timestamp column — use UUID v7 instead
This article was written by UnTrackedTools founder Alex Chen, based on real database optimization experience.