UUID v4 Generator — Random UUIDs Explained
UUID v4 uses random bits to generate universally unique identifiers. Here's how v4 differs from other UUID versions, what makes them unique, and when to use UUID v4 vs...
UUID v4 is the most commonly used UUID version. It generates a 128-bit identifier from random (or pseudo-random) bits, with no dependency on the current time, MAC address, or any server state. The result is statistically unique across all systems without coordination.
Use the UUID Generator to generate UUID v4 values instantly.
UUID v4 format
Every UUID v4 follows the same structure:
xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
Where:
4in the third group indicates UUID version 4yis one of8,9,a, orb— indicates the variant (RFC 4122)- All other
xpositions are random hex digits
Example UUID v4:
f47ac10b-58cc-4372-a567-0e02b2c3d479
Breaking it down:
f47ac10b— 32 random bits58cc— 16 random bits4372— version (4) + 12 random bitsa567— variant bits + 14 random bits0e02b2c3d479— 48 random bits
Total random bits: 122 (6 bits reserved for version and variant).
Generating UUID v4 in code
JavaScript (browser)
// Built-in crypto API (no library needed):
const uuid = crypto.randomUUID();
// "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Supported in all modern browsers and Node.js 14.17+
console.log(typeof uuid); // "string"
console.log(uuid.length); // 36
Node.js (multiple approaches)
// Approach 1: Built-in crypto (Node.js 14.17+)
const { randomUUID } = require('crypto');
const uuid = randomUUID();
// Approach 2: uuid package
const { v4: uuidv4 } = require('uuid');
const uuid = uuidv4();
// Approach 3: Manual implementation (for learning):
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);
});
}
Python
import uuid
# Generate UUID v4:
unique_id = uuid.uuid4()
print(unique_id) # UUID object
print(str(unique_id)) # "f47ac10b-58cc-4372-a567-0e02b2c3d479"
# As string without dashes (32 hex chars):
print(unique_id.hex) # "f47ac10b58cc4372a5670e02b2c3d479"
# As integer:
print(unique_id.int) # 324605033424591895846014609927575858297
Go
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
id := uuid.New()
fmt.Println(id.String()) // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Generate multiple:
for i := 0; i < 5; i++ {
fmt.Println(uuid.NewString())
}
}
UUID versions compared
| Version | Source of uniqueness | Use case |
|---|---|---|
| v1 | Time + MAC address | When ordering by creation time matters |
| v3 | MD5 hash of namespace + name | Deterministic UUIDs from known inputs |
| v4 | Random bits | General purpose unique IDs |
| v5 | SHA-1 hash of namespace + name | Deterministic UUIDs (newer than v3) |
| v7 | Unix timestamp + random | Sortable, time-ordered (newer) |
v4 is the default choice because it requires no coordination, no network access, and no seed data — just entropy from the OS.
UUID v4 uniqueness: the math
With 122 random bits, the probability of a collision is astronomically low.
To have a 50% chance of a single collision among n UUIDs:
n ≈ 2.71 × 10^18 (about 2.7 quintillion UUIDs)
At a rate of 1 billion UUIDs per second, you’d need to generate for about 86 years before expecting the first collision.
For practical applications (databases, session tokens, file names), UUID v4 collision probability is negligible.
When UUID v4 is not the right choice
When you need sortability: UUIDs are random, not ordered. If you insert UUID v4 values as primary keys, database index performance degrades because new rows insert randomly throughout the B-tree instead of at the end.
Solutions:
- UUID v7 — embeds a millisecond timestamp prefix for ordering while remaining unique
- ULID — similar to UUID v7, but URL-safe and uses Crockford base32
- KSUID — 20-byte sortable IDs with a 4-byte timestamp prefix
- Sequential UUIDs — some databases (PostgreSQL, SQL Server) have extensions to generate sequential UUID variants
When you need traceability: A v4 UUID reveals nothing about when or where it was generated. For distributed tracing, v1 (includes MAC address) or v7 (includes timestamp) provide more context in the ID itself.
When storage is critical: UUID v4 stores as 16 bytes (binary) or 36 chars (string). For high-volume tables, this overhead matters. Alternatives like Twitter Snowflake IDs use 64-bit integers (8 bytes).
UUID v4 in databases
PostgreSQL
-- Generate UUID v4:
SELECT gen_random_uuid(); -- Built-in since PostgreSQL 13
-- or: SELECT uuid_generate_v4(); -- requires pgcrypto extension
-- UUID as primary key:
CREATE TABLE users (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
email TEXT NOT NULL
);
-- UUIDs don't auto-increment, but they're globally unique:
INSERT INTO users (email) VALUES ('user@example.com') RETURNING id;
-- Returns: "f47ac10b-58cc-4372-a567-0e02b2c3d479"
MySQL / MariaDB
-- Generate UUID:
SELECT UUID();
-- "f47ac10b-58cc-4372-a567-0e02b2c3d479"
-- Optimized UUID storage (binary, not string):
CREATE TABLE users (
id BINARY(16) DEFAULT (UUID_TO_BIN(UUID(), TRUE)) PRIMARY KEY,
email VARCHAR(255) NOT NULL
);
-- UUID_TO_BIN with TRUE flag reorders bytes for better index performance
-- TRUE = swap time_hi and time_low (optimized for v1, less relevant for v4)
MongoDB
MongoDB’s ObjectId is not a UUID but fills a similar role — 12 bytes embedding a timestamp, random value, and counter. If you need standard UUIDs in MongoDB, store them as strings or binary:
const { v4: uuidv4 } = require('uuid');
const { Binary } = require('mongodb');
// Store as binary (16 bytes):
const id = Binary.createFromHexString(uuidv4().replace(/-/g, ''), 4);
// Or store as string (36 chars):
const doc = { _id: uuidv4(), name: 'example' };
Validating UUID v4
// Regex to validate any UUID:
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// Regex to validate UUID v4 specifically:
const uuidV4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isUUIDv4(str) {
return uuidV4Regex.test(str);
}
console.log(isUUIDv4('f47ac10b-58cc-4372-a567-0e02b2c3d479')); // true
console.log(isUUIDv4('f47ac10b-58cc-1372-a567-0e02b2c3d479')); // false (v1, not v4)
Related tools
- UUID Generator — generate v4 UUIDs instantly
- UUID Generator Online — UUID generation guide
- ULID Generator — sortable alternative to UUID v4
Related posts
- UUID v4 vs v7 for Databases: The Benchmark You Need — UUID v4 fragments your primary key index. UUID v7 fixes it with millisecond-orde…
- CUID2 — Collision-Resistant IDs Better Than UUID v4 — CUID2 generates secure, URL-safe, database-friendly IDs with better collision re…
- NanoID vs UUID — Which Unique ID Generator Should You Use? — NanoID generates shorter, URL-safe unique IDs using a custom alphabet. UUID v4 i…
- ULID Generator — Universally Unique Lexicographically Sortable Identifiers — ULID is a 26-character sortable unique identifier that embeds a millisecond time…
- UUID Generator Online — Generate UUID v4 and v7 Instantly — A UUID is a 128-bit identifier formatted as 32 hex digits in 5 groups. UUID v4 u…
Related tool
Generate UUID v4 and v7 identifiers in bulk.
Written by Mian Ali Khalid. Part of the Dev Productivity pillar.