UUID v4 vs v7: Which Should You Use?
· Cosyslabs
UUID v4 generates a fully random 128-bit identifier, while UUID v7 prefixes a millisecond Unix timestamp making IDs sortable by creation time. Use UUID v7 for database primary keys to improve index locality and insert performance. Use UUID v4 when you need unpredictable IDs with no time correlation.
UUID Structure: The Basics
A UUID is a 128-bit value displayed as 32 hex digits in five groups:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
^ ^
| +-- Variant bits (always 10xx)
+------- Version digit
The version digit M identifies the UUID type. The variant bits N are always 8, 9, a, or b in RFC 4122 UUIDs.
UUID v4: Pure Random
UUID v4 uses a cryptographically secure random number generator for 122 bits (6 bits are fixed for version and variant):
f47ac10b-58cc-4372-a567-0e02b2c3d479
^ ^
4 [89ab] — v4 signature
Generating UUID v4:
// Browser / Node.js 14.17+
const id = crypto.randomUUID();
// "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Older Node.js
const { v4: uuidv4 } = require("uuid");
const id = uuidv4();
import uuid
id = str(uuid.uuid4())
-- PostgreSQL
SELECT gen_random_uuid();
-- MySQL 8+
SELECT UUID(); -- generates v1, not v4
UUID v4 Strengths
- Unpredictable: 122 bits of randomness — practically impossible to guess
- Universal: supported everywhere, no coordination needed
- No information leakage: creation time, machine, or sequence is not embedded
UUID v4 Weaknesses
- Random inserts fragment B-tree indexes: each new row lands at a random position in the index, causing page splits and poor cache utilization
- Not sortable: you cannot determine insertion order from UUID v4 values
UUID v7: Time-Ordered
UUID v7 (RFC 9562, finalized 2024) encodes a 48-bit Unix timestamp in milliseconds in the most significant bits:
01905b80-3e40-7abc-8def-123456789abc
^^^^^^^^ ^^^^
48-bit ms timestamp | version 7
Generating UUID v7:
// uuid package v9+
import { v7 as uuidv7 } from "uuid";
const id = uuidv7();
// "01905b80-3e40-7abc-8def-123456789abc"
// Custom implementation
function uuidv7() {
const timestamp = BigInt(Date.now());
const randomA = BigInt(Math.floor(Math.random() * 0xfff));
const randomB = BigInt(Math.floor(Math.random() * 0x3fffffffffffffff));
const msHigh = (timestamp >> 16n) & 0xffffffffn;
const msLow = timestamp & 0xffffn;
const ver = 7n;
const variant = 0b10n;
// Full construction omitted for brevity — use the uuid package
}
-- PostgreSQL 17+ (native UUID v7 support)
SELECT uuidv7();
-- PostgreSQL 14-16 (extension)
CREATE EXTENSION IF NOT EXISTS "pg_uuidv7";
SELECT uuid_generate_v7();
UUID v7 Strengths
- Sequential inserts: new rows append near the end of B-tree indexes — no page splits
- Sortable:
ORDER BY idgives chronological order for free - Partitioning-friendly: timestamp prefix enables efficient time-based partitioning
- Still unique: 74 bits of randomness after the timestamp provides collision resistance
UUID v7 Weaknesses
- Time correlation: the timestamp reveals when a record was created — avoid for security-sensitive IDs exposed to users
- Clock dependency: monotonicity depends on system clock accuracy; two UUIDs generated in the same millisecond require sub-millisecond sequencing logic
Performance Comparison
The core performance difference matters at scale:
| Metric | UUID v4 | UUID v7 |
|---|---|---|
| Index fragmentation | High | Low |
| Insert performance (10M rows) | ~3x slower | Baseline |
| Sequential scan order | Random | Chronological |
| Cache hit rate (B-tree) | Low | High |
| Storage (bytes) | 16 | 16 |
Benchmarks on PostgreSQL with 50M rows show UUID v7 primary keys achieve 2–4x higher insert throughput compared to UUID v4 due to reduced index page splits and better write amplification.
When to Use Each
Use UUID v7 for:
- Database primary keys (relational or document stores)
- Event sourcing IDs where chronological order matters
- Distributed systems where you want time-based ordering without a central counter
- Log correlation IDs where insertion order equals event order
Use UUID v4 for:
- Password reset tokens, session IDs, or any security-sensitive identifier exposed to users
- API keys or invitation codes where unpredictability is a security requirement
- Cases where embedding creation time is a privacy concern
- Systems where you cannot rely on clock accuracy
What About UUID v1?
UUID v1 also embeds a timestamp but uses:
- A 60-bit 100-nanosecond timestamp (from 1582)
- A MAC address for uniqueness
UUID v1 is deprecated for new projects. It leaks the machine's MAC address, the timestamp bytes are scrambled (not sortable), and MAC addresses are not always unique in containerized environments. UUID v7 supersedes v1 for time-ordered use cases.
Database-Specific Notes
PostgreSQL: Use the native uuid column type (16 bytes). UUID v7 works with this type.
MySQL: The VARCHAR(36) UUID storage is inefficient. Use BINARY(16) and store UUIDs without hyphens. Consider ORDERED UUID or ULID instead.
MongoDB: MongoDB's ObjectId is a 12-byte time-ordered ID similar conceptually to UUID v7 — already sequential. For compatibility with UUID-expecting systems, use UUID v7.
SQLite: No native UUID type. Store as TEXT(36) or BLOB(16).
Try It Now
Generate UUID v4 and v7 values instantly with the UUID Generator Tool — runs entirely in your browser.
Summary
- UUID v4: 122 random bits — unpredictable, not sortable, causes index fragmentation
- UUID v7: 48-bit timestamp + 74 random bits — sortable, index-friendly, reveals creation time
- Use UUID v7 for database primary keys unless unpredictability is a security requirement
- UUID v7 is standardized in RFC 9562 (2024) and supported by major databases natively
More Tools from Cosyslabs
- Rough Estimator — Estimate the time and cost to migrate a legacy database from sequential integer IDs or UUID v4 to UUID v7 primary keys.
- Unit Convert All — Convert data storage units when modeling UUID-based table growth (e.g., 16 bytes × N million rows → GB of index space).
- PDF Convert All — Generate and download PDF reports from data identified by UUID-keyed records.
- Cosyslabs — The studio behind Dev Tools !, Routine Toolkit, Astrilio, CastFleet, and more.