UUID Best Practices

2026-06-06·6 min read·Dev Tools

UUID Basic Concepts

UUID (Universally Unique Identifier) is a 128-bit unique identifier in the format of an 8-4-4-4-12 hexadecimal string, such as 550e8400-e29b-41d4-a716-446655440000. UUIDs are designed to generate globally unique identifiers in distributed systems without requiring central coordination.

UUID has five main versions: UUID v1 is generated based on timestamps and MAC addresses, providing time ordering but containing privacy information; UUID v2 is the DCE security version, rarely used; UUID v3 is generated based on MD5 hashing, producing the same UUID for identical inputs; UUID v4 is completely randomly generated, the most commonly used version; UUID v5 is generated based on SHA-1 hashing, more secure than v3.

Version Characteristics and Selection

UUID v4 is the most commonly used due to its simplicity and no privacy leakage risk. It does not depend on any external information and can be independently generated on any node, making it ideal for distributed systems. However, the randomness of v4 may cause index fragmentation when used as a primary key in databases, affecting insertion performance.

UUID v7 (2024 new standard) combines timestamp sorting with randomness, ensuring uniqueness while remaining insertion-friendly. It is generated based on millisecond timestamps and can be naturally sorted, making it a new alternative to v4. For scenarios requiring reproducible identifiers, UUID v3 or v5 are better choices.

Code Implementation

// Generate UUID v4 in JavaScript
function generateUUIDv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

// Using native API (modern browsers)
const uuid = crypto.randomUUID();

// Generate UUID in Python
import uuid

# UUID v4
random_uuid = uuid.uuid4()

# UUID v5
dns_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')

# Parse from string
parsed = uuid.UUID('12345678-1234-5678-1234-567812345678')

Database Storage Optimization

When using UUIDs in databases, standard UUIDs occupy 36 bytes of string space, while binary storage requires only 16 bytes. MySQL recommends using BINARY(16) for storing UUIDs, with conversion handled at the application layer. For indexing, UUID v4's randomness can cause frequent B-tree index splits - the solution is to use UUID v7 or add a time prefix to UUIDs.

Recommended Tools

uuid-generator.net is an online UUID generator supporting multiple versions. The npm uuid package provides a complete JavaScript implementation. For scenarios requiring sorting, consider using ULID or NanoID as alternatives.