UUID Generator Developer Guide: Mechanics, Versions & Use Cases (2026)
Most UUID tutorials stop at "call this function and get a string." This one covers the mechanics that decide whether your identifiers actually hold up: the 128-bit layout, the five official RFC 4122 versions and when each one earns its keep, the 122 random bits behind a v4 and why collisions are still a non-event, formatting variants from urn:uuid: to braced GUIDs, and the honest trade-offs of UUIDs as primary keys versus auto-increment, NanoID, and ULID. The goal is identifiers you can defend in code review, not just paste from a generator.
What a UUID Actually Is
A UUID (Universally Unique Identifier, also called GUID in Microsoft ecosystems) is a 128-bit identifier standardized by RFC 4122. The 128 bits are laid out as 16 bytes, and the canonical text representation uses 32 hexadecimal characters arranged in five groups of 8-4-4-4-12 separated by four hyphens, for a total of 36 characters:
550e8400-e29b-41d4-a716-446655440000
^^^^^^^^ ^^^^ ^^^^ ^^^^ ^^^^^^^^^^^^
8 4 4 4 12 = 32 hex chars
4 hyphens = 4 chars
Total = 36 chars
That is the whole shape: 128 bits, 16 bytes, 32 hex digits, 4 hyphens, 36 characters. Two of those bits are not random in any version: the version nibble (the first hex digit of the third group, position 14) records which of the five algorithms produced the value, and the variant bits (the first one or two bits of the fourth group, position 19) record which standard the layout follows. For an RFC 4122 UUID the variant bits are 10, which is why the fourth group of a v4 UUID always starts with 8, 9, a, or b. In our example 550e8400-e29b-41d4-a716-446655440000, the third group starts with 4 (version 4) and the fourth group starts with a (binary 1010, so the high two bits are 10, the RFC 4122 variant). Both are required; both are checkable.
The reason this all works is arithmetic, not magic. The address space is 2128, which is roughly 3.4 × 1038. Fill the observable universe with grains of sand and you are still orders of magnitude short of 2128. Within that space, each generation algorithm carves out a slice so large that independently produced UUIDs almost never collide. Our UUID Generator produces v1 and v4 values directly from your browser so you can see the layout for yourself, and the surrounding developer tools guide catalogs the rest of the identifier-oriented tools.
The Five Official UUID Versions
RFC 4122 defines five algorithms, each filling the 128 bits differently. They share the version and variant bits; everything else depends on the version.
| Version | Name | Source of bits | Deterministic? | Sortable by time? |
|---|---|---|---|---|
| v1 | Time-based | 60-bit timestamp (100 ns intervals since 1582-10-15) + 14-bit clock sequence + 48-bit MAC node | No | Yes (within a host) |
| v2 | DCE Security | v1 layout with the low 32 bits of the timestamp replaced by a POSIX UID or GID | No | Loosely |
| v3 | Name + MD5 | MD5(namespace UUID ‖ name) trimmed to 128 bits, version and variant set | Yes (same name → same UUID) | No |
| v4 | Random | 122 random bits from a cryptographically strong RNG, 6 bits fixed (version + variant) | No | No |
| v5 | Name + SHA-1 | SHA-1(namespace UUID ‖ name) trimmed to 128 bits, version and variant set | Yes (same name → same UUID) | No |
UUID v1: time-based, with a MAC address
A v1 UUID stitches together three fields: a 60-bit count of 100-nanosecond intervals since the Gregorian epoch (15 October 1582), a 14-bit clock sequence that disambiguates when a clock rolls back or changes host, and a 48-bit node identifier that is almost always the generating host's MAC address. The arithmetic fits: 60 + 14 + 48 = 122 bits of real data, plus the 4-bit version and 2-bit variant for the full 128. Because the timestamp dominates, v1 UUIDs generated on the same host are monotonically increasing, which makes them useful when you need a rough ordering of when rows were created without a separate created_at column. The cost is privacy: the MAC address leaks a hardware identifier, which is why most modern v1 implementations replace the node with a random 48-bit value (a "pseudonymous MAC") rather than the real hardware address.
UUID v2: DCE Security, the rare one
Version 2 is barely seen in the wild. It reuses the v1 layout but overwrites the low 32 bits of the 60-bit timestamp with a POSIX UID (user ID) or GID (group ID) plus a marker byte. The trade is that v2 carries an OS principal identifier inside the UUID, which is useful inside DCE/RPC environments that already speak POSIX UIDs and almost nowhere else. The timestamp now has only 28 bits of effective resolution, so v2 UUIDs are not safely sortable across more than a few seconds of wall clock. Most standard libraries do not implement v2; if you need it, you usually have to build it by hand.
UUID v3 and v5: name + namespace, deterministic
Both v3 and v5 take a namespace UUID (a fixed UUID that names a domain, like DNS or URLs) and a name string, concatenate them, hash the result, and lay the digest into the UUID layout. The only difference is the hash: v3 uses MD5 (128-bit output, used directly), v5 uses SHA-1 (160-bit output, truncated to 128 bits). Both are deterministic: the same namespace plus the same name always produces the same UUID, on every machine, forever. That is the whole point. Use them when you need stable IDs derived from something you already have: a stable URL, a customer email, a domain name. Because SHA-1 is the stronger hash, prefer v5 in new code; v3 is preserved for systems that already have MD5-derived IDs baked in and cannot migrate without breaking references.
UUID v4: random, the default
Version 4 is what almost every UUID you have ever seen actually is. The algorithm is almost nothing: draw 128 bits from a cryptographically strong random number generator, overwrite the version nibble with 0100 (4) and the variant bits with 10, output the result. After those six fixed bits, 122 bits remain random, which is the headline number behind every collision-probability claim you have ever read about UUIDs. There is no timestamp, no MAC, no namespace; v4 values are uniform across the entire address space, which is what makes them safe to generate anywhere without coordination.
// JavaScript (Node 19+ and all modern browsers)
const id = crypto.randomUUID();
// "550e8400-e29b-41d4-a716-446655440000" (v4, lowercase, with hyphens)
// Python 3
import uuid
print(uuid.uuid4()) # UUID('550e8400-e29b-41d4-a716-446655440000')
// Go
import "github.com/google/uuid"
id := uuid.New() // 550e8400-e29b-41d4-a716-446655440000
The five versions together cover the design space: v4 for the default, v1 when ordering or traceability matter, v3 and v5 when IDs must be derived from names, and v2 for the rare DCE environment. The remaining sections are about choosing between them in real code.
When to Use Which Version
Most projects pick once and never revisit. The decision tree is small enough to fit in a paragraph: start with v4, switch only if you have a stated reason.
Default: UUID v4
Use v4 unless you can write down a reason not to. It is what crypto.randomUUID(), uuid.uuid4(), uuid.New(), java.util.UUID.randomUUID(), crypto.randomUUID() in Swift, and every ORM default produce. It needs no clock, no network, no MAC, and no coordination, and 122 random bits is more than enough uniqueness for any realistic workload. Pair it with our random-string-generator when you need short, shareable tokens instead of full UUIDs.
Use UUID v1 when you need ordering or traceability
Reach for v1 in exactly two situations: you need IDs that sort by creation time (and you do not have a separate created_at column), or you need to trace an ID back to the generating host for debugging. The first situation is rarer than people think: most production schemas already store a timestamp, and that timestamp is more honest than the v1 timestamp because it is not limited by 100-nanosecond clock resolution or by clock skew across hosts. The second situation is real, but should use a pseudonymous random node, not a real MAC, to avoid leaking hardware identifiers. If you want time-ordered and random-friendly, look at ULID or UUID v7 instead of v1; both are covered later in this guide.
Use UUID v3 or v5 when you need deterministic IDs from names
The use case is "I have a stable string and I want the same UUID every time." Two patterns come up constantly. The first is content-addressing: a CDN that needs a stable cache key for https://example.com/asset.css can compute uuid5(NAMESPACE_URL, "https://example.com/asset.css") once and use the result as a cache key without a registry. The second is idempotency: an event processor that must deduplicate inbound events can use uuid5(NAMESPACE_DNS, event.correlation_id) so the same logical event always maps to the same UUID, even if it arrives twice. Use v5 for new systems (SHA-1 is the stronger hash); use v3 only when interoperating with systems already pinned to MD5. Either way, the namespace UUID prevents accidental collisions between unrelated systems that happen to use the same name string.
// Deterministic IDs from names: same input always yields same UUID
const { v5: uuidv5 } = require('uuid');
const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; // RFC 4122
const cacheKey = uuidv5('https://example.com/asset.css', NAMESPACE_URL);
// '3a5c3b8e-1f8e-5c8a-9d2a-7e1c5b8e3a5c' (always, on every machine)
const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const userId = uuidv5('alice@example.com', NAMESPACE_DNS);
// same UUID every time, no registry needed
The "when not to use" half of the decision is shorter: do not use v1 if privacy matters (MAC leak), do not use v2 unless you are explicitly in a DCE environment, do not use v3 in new code (use v5), and do not build a custom UUID format if any standard version fits. Custom formats lose the cross-language parser guarantee that makes UUIDs worth using in the first place.
Collision Probability: Why 122 Random Bits Is Enough
The single sentence that lets engineers sleep at night: a v4 UUID has 122 random bits, and the birthday bound says you reach a 50 percent chance of a single collision at roughly 261 generated IDs, which is about 2.3 × 1018 values. To get there you would need to generate one billion UUIDs per second for about 73 years. The number is large enough that real-world v4 collisions are caused by broken random number generators (a famous early JavaScript bug seeded from Math.random() on the same second), not by chance.
The birthday bound, in one paragraph
The birthday problem asks: given N items drawn uniformly from a space of size S, how large can N get before two of them probably match? The threshold for a 50 percent chance is approximately N ≈ sqrt(S). For v4, S = 2122, so N ≈ 261. The arithmetic is exact: sqrt(2122) = 261 ≈ 2.305 × 1018. The full collision probability for N IDs is about 1 − exp(−N2 / (2 × 2122)), and at N = 261 that expression evaluates to about 0.39 (with a tighter approximation), but the rule of thumb "50 percent at 261" is the version engineers actually use and it is accurate within a constant factor. The conclusion holds regardless: the threshold is astronomically larger than any production system will ever generate.
By the numbers, machine-verified
- 2128 = 340,282,366,920,938,463,463,374,607,431,768,211,456 (full UUID space, all versions)
- 2122 = 5,316,911,983,139,663,936,019,748,750,721,568,704 (v4 random subset)
- 261 = 2,305,843,009,213,693,952 (50 percent birthday threshold for v4)
- 2103 ≈ 1.0 × 1031 IDs for a one-in-a-billion collision chance at v4 (the conservative engineering threshold)
For deterministic versions, the picture is different. v3 and v5 inherit the collision behavior of their hash: MD5 has known collision attacks and should not be used where an adversary might choose the name, while SHA-1 also has practical collision attacks (SHAttered, 2017) but only when the attacker controls both inputs. For deduplication and cache-key use cases where the name is not adversarial, v5 is still fine; for anything that crosses a trust boundary, switch to a v4 UUID stored in a registry rather than hashing the name.
Math.random() used as the RNG, a VM cloned without re-seeding, a firmware RNG that stalled during boot, or a custom UUID format that quietly reduced the random bit count. Audit your RNG, do not audit the birthday bound.
UUID vs Auto-Increment: a Real Decision
The default database primary key for thirty years was an integer that went up by one each row. UUIDs are now common in that role, and the trade is not free. The honest comparison is by what each one guarantees and what each one costs.
What auto-increment does well
An auto-increment integer is compact (4 or 8 bytes), dense (no gaps from random insertion), friendly to clustered indexes (each new row appends to the end of the B-tree), and trivially ordered. It is the right choice for a single-writer database that never needs to merge rows from a second source. Its weakness is that it cannot be generated without the database: a service that needs an ID before the row exists must either hold a transaction open or pre-allocate a block, and a federated system cannot merge two databases without renumbering one of them.
What UUIDs do well
A UUID can be generated by anyone, anywhere, without coordination. A client can mint an ID for a record it is about to create, send it through an event pipeline, and have it land in three databases already consistent. UUIDs never leak row counts the way sequential integers do (seeing order_id=1247 tells a customer roughly how many orders preceded theirs), and they make sharding trivial: each shard mints its own IDs and merges without collisions. The costs are storage (16 bytes binary, 36 bytes text), and index fragmentation: a fully random v4 UUID inserts into the middle of a B-tree on every write, which is more expensive than an append.
The decision in one sentence
If you generate IDs in one place, on one database, and never merge from outside, auto-increment is fine. If you generate IDs in more than one place, or you ever merge data from external sources, or you simply do not want to leak row counts, use a UUID. When you do, store it as a 16-byte binary type, not the 36-character text form, and consider a time-ordered variant (UUID v7 or ULID) if writes are heavy enough that index fragmentation actually shows up in production metrics.
-- Store UUIDs as binary(16), not as char(36).
-- PostgreSQL has a native uuid type (16 bytes, indexed as binary):
CREATE TABLE events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- v4, 16 bytes
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- MySQL 8: store as BINARY(16) for the same effect:
CREATE TABLE events (
id BINARY(16) PRIMARY KEY,
payload JSON NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Insert with UUID_TO_BIN(x, swap) for time-ordered v7 storage.
The full developer-tooling angle on the wider identifier ecosystem, including how UUIDs compare to slug-based IDs and content addressing, is catalogued in the developer tools guide; this article stays on the UUID-vs-alternative comparison.
UUID vs NanoID and ULID
Two alternatives to UUID have become common in modern stacks, and both are worth knowing because each fixes a real UUID pain point.
NanoID: shorter, URL-safe, 126 random bits
NanoID is a 21-character string drawn from a 64-character URL-safe alphabet (A–Z, a–z, 0–9, -_). Twenty-one characters at 6 bits each is 126 bits of entropy, slightly more than a v4 UUID's 122. The wins are size (21 vs 36 characters), URL-safety (no hyphens to escape), and readability in shared links. The trade is ecosystem: NanoID is recognized by JavaScript and Python libraries, but not by every database, ORM, and parser the way UUID is. Use NanoID for shareable resource IDs in URLs and short-lived tokens; use UUID when you need cross-system uniqueness with no parser ambiguity.
ULID: 26 chars, sortable, 80 random bits
ULID is a 26-character string in Crockford's base32. The first 10 characters encode a 48-bit millisecond timestamp; the last 16 characters encode 80 random bits. Total entropy is 80 bits, which is well below v4's 122 but still enormous (280 ≈ 1.2 × 1024, and the birthday threshold is 240 ≈ 1.1 × 1012 per millisecond, which is unreachable in practice). The headline feature is sortability: ULIDs generated in the same millisecond sort lexicographically in the order they were created, and ULIDs from different milliseconds sort by time. That gives you the "v1 ordering" benefit without the MAC leak, and gives you the "v4 random" benefit within each millisecond. ULID is the right pick when you want UUID-level uniqueness plus time-ordered clustering in a primary-key index.
| Property | UUID v4 | NanoID | ULID |
|---|---|---|---|
| Length (chars) | 36 | 21 | 26 |
| Entropy (bits) | 122 | 126 | 80 (+ 48 ms timestamp) |
| Sortable by time | No | No | Yes (ms precision) |
| URL-safe (no escaping) | Hyphens need encoding | Yes | Yes (Crockford base32) |
| Spec / parser ubiquity | RFC 4122, universal | JS, Python, community | Community spec, growing |
| Best for | Default, cross-system | Short shareable IDs | Time-ordered primary keys |
UUID v7 (RFC 9562, the 2024 update to RFC 4122) is the standardized answer to ULID: 48-bit millisecond timestamp plus 74 random bits, in the canonical 36-character UUID layout. If your stack supports v7, it gives you the time-ordering of ULID with the universal parser support of UUID, and you can read the documentation best practices guide for how to write migration notes that explain the change to readers downstream.
Formatting Variants: Hyphens, Braces, and URN Prefixes
The 128 bits inside a UUID do not care how you print them, but every parser in your stack does. The three formats you will meet in production:
1. Canonical with hyphens (the default)
The RFC 4122 canonical form is the 8-4-4-4-12 layout, lowercase by convention: 550e8400-e29b-41d4-a716-446655440000. This is what every standard library outputs by default, what JSON-LD expects, and what database uuid columns store. Use it unless you have a reason.
2. Without hyphens (compact)
Stripping the four hyphens gives 32 hex characters: 550e8400e29b41d4a716446655440000. Same bits, 32 bytes instead of 36. Useful in filenames, short log keys, and anywhere the hyphens would need escaping. Most parsers accept both forms; the uuid command-line tool on Linux normalizes both ways.
3. Braced GUID (Microsoft)
Microsoft tooling wraps the value in curly braces: {550e8400-e29b-41d4-a716-446655440000}. The bytes, version, and variant are identical to the unbraced form; the braces are a presentation choice. .NET's Guid.ToString("B") produces this form, and the Windows registry stores COM interface IDs this way. Treat braces as transport encoding, not as part of the value: strip them before comparing or storing in a non-Microsoft system.
4. URN form (formal)
The urn:uuid: prefix marks the value as a URN: urn:uuid:550e8400-e29b-41d4-a716-446655440000. This is the form RDF, XML namespaces, and some enterprise registries use. Treat the URN prefix the same way as the GUID braces: a transport concern. Most UUID parsers strip it on input.
// Same UUID in four formats - identical 128 bits
const id = '550e8400-e29b-41d4-a716-446655440000';
id; // "550e8400-e29b-41d4-a716-446655440000" (canonical)
id.replaceAll('-', ''); // "550e8400e29b41d4a716446655440000" (compact, no hyphens)
'{' + id + '}'; // "{550e8400-e29b-41d4-a716-446655440000}" (braced GUID)
'urn:uuid:' + id; // "urn:uuid:550e8400-e29b-41d4-a716-446655440000" (URN)
// Parse any of them back to the same 128 bits:
const parsed = crypto.randomUUID(); // outputs canonical form
// Most parsers accept all four; normalize before comparing.
Two practical rules prevent most format bugs. First, normalize on the boundary: when a UUID enters your system, parse it once, store it as 16 binary bytes, and re-emit it in whatever format the consumer expects. Second, never compare UUIDs as strings without normalizing first: a braced GUID and an unbraced UUID with the same bits compare unequal as strings but equal as bytes. The data conversion workflows guide covers the same normalize-on-ingest discipline for other identifier formats.
The UUID-as-Primary-Key Debate
This is the argument that never quite resolves, because both sides are right about different things. The honest version is below.
The case for UUIDs as primary keys
Distributed generation is the killer feature. With UUIDs, any service can mint an ID before it touches the database, which means a single client can build a whole graph of related objects (order, line items, shipping record, audit log) and persist them in one transaction without a round-trip to fetch generated IDs. Federated systems merge without renumbering. Sharding is trivial: each shard mints independently. UUIDs also do not leak business metrics the way sequential integers do (no "you are our 47th customer" leaks). For any system that might grow past a single database, UUIDs are the right default.
The case against
Storage is the obvious cost: 16 bytes binary or 36 bytes text versus 4 or 8 bytes for an integer. Multiply by every foreign key that references the primary key, and a UUID-keyed schema can be two to four times larger than the integer equivalent. The less obvious cost is index fragmentation: a v4 UUID inserts into a random page of every B-tree index, which causes more page splits, more write amplification, and worse cache locality than an append-only integer. On a hot table this shows up as higher write latency and lower throughput, and the fix is to use a time-ordered UUID variant (v1, v7, or ULID) so inserts cluster at the end of the index.
The compromise most teams converge on
Use a UUID, store it as a 16-byte binary type, and pick the variant by workload. For a low-write table (users, organizations, products), v4 is fine and the index-fragmentation cost is invisible. For a high-write table (events, telemetry, audit logs), use v7 or ULID so inserts stay clustered. Never store UUIDs as the 36-character text form in a primary-key column; that quadruples the storage and slows every join. The companion pieces on schema design and migration live in the static-site-generators writeup (which uses content-addressed UUIDs for build artifacts) and the code minification guide (which uses content hashes, the deterministic-ID cousin of v5 UUIDs).
7 Common UUID Mistakes (and the Fix for Each)
- Storing UUIDs as
char(36). Four times the bytes of a 16-byte binary, slower joins, no parser benefit. Fix: use the nativeuuidtype (PostgreSQL) orBINARY(16)(MySQL); reserve the text form for serialization. - Using
Math.random()to build a v4. Non-cryptographic RNGs are predictable and have produced real-world collisions. Fix: usecrypto.getRandomValues(),crypto.randomUUID(), or your language's standard UUID library, which uses a CSPRNG by default. - Comparing UUIDs as strings without normalizing. A braced GUID and an unbraced UUID with the same bits compare unequal as strings. Fix: parse to bytes (or 32 lowercase hex chars) before comparing; never compare the raw text.
- Trusting a v1 timestamp for ordering across hosts. v1 is monotonic only within a single host with a single clock; cross-host ordering is dominated by clock skew. Fix: store a real
created_attimestamp column for ordering, and treat v1 ordering as a debugging hint. - Leaking MAC addresses with v1. The 48-bit node is often the real hardware MAC, which is a privacy leak and a fingerprint. Fix: use a random 48-bit node, or switch to v7 or ULID if you only needed time ordering.
- Using v3 (MD5) where the name is adversarial. MD5 has practical collision attacks; an attacker who can choose the name can forge a matching UUID. Fix: use v5 (SHA-1) for new systems, and switch to a v4 UUID in a registry if the name crosses a trust boundary.
- Building a custom UUID format. "We just drop a hyphen and add a prefix" loses the universal parser guarantee that makes UUIDs worth using. Fix: use one of the five standard versions, and if none fits, use ULID or v7 instead of inventing a format.
Every one of these is a workflow problem as much as a library problem, which is why the fix in every case is "use the standard," not "tune the parameters." The standards are small enough that reading them once removes most of the failure modes for good.
Frequently Asked Questions
Related Articles
Regex Testing Guide
The pillar for regular expressions: engine mental model, building blocks, and testing workflows that pair cleanly with deterministic UUIDs in validation rules.
Regex Tester Guide
Pattern-matching mechanics and use cases, including the regex that validates the 8-4-4-4-12 UUID layout.
Regex Tester Ultimate Guide
Advanced regex patterns, lookarounds, and backreferences for stricter UUID parsing and version-bit extraction.
Regex Tester Developer Guide
Developer workflows for testing and debugging regexes, with worked examples for UUID and identifier validation.
Markdown Best Practices
Writing markdown that stays readable, with structured data and code fences that show UUIDs in canonical form.
Markdown Platforms
Which markdown platforms support what, and how identifier-heavy technical docs render across them.
GitHub Markdown Guide
GitHub-flavored markdown specifics, including how UUIDs and other identifiers render in issues and READMEs.
HTML to Markdown Conversion Guide
Conversion workflows for moving technical documentation, including identifier-heavy reference docs, between formats.
Code Minification Best Practices
CSS and JS minification for performance gains, the content-hash cousin of deterministic v5 UUIDs.
Static Site Generators
Jekyll, Hugo, and Eleventy compared, including how each handles content-addressed UUIDs for build artifacts.
Developer Tools Guide
The wider developer-tool suite, including UUID generation, string manipulation, and conversion tools.
Data Conversion Tools: Professional Workflows
Conversion workflows for professionals, including the normalize-on-ingest discipline that prevents UUID format bugs.
Conclusion: Identifiers That Hold Up
UUIDs are a small, old, well-specified piece of technology that solves a problem most projects meet eventually: how to mint an identifier on one host that is safe to merge with identifiers minted on any other. The 128-bit layout, the five RFC 4122 versions, and the 122 random bits of v4 together cover almost every case, and the rare exceptions (time-ordered primary keys, short shareable IDs) have well-known answers in v7, ULID, and NanoID. The failure modes are not in the math; they are in the workflow: storing UUIDs as text, building them from weak RNGs, comparing them without normalizing, or inventing custom formats when a standard one would fit. Avoid those seven mistakes and the rest of the UUID machinery does what it was designed to do.
When you are ready to move from reading to generating, open the UUID generator, pair it with the random-string-generator for short tokens, and consult the documentation best practices guide for how to record the version choice in your schema. More guides on developer tooling and identifiers are catalogued on the NoCostTools blog.