UUID/GUID Generator: Complete Guide to Unique Identifiers for Developers
UUIDs provide globally unique identifiers without coordination. Learn the different versions, when to use them, and how to implement them correctly.
What is a UUID?
A UUID (Universally Unique Identifier) is a 128-bit identifier that's designed to be unique across space and time without requiring a central authority. GUIDs (Globally Unique Identifiers) are Microsoft's implementation of the same concept.
UUID Format
550e8400-e29b-41d4-a716-446655440000
| | | | | | | | | |
| | | | | | | | +----------+-- Node (48 bits)
| | | | | | +--+-- Clock sequence (14 bits)
| | | | +--+-- Version (4 bits) + Variant (2 bits)
| | +--+-- Time high (16 bits)
+------+-- Time low (32 bits) + Time mid (16 bits)Key characteristics:
- 32 hexadecimal digits
- 4 hyphens (8-4-4-4-12 format)
- 36 characters total
- Case insensitive
UUID Versions
UUID v1 (Time-based)
Generated from timestamp and MAC address.
// Example v1 UUID
"6fa459ea-ee8a-11eb-9a03-0242ac130003"
// ^ Version 1Pros:
- Sortable by creation time
- Can extract timestamp
- Guaranteed unique on single machine
- Exposes MAC address (privacy concern)
- Predictable
- Clock issues can cause duplicates
UUID v4 (Random)
Generated from random or pseudo-random numbers.
// Example v4 UUID
"550e8400-e29b-41d4-a716-446655440000"
// ^ Version 4Pros:
- No information leakage
- Simple to generate
- Most widely used
- Not sortable
- Requires good random source
- Tiny collision probability
UUID v7 (Time-ordered)
New standard combining timestamp with randomness.
// Example v7 UUID
"018e8400-e29b-71d4-a716-446655440000"
// ^ Version 7Pros:
- Sortable by creation time
- Database index friendly
- No MAC address exposure
- Better than v1 for most uses
- Relatively new (2024 RFC)
- Less library support currently
Other Versions
| Version | Method | Use Case |
|---|---|---|
| v2 | DCE Security | Legacy systems |
| v3 | MD5 hash | Deterministic from name |
| v5 | SHA-1 hash | Deterministic from name |
| v6 | Reordered v1 | Time-sortable v1 |
Generating UUIDs
JavaScript (Browser)
// Native crypto API (v4)
function generateUUID() {
return crypto.randomUUID();
}
// Manual implementation (v4)
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}Node.js
import { randomUUID } from 'crypto';
// Built-in (v4)
const uuid = randomUUID();
// Using uuid package
import { v4 as uuidv4, v7 as uuidv7 } from 'uuid';
const id = uuidv4();
const timeId = uuidv7();Python
import uuid
# Version 4 (random)
uuid.uuid4() # UUID('550e8400-e29b-41d4-a716-446655440000')
# Version 1 (time-based)
uuid.uuid1()
# Version 5 (SHA-1 from namespace + name)
uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
# Convert to string
str(uuid.uuid4()) # '550e8400-e29b-41d4-a716-446655440000'Java
import java.util.UUID;
// Version 4
UUID uuid = UUID.randomUUID();
// From string
UUID parsed = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
// To string
String str = uuid.toString();Go
import "github.com/google/uuid"
// Version 4
id := uuid.New()
// From string
parsed, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")
// To string
str := id.String()PostgreSQL
-- Enable extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Generate v4
SELECT uuid_generate_v4();
-- Generate v1
SELECT uuid_generate_v1();
-- Use as default
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(100)
);UUID vs. Other ID Strategies
Auto-increment IDs
id SERIAL PRIMARY KEY -- 1, 2, 3, ...| Aspect | Auto-increment | UUID |
|---|---|---|
| Size | 4-8 bytes | 16 bytes |
| Uniqueness | Per table | Global |
| Guessable | Yes | No |
| Generation | Database | Anywhere |
| Merge conflicts | Common | Rare |
Snowflake IDs (Twitter)
64-bit IDs combining timestamp + machine + sequence:
1541815603606036480Use when:
- Need sortable IDs
- Have distributed system
- Want smaller than UUID
ULID
Lexicographically sortable, 128-bit identifier:
01ARZ3NDEKTSV4RRFFQ69G5FAVUse when:
- Need sortable UUIDs
- Want URL-friendly format
- Need better index performance
NanoID
Compact, URL-friendly random IDs:
V1StGXR8_Z5jdHi6B-myTUse when:
- Need shorter IDs
- URL/filename safe required
- Less collision resistance acceptable
Database Considerations
Indexing UUIDs
Random UUIDs (v4) cause index fragmentation:
-- UUID v4: Random insertion points
-- UUID v7: Sequential insertion (better)
-- Consider ordered UUID storage
CREATE TABLE items (
id UUID PRIMARY KEY,
-- Store as binary for efficiency
-- id BINARY(16) PRIMARY KEY
);Storage Size
| Format | Size |
|---|---|
| UUID string | 36 bytes |
| UUID binary | 16 bytes |
| Integer ID | 4-8 bytes |
Query Performance
-- String comparison (slower)
WHERE id = '550e8400-e29b-41d4-a716-446655440000'
-- Binary comparison (faster)
WHERE id = UNHEX(REPLACE('550e8400-e29b-41d4-a716-446655440000', '-', ''))Best Practices
1. Choose the Right Version
| Scenario | Recommended |
|---|---|
| General purpose | v4 or v7 |
| Sortable by time | v7 |
| Deterministic | v5 |
| Legacy compatibility | v1 |
2. Use Binary Storage When Possible
# PostgreSQL native UUID type
# MySQL BINARY(16)
# Store efficiently, query with functions3. Validate Input
function isValidUUID(str) {
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return regex.test(str);
}4. Don't Expose Internal IDs
// ❌ Exposes database structure
/api/users/1
/api/orders/2
// ✅ UUIDs hide sequence
/api/users/550e8400-e29b-41d4-a716-446655440000
/api/orders/6fa459ea-ee8a-11eb-9a03-0242ac1300035. Generate Client-Side When Appropriate
// Offline-capable apps can generate IDs
const newItem = {
id: crypto.randomUUID(),
name: 'Item',
createdAt: new Date()
};
// Sync later without conflicts
await syncToServer(newItem);Collision Probability
UUID v4 has 122 random bits. The probability of collision:
| UUIDs Generated | Collision Probability |
|---|---|
| 1 billion | ~0.00000000001% |
| 1 trillion | ~0.00001% |
| 2.7 quintillion | 50% |
Security Considerations
UUID v1 Leaks Information
// v1 UUID contains:
// - Timestamp (when created)
// - MAC address (which machine)
// Don't use v1 for:
// - Public-facing IDs
// - Security-sensitive contextsUUIDs are Not Secrets
// ❌ Don't use UUID as password/token
const resetToken = crypto.randomUUID(); // Insufficient entropy
// ✅ Use proper crypto for secrets
const resetToken = crypto.randomBytes(32).toString('hex');Don't Trust Client UUIDs
// Client can send any UUID
// Always validate and authorize
app.put('/api/items/:id', async (req, res) => {
const item = await Item.findById(req.params.id);
// Verify ownership
if (item.userId !== req.user.id) {
return res.status(403).json({ error: 'Forbidden' });
}
// Proceed with update
});Conclusion
UUIDs are essential for modern distributed systems. Choose v4 for general use, v7 for sortable IDs, and always consider your database and performance requirements.
Use our free UUID Generator to quickly create UUIDs during development. Generate single IDs or bulk batches in any version you need.
Try Our Free Tools
Put these tips into practice with our free online tools. No signup required.
Explore Tools