When you need to assign a unique identifier to a database record, a user session, a file, or any other entity in a distributed system, UUID (Universally Unique Identifier) is often the right tool. Unlike auto-incrementing integers, UUIDs can be generated independently by any machine without coordination, making them essential for distributed architectures, offline-first applications, and microservices.
This guide covers UUID versions 1 through 7, their structure, performance characteristics, security considerations, and practical guidance on when to use each variant in real-world applications.
What is a UUID?
A UUID is a 128-bit number, typically expressed as 32 hexadecimal digits in five hyphen-separated groups:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
550e8400-e29b-41d4-a716-446655440000Where:
- M identifies the version (1-7)
- N identifies the variant (the current standard uses variant 10xx, so N is 8, 9, a, or b)
The UUID specification is defined in RFC 4122 (versions 1-5) and the updated RFC 9562 (versions 6-8).
Mathematically, a UUID v4 collision is virtually impossible: with 2^122 possible values (~5.3 x 10^36), if you generated 1 billion UUIDs per second for the next billion years, the probability of a collision would be about 50% -- making them practically unique for all real-world purposes.
UUID v1: Time-Based (with MAC Address)
UUID v1 combines the current timestamp (measured in 100-nanosecond intervals since October 15, 1582) with the MAC address of the generating machine.
Example: 6ba7b810-9dad-11d1-80b4-00c04fd430c8 (version 1 indicated by the 1 in the third group)
Advantages:
- Monotonically increasing (sortable by time when bytes are rearranged)
- Guaranteed unique across machines (MAC address provides node uniqueness)
Disadvantages:
- Privacy concern: Embeds the MAC address, revealing the generating machine's network interface identifier
- Predictable: Since both timestamp and MAC are known, future UUIDs can be predicted
- Not ideal for database primary keys due to random insertion order
UUID v1 is largely superseded by v6 and v7 for new applications.
UUID v4: Random (The Workhorse)
UUID v4 is generated from 122 bits of cryptographically secure random data (6 bits are used for version and variant markers). It's the most commonly used UUID version today.
// Browser -- uses Web Crypto API (secure):
const uuid = crypto.randomUUID();
// => "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
// Node.js -- uses crypto module:
import { randomUUID } from 'crypto';
const uuid = randomUUID();
// Python:
import uuid
str(uuid.uuid4()) # => "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
// Go:
import "github.com/google/uuid"
uuid.New().String()Advantages:
- No privacy concerns (no identifying information embedded)
- Trivially simple to generate
- Available natively in modern browsers via crypto.randomUUID()
Disadvantages:
- Not sortable -- random insertion causes B-tree index fragmentation in databases like PostgreSQL and MySQL
- Slightly slower database queries compared to sequential IDs due to cache inefficiency
UUID v4 is appropriate for most use cases where database performance with large datasets isn't critical.
UUID v5: Name-Based (SHA-1 Hashed)
UUID v5 generates a deterministic UUID from a namespace and a name using SHA-1 hashing. The same namespace + name always produces the same UUID -- useful for creating stable, reproducible identifiers.
// Using the 'uuid' npm package:
import { v5 as uuidv5 } from 'uuid';
// Standard namespaces defined in RFC 4122:
const DNS_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const URL_NAMESPACE = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
const id = uuidv5('example.com', DNS_NAMESPACE);
// => "cfbff0d1-9375-5685-968c-48ce8b15ae17" (always the same)Use cases for v5:
- Generating consistent IDs for URLs or domain names (convert a URL to a UUID)
- Content deduplication (same content always maps to same UUID)
- Migration: generating stable IDs from legacy data without storing a mapping table
UUID v3 is the same concept but uses MD5 instead of SHA-1. Prefer v5 over v3 for new applications since MD5 is cryptographically broken (though both v3 and v5 are safe here since you're not relying on SHA-1/MD5 for security -- just determinism).
UUID v6 and v7: The Modern Standard
Versions 6 and 7 were standardized in RFC 9562 (2024) to address UUID v1's privacy issues and UUID v4's database performance problems.
UUID v6 reorders the timestamp bytes of UUID v1 so that the most significant bytes come first, making v6 UUIDs lexicographically sortable. It still includes the MAC address (same privacy concern as v1) but improves database performance.
UUID v7 uses a Unix timestamp in milliseconds in the most significant bits, followed by random bytes:
// Using the 'uuid' npm package (version 9+):
import { v7 as uuidv7 } from 'uuid';
const id = uuidv7();
// ULID is a popular alternative with similar properties:
import { ulid } from 'ulid';
const id = ulid(); // => "01ARZ3NDEKTSV4RRFFQ69G5FAV"UUID v7 advantages:
- Time-ordered: sequential within the same millisecond
- No privacy leakage (no MAC address)
- Excellent database performance (sequential inserts avoid B-tree fragmentation)
- Globally unique without coordination
UUID v7 is the recommended choice for new database primary keys in distributed systems.
UUIDs vs. Auto-Increment IDs vs. NanoID
Auto-increment integers (PostgreSQL SERIAL, MySQL AUTO_INCREMENT):
+ Compact (4 or 8 bytes vs. 16 for UUID)
+ Perfectly sequential -- excellent index performance
- Require a central authority to generate (coordination bottleneck in distributed systems)
- Reveal record counts and creation order (security risk -- /users/1 reveals this is the first user)
- Hard to merge data from multiple databases
UUID v4:
+ Decentralized generation
+ No information leakage
- Random insertion -- poor cache performance for large tables
- 36 characters as string (larger than int)
UUID v7 / ULID:
+ Decentralized generation
+ Time-sortable -- good database performance
+ No MAC address leakage
- Slightly more complex to generate than v4
NanoID (npm package): Generates compact URL-safe IDs of configurable length:
import { nanoid } from 'nanoid';
nanoid() // => "V1StGXR8_Z5jdHi6B-myT" (21 chars, ~126 bits)
nanoid(10) // => "IRFa-VaY2b" (10 chars, customizable)NanoID is useful when you need shorter, URL-safe identifiers and don't need UUID format compatibility.
Security Considerations for UUIDs
Use `crypto.randomUUID()` not `Math.random()`: Never generate UUIDs using Math.random(). It's not cryptographically secure -- an attacker who observes several UUIDs generated with Math.random() can predict future ones.
// INSECURE -- don't do this:
function badUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0; // Math.random() is predictable!
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
// SECURE -- use the built-in:
const uuid = crypto.randomUUID();UUID v1 privacy risk: UUID v1 embeds your machine's MAC address. If you log or expose UUID v1 values, you're revealing identifying hardware information. Use v4 or v7 instead.
UUIDs are not secret tokens: Don't use UUIDs as password reset tokens or API keys. They're unique but not unpredictable enough for session tokens -- use crypto.getRandomValues() to generate 256-bit random tokens instead.