uuid guid generate developer-tools

The Ultimate UUID/GUID Guide: Everything You Need to Know About Unique Identifiers

Master UUIDs and GUIDs. Learn about different versions (v1, v4, v6, v7), their use cases in modern software, and generate them instantly.

2026-04-09 Use This Tool

What Is a UUID?

A UUID (Universally Unique Identifier), also known as a GUID (Globally Unique Identifier) in Microsoft terminology, is a 128-bit number used to uniquely identify information in computer systems. Unlike auto-increment integers that require a central authority to hand out the next value, UUIDs can be generated independently by any machine, at any time, with an astronomically low chance of collision.

The canonical textual representation of a UUID looks like this:

550e8400-e29b-41d4-a716-446655440000
^^^^^^^^ ^^^^ ^^^^ ^^^^ ^^^^^^^^^^^^
  time   time vers  var    node

That hyphenated string encodes 32 hexadecimal digits (128 bits) in the format xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx, where:

  • M is the version digit (1, 3, 4, 5, or 7)
  • N is the variant nibble (8, 9, a, or b for RFC 4122-compliant UUIDs)

A Brief History

The concept of a universally unique identifier originated at Apollo Computer and Digital Equipment Corporation (DEC) in the late 1980s as part of the Network Computing System (NCS) and Distributed Computing Environment (DCE). The goal was to allow distributed systems to create identifiers without any central registry.

Microsoft adopted the concept for COM/OLE and called it a GUID, but the underlying structure is identical to a UUID. The two terms are interchangeable in practice.

The formal specification arrived with RFC 4122, published in July 2005 by the IETF. It standardised five UUID versions (v1–v5) and defined the variant bits. Two decades later, RFC 9562 (published in May 2024) superseded RFC 4122 and officially added UUID versions 6 and 7, which address the database-performance shortcomings of earlier versions.


UUID Structure: 128 Bits Explained

A UUID is always exactly 128 bits (16 bytes). When formatted as a string, it is 36 characters long (32 hex digits + 4 hyphens).

Field             Bits   Hex digits  Description
─────────────────────────────────────────────────────
time_low            32       8       Low 32 bits of timestamp (v1) / data
time_mid            16       4       Mid 16 bits of timestamp (v1) / data
time_hi_and_version 16       4       High 12 bits of timestamp + 4-bit version
clock_seq_hi_res     8       2       Variant bits + high clock sequence
clock_seq_low        8       2       Low clock sequence
node                48      12       Node ID (MAC address in v1, random otherwise)

The version is encoded in the most significant 4 bits of the time_hi_and_version field (the 13th hex character). The variant is encoded in the 2–3 most significant bits of clock_seq_hi_res (the 17th hex character).


UUID Versions Explained

Version 1 — Time-Based

UUID v1 combines a 60-bit timestamp (100-nanosecond intervals since 15 October 1582) with the host's MAC address and a clock sequence.

Example: 6ba7b810-9dad-11d1-80b4-00c04fd430c8

Pros: Contains temporal information, making it roughly sortable by creation time.
Cons: Embeds the MAC address, which raises privacy concerns — it can reveal when and where a UUID was generated. Not recommended for public-facing identifiers.

Version 2 — DCE Security

UUID v2 replaces part of the timestamp with a POSIX UID/GID and a domain identifier. It is defined in the DCE 1.1 specification but rarely used in practice because it sacrifices uniqueness guarantees for the domain embedding.

Version 3 — Name-Based (MD5)

UUID v3 generates a deterministic UUID from a namespace UUID and a name by hashing them with MD5.

Example: 5df41881-3aed-3515-88a7-2f4a814cf09e (namespace DNS + "example.com")

Use case: Stable, reproducible identifiers for the same logical resource. If you hash the same namespace + name twice, you always get the same UUID.
Caution: MD5 is cryptographically weak. Prefer v5 for new systems.

Version 4 — Random (Most Popular)

UUID v4 uses 122 bits of cryptographically random data (the remaining 6 bits are used for version and variant).

Example: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

This is by far the most commonly used UUID version. It requires no coordination, no network access, and no knowledge of the host. The randomness comes from a CSPRNG (cryptographically secure pseudorandom number generator).

Version 5 — Name-Based (SHA-1)

UUID v5 is identical in concept to v3 but uses SHA-1 instead of MD5.

Example: 886313e1-3b8a-5372-9b90-0c9aee199e5d (namespace DNS + "example.com")

Use case: Whenever you need deterministic, reproducible UUIDs and want a stronger hash than MD5. SHA-1 is still not cryptographically secure for all purposes, but it is significantly better than MD5 for collision resistance.

Version 7 — Time-Ordered (Recommended for Databases)

UUID v7 is the star of RFC 9562. It embeds a 48-bit Unix timestamp in milliseconds in the most significant bits, making the UUID k-sortable — UUIDs generated later sort after UUIDs generated earlier.

Example: 018e8f5a-2b3c-7d4e-8f9a-0b1c2d3e4f50

The first 12 hex characters (018e8f5a-2b3c) encode the millisecond timestamp. The remainder is random. This makes v7 ideal as a database primary key: it retains the global uniqueness of v4 while being insertion-ordered, which dramatically reduces B-tree index fragmentation.


Collision Probability: The Birthday Problem

UUID v4 uses 122 bits of randomness. The probability of a collision can be estimated using the birthday problem formula:

p(n) ≈ 1 − e^(−n²/2N)

where N = 2^122 ≈ 5.32 × 10^36 (total possible UUIDs).

To have a 50% chance of at least one collision, you would need to generate approximately 2.71 × 10^18 (2.71 quintillion) UUIDs. At a rate of 1 billion UUIDs per second, that would take about 86 years.

For practical purposes, UUID v4 collisions are so improbable that they can be treated as impossible in every real-world application.


UUID vs. Auto-Increment IDs

Feature UUID v4 Auto-Increment
Uniqueness scope Global Local (per table)
Generation location Client-side Server-side
Predictability Non-predictable Sequential
URL safety Yes (with encoding) Yes
DB index performance Poor (random) Excellent (sequential)
Merge / replication Easy Conflict-prone
Storage size 16 bytes (binary) 4–8 bytes
Human readability Low High
Security (enumeration) Safe Vulnerable

Auto-increment IDs are perfectly fine for single-database applications with no distributed requirements. UUIDs shine when:

  • Multiple services or databases need to generate IDs independently.
  • Records may be merged from different sources.
  • You want to avoid exposing sequential IDs in URLs (enumeration attacks).

Database Performance: v4 vs. v7

The Problem with UUID v4 in Databases

Because UUID v4 is random, each new row is inserted at a random position in the B-tree index. This causes:

  1. Index page splits — the database must frequently split index pages to accommodate out-of-order insertions.
  2. Cache thrashing — random access patterns defeat the buffer pool, causing frequent disk reads.
  3. Write amplification — significantly more I/O than sequential inserts.

Benchmarks on large tables (>10M rows) often show UUID v4 primary keys performing 3–5× worse than sequential keys for insert-heavy workloads.

UUID v7 Solves This

UUID v7 is monotonically increasing within the same millisecond window. New records are inserted at or near the end of the index, similar to auto-increment. The result is:

  • Near-zero index fragmentation.
  • Optimal buffer pool utilisation.
  • Insert performance comparable to auto-increment.

Recommendation: Use UUID v7 for any new database schema that needs globally unique primary keys.


Distributed Systems Use Cases

UUIDs are the backbone of distributed identity:

  • Microservices: Each service can generate IDs independently without talking to a central sequence server.
  • Event sourcing: Events get immutable IDs that remain unique across replays and rehydrations.
  • CQRS: Commands and queries can be correlated by a UUID generated at the client.
  • Multi-region databases: Records created in different regions never clash, making eventual consistency and merge operations trivial.
  • Idempotency keys: APIs can use client-generated UUIDs as idempotency keys to safely retry requests.
  • Content-addressable systems: UUID v3/v5 can produce stable identifiers for the same resource across systems.

ULID: A Modern Alternative

ULID (Universally Unique Lexicographically Sortable Identifier) is a community-developed alternative to UUID that is URL-safe by default and always sortable.

Feature UUID v4 UUID v7 ULID
Sortable No Yes Yes
URL-safe With encoding With encoding Yes (Crockford Base32)
Time component No Yes (ms) Yes (ms)
Standard RFC 9562 RFC 9562 Community spec
Format length 36 chars 36 chars 26 chars
Monotonic within ms No Optional Yes

ULID looks like 01ARZ3NDEKTSV4RRFFQ69G5FAV — 26 characters, no hyphens, safe to use directly in URLs. If you need sortability and URL-safety out of the box without worrying about RFC compatibility, ULID is worth considering.


Generating UUIDs in Different Languages

JavaScript / TypeScript (Node.js & Browser)

import { v4 as uuidv4, v7 as uuidv7 } from 'uuid';

const randomId  = uuidv4(); // "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"
const sortableId = uuidv7(); // "018e8f5a-2b3c-7d4e-8f9a-0b1c2d3e4f50"

// Native crypto (Node 14.17+ / modern browsers)
const nativeId = crypto.randomUUID(); // UUID v4

Python

import uuid

# v4 — random
print(uuid.uuid4())  # e.g. "f47ac10b-58cc-4372-a567-0e02b2c3d479"

# v5 — deterministic from namespace + name
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com'))
# "886313e1-3b8a-5372-9b90-0c9aee199e5d"

# v1 — time-based
print(uuid.uuid1())

Go

import "github.com/google/uuid"

id := uuid.New()          // UUID v4
v7, _ := uuid.NewV7()    // UUID v7 (google/uuid v1.6+)
fmt.Println(id.String())

Java

import java.util.UUID;

UUID v4 = UUID.randomUUID();
System.out.println(v4); // "3e4666bf-d5e5-4aa7-b8ce-cefe41c7568a"

// Name-based v5 requires a third-party library (e.g., com.fasterxml.uuid)

Rust

use uuid::Uuid;

let v4 = Uuid::new_v4();
let v7 = Uuid::now_v7();
println!("{}", v4);
println!("{}", v7);

C# / .NET

using System;

Guid g = Guid.NewGuid(); // UUID v4
Console.WriteLine(g.ToString()); // "d2719d7b-aaef-4b9f-8e96-8ea6e7e08fdf"

Best Practices

  1. Use v4 for general-purpose unique identifiers where ordering doesn't matter and you want maximum simplicity.
  2. Use v7 for database primary keys to avoid index fragmentation and get natural sort order.
  3. Use v5 for deterministic IDs when you need the same input to always produce the same UUID (e.g., de-duplicating content by URL).
  4. Avoid v1 in privacy-sensitive contexts — it embeds your MAC address and creation time.
  5. Store UUIDs as binary (16 bytes) in the database, not as varchar(36), to save space and improve index performance.
  6. Never use v2 unless you are specifically implementing DCE Security.
  7. Validate input UUIDs on API boundaries to prevent injection of malformed identifiers.
  8. Use a well-tested library rather than rolling your own UUID generation — entropy sourcing is easy to get wrong.

Frequently Asked Questions

Q: Is a UUID the same as a GUID?
A: Functionally, yes. GUID is Microsoft's name for the same 128-bit identifier format. The structure is identical; only the terminology differs.

Q: Can two UUIDs ever be the same?
A: In theory yes, but the probability is negligibly small for v4. You'd need to generate 2.71 quintillion UUIDs to have a 50% chance of a single collision. In practice, you will never encounter a collision.

Q: Which UUID version should I use for database primary keys?
A: UUID v7 is the best choice. It's time-ordered (good for B-tree indexes), globally unique, and standardised in RFC 9562. If your library doesn't support v7 yet, use a ULID or a "COMB" UUID pattern as a workaround.

Q: Is UUID v4 secure enough to use as a session token?
A: UUID v4 has 122 bits of randomness, which is generally sufficient. However, dedicated session token libraries (e.g., nanoid, secrets.token_urlsafe in Python) may use slightly more entropy or better encodings. For high-security contexts, prefer a dedicated token generator.

Q: How do I store a UUID efficiently in a SQL database?
A: Use a native UUID column type if available (PostgreSQL, MySQL 8+), or a BINARY(16) column. Avoid CHAR(36) / VARCHAR(36), which takes 2.25× more space and is slower to index.

Q: What is the difference between UUID v3 and v5?
A: Both are name-based and deterministic. v3 uses MD5; v5 uses SHA-1. SHA-1 has better collision resistance, so v5 is preferred for new systems. Neither should be used for security-critical hashing.

Q: Does UUID v7 replace UUID v4?
A: For database primary keys, yes — v7 is strictly better. For other use cases (e.g., API keys, tokens, correlation IDs) where ordering is irrelevant, v4 remains perfectly fine.


Summary

UUIDs are a foundational primitive in modern software engineering. Understanding the differences between versions helps you make the right trade-off:

  • v4 — best for general uniqueness with zero coordination.
  • v5 — best for deterministic, reproducible identifiers.
  • v7 — best for database primary keys due to time-ordering.

Whether you are building a monolith, a microservices architecture, or a globally distributed database, UUIDs provide a battle-tested, standardised way to identify your data uniquely and safely.