UUID Guide: Versions and Uniqueness
A comprehensive guide to UUIDs: concepts, versions, generation principles, and applications in databases, APIs, and distributed systems.
What is a UUID?
A UUID (Universally Unique Identifier) is a 128-bit number used to uniquely identify information in computer systems.
Standard format:
550e8400-e29b-41d4-a716-446655440000
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- 36 characters (32 hexadecimal digits + 4 hyphens)
- Grouped as 8-4-4-4-12
- Range: 2^128 (approximately 3.4 × 10^38)
Why Do We Need UUIDs?
Problems with Traditional IDs
Many systems use auto-incrementing integers as primary keys:
-- Traditional approach
INSERT INTO users (id, name) VALUES (1, 'Alice');
INSERT INTO users (id, name) VALUES (2, 'Bob');
Problems:
- Predictable: Attackers can guess other record IDs
- Distributed conflicts: Multiple databases generate the same ID
- Information leakage: Exposes business scale (e.g., user count)
- Merge difficulties: ID conflicts during data migration
Advantages of UUIDs
-- Using UUIDs
INSERT INTO users (id, name) VALUES ('550e8400-e29b-41d4-a716-446655440000', 'Alice');
INSERT INTO users (id, name) VALUES ('7c9e6679-7425-40de-944b-e07fc1f90ae7', 'Bob');
Advantages:
- Globally unique: No centralized coordination needed
- Unpredictable: Enhanced security
- Offline generation: Clients can generate independently
- Cross-system compatible: Standardized format
UUID Versions
UUID has multiple versions, each with different generation strategies:
| Version | Name | Generation Method | Characteristics |
|---|---|---|---|
| v1 | Time-based | Timestamp + MAC address | Sortable, but exposes hardware info |
| v2 | DCE Security | Based on v1, reduced time precision | Rarely used |
| v3 | Name-based (MD5) | Namespace + name MD5 hash | Deterministic, same input produces same UUID |
| v4 | Random | Completely random | Most common, simple and secure |
| v5 | Name-based (SHA-1) | Namespace + name SHA-1 hash | Recommended, more secure than v3 |
| v6 | Reordered timestamp | Improved v1, timestamp high bits first | Sortable, compatible with v1 |
| v7 | Timestamp + random | Unix timestamp + random | Next-gen standard, sortable and secure |
| v8 | Custom | Defined by implementer | Experimental, not recommended for production |
v4 UUID (Most Common)
v4 UUIDs are generated entirely from random numbers:
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
^ ^
| Variant bits (8, 9, a, b)
Version 4
Generation example (JavaScript):
// Using crypto API
function generateUUID() {
return crypto.randomUUID();
}
console.log(generateUUID());
// "550e8400-e29b-41d4-a716-446655440000"
v7 UUID (Next-Gen Standard)
v7 is the latest UUID standard, combining timestamp and random numbers:
tttttttt-tttt-7xxx-yxxx-xxxxxxxxxxxx
^^^^^^^^^^^^^^^
Timestamp (ms)
Advantages:
- Sortable (by time)
- More secure (contains random component)
- Suitable for database indexing
UUID vs Auto-Increment ID
| Feature | Auto-Increment ID | UUID |
|---|---|---|
| Size | 4/8 bytes | 16 bytes |
| Readability | High | Low |
| Sortability | Naturally ordered | v1/v7 sortable, v4 not |
| Generation | Database-generated | Client/server can both generate |
| Distributed | Conflict risk | Globally unique |
| Security | Predictable | Unpredictable |
| Storage cost | Low | Higher |
| Index performance | Excellent | v4 poor, v7 good |
When to Use UUIDs?
Recommended for UUIDs:
- Distributed systems
- Need offline ID generation
- High security requirements (don't expose business scale)
- Frequent data merging/migration
- Microservice architecture
Not recommended for UUIDs:
- Monolithic applications with no distributed needs
- Storage cost sensitive
- Frequent sorting and range queries (unless using v7)
- Primary key frequently used as foreign key
Using UUIDs in Databases
PostgreSQL
-- Enable UUID extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Create table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Insert data
INSERT INTO users (name) VALUES ('Alice');
-- id auto-generated: "550e8400-e29b-41d4-a716-446655440000"
PostgreSQL 13+ built-in support:
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(100) NOT NULL
);
MySQL
CREATE TABLE users (
id CHAR(36) PRIMARY KEY DEFAULT (UUID()),
name VARCHAR(100) NOT NULL
);
INSERT INTO users (name) VALUES ('Alice');
JavaScript (Node.js)
const { randomUUID } = require('crypto');
const id = randomUUID();
console.log(id); // "550e8400-e29b-41d4-a716-446655440000"
Performance Considerations
Storage Overhead
Auto-increment INT: 4 bytes
Auto-increment BIGINT: 8 bytes
UUID: 16 bytes (stored) / 36 bytes (string representation)
Optimization strategies:
- Use binary storage (saves 50%):
-- PostgreSQL
CREATE TABLE users (
id UUID PRIMARY KEY, -- Stored internally as 16 bytes
name VARCHAR(100)
);
- Use v7 UUIDs (better index performance)
Index Performance
Problems with v4 UUIDs:
- Completely random, causing frequent B-tree index splits
- Insert performance degrades
Solutions:
Use v7 UUIDs (timestamp prefix, ordered inserts)
Use ordered UUID functions (MySQL):
-- Place timestamp at the front
CREATE FUNCTION ordered_uuid() RETURNS CHAR(36)
RETURN CONCAT(
HEX(UNIX_TIMESTAMP()),
'-',
SUBSTRING(UUID(), 9, 8),
'-4',
SUBSTRING(UUID(), 15, 3),
'-',
SUBSTRING(UUID(), 19, 4),
'-',
SUBSTRING(UUID(), 25, 12)
);
- Use BIGINT auto-increment ID + UUID business ID:
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY, -- For indexing and relations
uuid CHAR(36) UNIQUE NOT NULL, -- For external exposure
name VARCHAR(100)
);
Frequently Asked Questions
Can UUIDs Collide?
Theoretically possible, but extremely improbable.
v4 UUID collision probability:
Generating 1 billion UUIDs, the collision probability is approximately:
P ≈ n² / (2 × 2^122)
P ≈ (10^9)² / (2 × 5.3 × 10^36)
P ≈ 10^18 / 10^37
P ≈ 10^-19
This is much lower than the probability of hardware failure!
What's the Difference Between UUID and GUID?
No essential difference.
- UUID is defined by the RFC 4122 standard
- GUID is Microsoft's implementation (early versions differed slightly)
- Now the two are usually used interchangeably
How to Validate UUID Format?
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('not-a-uuid')); // false
Best Practices
Choose the right version:
- General purpose: v4 (simple random)
- Need sorting: v7 (timestamp + random)
- Deterministic generation: v5 (name-based hash)
Database optimization:
- Use native UUID types (if supported)
- Consider v7 UUIDs for better index performance
- Large tables can use dual ID strategy (auto-increment + UUID)
API design:
- Expose UUIDs externally, not auto-increment IDs
- Use UUIDs as resource identifiers
Security:
- Don't use v1 (exposes MAC address)
- v4 and v7 are secure choices
Use the DevKit UUID Generator
DevKit provides an online UUID generation tool supporting:
- Batch v4 UUID generation
- Custom formats (with/without hyphens)
- Uppercase/lowercase options
- One-click copy