UUID v4: The Definitive Guide
A UUID (Universally Unique Identifier) is a 128-bit number that looks like this: 550e8400-e29b-41d4-a716-446655440000. The "universally unique" part means you can generate one on any machine, at any time, without coordinating with anyone, and be virtually certain it's unique.
How Unique Is "Unique"?
UUID v4 uses 122 random bits (6 bits are fixed for version/variant). That's 2^122 = 5.3 × 10^36 possible values. To put this in perspective:
- Generate 1 billion UUIDs per second
- Do this for 100 years
- You'd have a 50% chance of ONE collision
In practice, your system will fail for a thousand other reasons before UUID collision becomes a concern.
UUID Versions
| Version | Based on | Use case |
|---|---|---|
| v1 | Timestamp + MAC address | Sortable, but leaks device info |
| v4 | Random | Most popular, no information leakage |
| v5 | SHA-1 hash of namespace + name | Deterministic — same input = same UUID |
| v7 | Timestamp + random (new) | Sortable like v1, random like v4 |
v4 is the default choice. v7 is gaining traction for database primary keys because it's sortable (better B-tree performance than random v4).
Generating UUIDs
JavaScript (browser):
crypto.randomUUID();
// "3b241101-e2bb-4d7a-8613-e4cf2408e94e"Node.js:
import { randomUUID } from 'crypto';
const id = randomUUID();Python:
import uuid
str(uuid.uuid4())PostgreSQL:
SELECT gen_random_uuid();
-- or as column default:
CREATE TABLE users (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
name TEXT NOT NULL
);UUID vs Auto-Increment
Auto-increment IDs (1, 2, 3...) are simple but have drawbacks in distributed systems:
- Predictable: Competitors can enumerate your data (
/users/1,/users/2...) - Centralized: Need a single source to assign IDs (bottleneck)
- Merge conflicts: Two databases both have
id=42for different records
UUIDs solve all three. The tradeoff: they're larger (16 bytes vs 4-8 bytes) and not human-friendly.
UUIDs in URLs
/users/550e8400-e29b-41d4-a716-446655440000 is ugly. Options:
- Nanoid:
/users/V1StGXR8_Z5jdHi6B— shorter, URL-safe - Hashids:
/users/abc123— encode numeric IDs into short strings - ULID:
/users/01ARZ3NDEKTSV4RRFFQ69G5FAV— sortable, Crockford base32
Generate now: UUID Generator — v4 UUIDs with one click.