What is a UUID (Universally Unique Identifier)?
A Universally Unique Identifier (UUID), standardized in IETF RFC 4122, is a 128-bit value used to uniquely identify entities in software systems without requiring central registration or coordination between database servers.
A standard canonical UUID is represented as 32 hexadecimal digits displayed in five hyphen-delimited groups formatted as 8-4-4-4-12:
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
In a Version 4 UUID, the digit at position 13 is always fixed to 4 (indicating Version 4), while the variant bits at position 17 always start with 8, 9, a, or b (RFC 4122 variant).
UUID Version Comparison
| Version | Generation Basis | Primary Use Case & Characteristics |
|---|---|---|
| Version 1 | Timestamp + MAC Address | Time-ordered. Leaks hardware MAC address; rarely used in modern public APIs. |
| Version 4 | Cryptographic Randomness (122 bits) | The industry standard for microservices, database keys, and user session IDs. |
| Version 5 | Namespace + SHA-1 Hash | Deterministic: Generates identical UUID for the same namespace and string. |
| Version 7 (New) | Unix Epoch (ms) + Randomness | Optimized for database B-Tree clustering indexes; preserves sequential insertion. |
Generating UUID v4 in Code
Native JavaScript (Browser & Node.js 16+)
// Built-in WebCrypto API
const uniqueId = crypto.randomUUID();
console.log("Generated UUID:", uniqueId);
Python 3 Standard Library
import uuid
# Generate a cryptographically random UUID v4
random_id = uuid.uuid4()
print("UUID String:", str(random_id))
Go (Golang)
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
id := uuid.New()
fmt.Println("UUID v4:", id.String())
}
Frequently Asked Questions
Can two computers generate the exact same UUID v4?
While theoretically possible, the mathematical probability of two computers generating the same v4 UUID is roughly 1 in 5.3 × 10³⁶. For all practical software architecture scenarios, v4 UUIDs are treated as globally unique.
Can I use UUIDs as database primary keys?
Yes, especially in distributed databases (Cassandra, MongoDB, CockroachDB) where central auto-increment sequences create bottlenecks. For relational databases (PostgreSQL, MySQL), using UUIDv7 or binary storage (
UUID column type) avoids index fragmentation.