A UUID (Universally Unique Identifier) is a 128-bit identifier used to uniquely identify resources in distributed systems, databases and APIs. Its collision probability is so low that it is considered practically unique in any system.

UUID version 4 is the most common: it is generated pseudo-randomly according to the RFC 4122 standard. It is represented in hexadecimal with hyphens: 8-4-4-4-12 characters (xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx). UUID v4 is not sorted: successively generated UUIDs are not ordered, which can cause performance issues with B-tree indexes in databases. ULID (Universally Unique Lexicographically Sortable Identifier) solves this by embedding a timestamp in the first bits.

📐 Formula

UUID v4: 122 random bits out of 128 bits | Collision probability: 1 in 5.3 × 10³⁶ for any 2 UUIDs

📊 Reference table

Format Length Sorted Collision prob. Use case
UUID v4 36 chars (with hyphens) No ~10⁻³⁶ General ID, database
UUID v1 36 chars Partial ~10⁻³⁶ ID with MAC timestamp
ULID 26 chars Yes (lexico.) ~10⁻³⁶ Sortable logs, events
NanoID 21 chars (default) No ~10⁻³⁰ Short URLs, compact IDs
Cuid2 24 chars No ~10⁻³⁶ Secure ID, web

💡 Practical examples

Example 1: UUID v4 as PostgreSQL primary key CREATE TABLE users (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), ...); — gen_random_uuid() generates UUID v4. Advantage: no conflicts between distributed servers. Drawback: less performant index than SERIAL/BIGSERIAL.
Example 2: UUID as session identifier session_id = crypto.randomUUID() — native JavaScript (browser + Node.js 14.17+). Generating a UUID server-side for each session guarantees uniqueness without a shared database.
Example 3: ULID for sortable logs A ULID like 01ARYZ6S41TPTWGY5UDXX5 embeds a timestamp (48 bits) + random (80 bits). Logs can be naturally sorted by insertion order without a separate index.