Complete Guide to UUID Generation and Usage
UUID (Universally Unique Identifier) is a standard method for generating globally unique identifiers. UUIDs are used when you need duplicate-free IDs in databases, APIs, and distributed systems.
1. UUID Basic Concepts
A UUID is a 128-bit number, represented as a 36-character string in the format 550e8400-e29b-41d4-a716-446655440000.
UUID Characteristics:
- Extremely low probability of duplication (practically guaranteed uniqueness)
- Can be generated independently without central management
- Safe to use in distributed systems
2. UUID Version Characteristics
Version 1 (Time-based)
Generated using timestamps and MAC address.
- Pros: Guarantees chronological order
- Cons: Privacy concerns due to MAC address inclusion
Version 4 (Random)
Generated using completely random values.
- Pros: Unpredictable, privacy-safe
- Cons: No chronological order
- Most commonly used
Version 5 (Name-based)
Generated by SHA-1 hashing namespace and name.
- Pros: Same input always produces same UUID
- Use case: When deterministic IDs are needed
3. Practical Use Cases
Database Primary Keys
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255),
email VARCHAR(255)
);
API Resource Identifiers
// RESTful API endpoint
GET /api/users/550e8400-e29b-41d4-a716-446655440000
File Name Generation
const fileId = crypto.randomUUID();
const filename = `upload-${fileId}.jpg`;