UUID Generator Guide: Understanding v1, v4, and v5 UUIDs
UUIDs (Universally Unique Identifiers), also called GUIDs in Microsoft systems, are 128-bit identifiers designed to be unique across space and time without requiring a central registry.
What is a UUID?
A UUID looks like this:
550e8400-e29b-41d4-a716-446655440000
Format: 8-4-4-4-12 hexadecimal digits (36 characters total including hyphens)
Total combinations: 2^122 ≈ 5.3 × 10^36 (for version 4)
To put this in perspective: If you generated 1 billion UUIDs per second, it would take over 100 billion years to have a 50% chance of a collision.
UUID Versions Explained
UUID v1: Timestamp-based
Format: xxxxxxxx-xxxx-1xxx-yxxx-xxxxxxxxxxxx
Generated from:
- Current timestamp (60-bit)
- Clock sequence (14-bit)
- MAC address (48-bit)
Example:
// Node.js with uuid package
import { v1 as uuidv1 } from 'uuid';
const id = uuidv1(); // '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
Pros:
- Time-ordered (sortable by creation time)
- Reveals creation timestamp
Cons:
- Exposes MAC address (privacy concern)
- Predictable (not random)
- Clock synchronization issues
Use cases:
- Database primary keys (when you want time-ordering)
- Event logging with chronological sorting
UUID v4: Random
Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
Generated from cryptographically strong random numbers.
Example:
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4(); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
Pros:
- Truly random (no privacy concerns)
- Most widely supported
- No clock dependency
Cons:
- Not sortable by creation time
- Slightly higher collision risk (still negligible)
Use cases:
- User IDs
- Session tokens
- API keys
- Resource identifiers
This is the most common UUID version (90%+ of use cases).
UUID v5: SHA-1 Hash-based
Format: xxxxxxxx-xxxx-5xxx-yxxx-xxxxxxxxxxxx
Generated from SHA-1 hash of a namespace + name.
Example:
import { v5 as uuidv5 } from 'uuid';
const namespace = uuidv5.DNS; // Predefined namespace
const name = 'example.com';
const id = uuidv5(name, namespace); // Always returns same UUID for same input
Pros:
- Deterministic (same input → same UUID)
- Reproducible across systems
- Content-addressable
Cons:
- Requires namespace UUID
- Not random (reveals relationship between UUIDs)
Use cases:
- Content-addressable storage
- Idempotent operations
- Derived identifiers
Choosing the Right UUID Version
| Scenario | Recommended |
|---|---|
| User IDs | v4 |
| Database primary keys | v4 (or v1 if you need time-ordering) |
| Session tokens | v4 |
| API request IDs | v4 |
| File/content addressing | v5 |
| Event sourcing | v1 (for chronological order) |
When in doubt, use v4.
Generating UUIDs in Different Languages
JavaScript (Browser)
// Modern browsers support crypto.randomUUID()
const uuid = crypto.randomUUID();
console.log(uuid); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
Node.js
import { v4 as uuidv4 } from 'uuid';
const uuid = uuidv4();
Python
import uuid
# v4 (random)
uuid4 = uuid.uuid4()
print(uuid4) # '3c6e0b8a-2e1f-4e3f-9a7c-1b5d9f8e2c3d'
# v1 (timestamp)
uuid1 = uuid.uuid1()
# v5 (hash-based)
namespace = uuid.NAMESPACE_DNS
uuid5 = uuid.uuid5(namespace, 'example.com')
Java
import java.util.UUID;
// v4 (random)
UUID uuid = UUID.randomUUID();
System.out.println(uuid.toString());
PostgreSQL
-- Enable extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Generate v4 UUID
SELECT uuid_generate_v4();
-- Use as primary key
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
username VARCHAR(100)
);
Validating UUIDs
JavaScript
function isValidUUID(uuid) {
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return regex.test(uuid);
}
console.log(isValidUUID('550e8400-e29b-41d4-a716-446655440000')); // true
console.log(isValidUUID('invalid-uuid')); // false
Python
import uuid
try:
uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
print("Valid UUID")
except ValueError:
print("Invalid UUID")
Common Use Cases
1. Database Primary Keys
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Query by UUID
SELECT * FROM orders WHERE id = '550e8400-e29b-41d4-a716-446655440000';
Why UUIDs over auto-increment integers?
- No central sequence (works in distributed systems)
- Non-enumerable (can't guess next ID)
- Merge-friendly (no ID conflicts when combining databases)
2. API Idempotency Keys
async function createPayment(amount, idempotencyKey) {
// Use client-provided UUID to prevent duplicate payments
const existing = await db.findByIdempotencyKey(idempotencyKey);
if (existing) return existing; // Already processed
return await processPayment(amount, idempotencyKey);
}
// Client generates UUID
const key = crypto.randomUUID();
await createPayment(100, key);
3. Distributed Tracing
const traceId = crypto.randomUUID();
const spanId = crypto.randomUUID();
logger.info('Processing request', { traceId, spanId });
await callService({ headers: { 'X-Trace-Id': traceId } });
Performance Considerations
Storage Size
- UUID: 128 bits (16 bytes)
- String representation: 36 bytes (inefficient)
- Binary storage: Use BINARY(16) in MySQL or UUID type in PostgreSQL
Index Performance
-- ❌ SLOW - String comparison
CREATE INDEX idx_user_id ON orders ((user_id::text));
-- ✅ FAST - Native UUID comparison
CREATE INDEX idx_user_id ON orders (user_id);
Bulk Generation
// Generate 10,000 UUIDs
const uuids = Array.from({ length: 10000 }, () => crypto.randomUUID());
Try It Yourself
Use our Free UUID Generator to:
- Generate v1, v4, v5 UUIDs instantly
- Bulk generate up to 1,000 UUIDs
- Validate UUID format
- Decode UUID metadata (version, variant)
- Copy to clipboard with one click
Best Practices
- Use v4 by default unless you have specific needs
- Store as binary/UUID type in databases (not strings)
- Don't use UUIDs for sequential ordering (use timestamps)
- Do use UUIDs for distributed systems, public IDs, idempotency keys
- Validate UUIDs from untrusted sources
Conclusion
UUIDs are essential for modern distributed systems. They provide globally unique identifiers without coordination, making them perfect for microservices, distributed databases, and API design.
Quick Decision Tree:
- Need random, unpredictable IDs? → v4
- Need time-ordered IDs? → v1
- Need deterministic IDs from content? → v5
Generate UUIDs instantly with our free UUID generator tool — no installation or registration required!
Top comments (0)