What is a UUID?
A UUID (Universally Unique Identifier) is a 128-bit identifier that is guaranteed to be unique across time and space. UUIDs are also known as GUIDs (Globally Unique Identifiers) in Microsoft systems. They are represented as 32 hexadecimal digits in five groups separated by hyphens.
UUID Format Example
Format: 8-4-4-4-12 hexadecimal digits
UUID Versions
UUID Version 4 (Random)
UUID v4 is generated using random or pseudo-random numbers. It's the most commonly used version and provides excellent uniqueness guarantees. The probability of collision is extremely low.
✅ Best for:
- General-purpose unique identifiers
- API keys and tokens
- Session IDs
- File names and temporary identifiers
UUID Version 7 (Time-Ordered)
UUID v7 is a newer version that includes a timestamp component, making it naturally sortable by creation time. This is particularly useful for database primary keys where you want chronological ordering.
⚡ Advantages:
- Naturally sortable by time
- Better database performance
- Easier debugging and logging
- Reduced index fragmentation
Other UUID Versions
- UUID v1: Based on MAC address and timestamp
- UUID v3: Name-based using MD5 hashing
- UUID v5: Name-based using SHA-1 hashing
- UUID v6: Time-ordered version of v1
Common Use Cases
Database Primary Keys
UUIDs are excellent for database primary keys,especially in distributed systems where you can't rely on auto-incrementing integers. They prevent ID conflicts when merging databases or replicating data.
API Keys and Tokens
UUIDs make excellent API keys and authentication tokens due to their uniqueness and unpredictability. They're hard to guess and provide good security.
File Names and URLs
UUIDs can be used to generate unique file names,preventing conflicts and providing some level of obfuscation for sensitive files.
Distributed Systems
In microservices and distributed architectures,UUIDs ensure that different services can generate unique identifiers without coordination.
UUID vs Other Identifiers
Comparison Table
| Type | Size | Uniqueness | Sortable |
|---|---|---|---|
| Auto-increment | 4-8 bytes | Per table | ✅ Yes |
| UUID v4 | 16 bytes | Global | ❌ No |
| UUID v7 | 16 bytes | Global | ✅ Yes |
Best Practices
✅ UUID Best Practices
- Choose the Right Version: Use v4 for general use, v7 for sortable IDs
- Database Indexing: Consider performance implications of UUID indexes
- Storage Format: Store as binary (16 bytes) rather than string (36 bytes)
- URL Safety: Use base64url encoding for URL-safe UUIDs
- Validation: Always validate UUID format before processing
❌ Common Mistakes
- Using v1 in Web Apps: MAC address exposure is a privacy concern
- String Storage: Storing as strings wastes space and hurts performance
- Poor Indexing: Not considering UUID index performance
- Weak Randomness: Using poor random number generators