UUIDs Explained: v1, v4, v7 and When to Use Them
When to use v4 for randomness, v7 for time-ordered IDs, and how different UUID versions affect databases and distributed systems.
Universally Unique Identifiers (UUIDs) are 128-bit numbers used to identify information in computer systems. They are designed to be unique across space and time, without central coordination. But did you know there are multiple versions?
The Most Common: UUID v4
UUID v4 is completely random. It uses random numbers for almost all of its bits.
- Pros: Extremely low collision probability, easy to generate.
- Cons: Not sortable, and poor database-index locality because new values land at random positions (RFC 9562 says this of all non-time-ordered versions).
The New Standard: UUID v7
UUID v7 is a time-ordered value. It combines a timestamp with random data.
- Pros: Sortable by creation time, excellent for database primary keys (B-tree friendly).
- Cons: Reveals creation time (might be a privacy concern).
Legacy: UUID v1
UUID v1 combines a timestamp, a clock sequence and a node ID, which is traditionally the MAC address of the machine generating it.
- Pros: Time-based, so the creation time can be decoded from it.
- Cons: A MAC address in the node field is a privacy risk (RFC 9562 calls this out), it relies on the system clock, and the values do not sort by time as written.
Database Performance Impact
The choice of UUID version can significantly impact database performance, especially with large datasets:
- UUID v4 (Random): New records are inserted at random positions in a B-tree index, which gives poor locality: more pages are touched and more page splits occur than with sequential keys.
- UUID v7 (Time-ordered): New records land at or near the right-hand edge of the index, which keeps recently written pages hot and gives better locality.
- UUID v1 (Gregorian timestamp): The low timestamp bits come first, so values do not sort by creation time. UUID v6 reorders the same data to fix that.
RFC 9562 notes that time-ordered UUIDs benefit from greater database-index locality. How much that matters depends on your database, table size and write rate, so benchmark with your own data before treating it as a given.
Use Case Recommendations
Use UUID v7 When:
- You need sortable identifiers (e.g., for pagination or chronological ordering)
- Database performance is critical (large tables, high insert rates)
- You want to extract creation time from the ID itself
- You're building distributed systems where time-ordering matters
Use UUID v4 When:
- You want identifiers that carry no time or ordering information
- You don't need time-based sorting
- Privacy is a concern (you don't want to reveal creation time)
- You're working with smaller datasets where performance isn't critical
Avoid UUID v1 When:
- Privacy is important (MAC address leakage)
- You need deterministic IDs derived from a name (use v5 instead)
- You're building modern applications (v7 is the better time-ordered option)
UUID Format Breakdown
All UUIDs follow the same format: 32 hexadecimal digits displayed in 5 groups separated by hyphens:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
Where:
M = version (1, 4, 7, etc.)
N = variant (usually 8, 9, A, or B)The version number is embedded in the UUID itself, making it easy to identify which version was used to generate a particular UUID.
All the UUID Versions at a Glance
The current specification is RFC 9562, published in 2024, which replaces RFC 4122 and adds versions 6, 7 and 8. The versions differ in how the 128 bits are filled:
| Version | Built from | Sortable by time | Typical use |
|---|---|---|---|
| v1 | Gregorian timestamp, clock sequence, node (often a MAC address) | Not as written (low timestamp bits come first) | Legacy systems |
| v3 / v5 | MD5 (v3) or SHA-1 (v5) hash of a namespace plus a name | No | Stable IDs derived from a name or URL |
| v4 | 122 random bits | No | General-purpose random IDs |
| v6 | v1 timestamp with the bytes reordered | Yes | Upgrading existing v1 data |
| v7 | 48-bit Unix millisecond timestamp plus random bits | Yes | Database primary keys |
| v8 | Custom, vendor-defined layout | Depends | Experimental or application-specific |
Inside a UUID v7
A v7 UUID starts with a 48-bit big-endian Unix timestamp in milliseconds. After that come the 4-bit version, 12 random bits, the 2-bit variant, and 62 more random bits. Because the timestamp occupies the most significant bytes, comparing two v7 values as bytes or as lowercase hex strings orders them by creation time.
01941f29-7c00-7xxx-8xxx-xxxxxxxxxxxx
|-- 48 bit ms timestamp --| ^ ^
| variant bits (10)
version = 7Here is a minimal Node.js generator and a function that reads the timestamp back out of an ID. The first line uses a fixed timestamp so the output is reproducible. The random tail will differ each run.
import { randomBytes } from "node:crypto";
function uuidv7(ms = Date.now()) {
const b = randomBytes(16);
b.writeUIntBE(ms, 0, 6); // 48-bit timestamp
b[6] = (b[6] & 0x0f) | 0x70; // version 7
b[8] = (b[8] & 0x3f) | 0x80; // variant 10xx
const h = b.toString("hex");
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
}
function timeOf(id) {
return new Date(parseInt(id.replace(/-/g, "").slice(0, 12), 16));
}
const id = uuidv7(1735689600000);
id.slice(0, 13); // "01941f29-7c00"
timeOf(id).toISOString(); // "2025-01-01T00:00:00.000Z"This sketch is for understanding the layout. IDs created in the same millisecond are ordered randomly relative to each other, whereas RFC 9562 describes optional counter techniques to keep them monotonic. For production, use a maintained library. Our UUID Generator follows the RFC 9562 layouts and draws its random bits from crypto.getRandomValues, but for production IDs use a maintained library in your own stack.
Name-Based UUIDs: v3 and v5
Versions 3 and 5 are deterministic. They hash a namespace UUID together with a name, so the same inputs always produce the same ID. That is useful when you need a stable identifier for something that already has a natural key, such as a URL or a domain, without keeping a lookup table. Version 5 uses SHA-1 and is preferred over v3, which uses MD5. Neither should be treated as a security feature, since the inputs are guessable. See hashing algorithms explained for why those hash functions are no longer trusted for security.
import { createHash } from "node:crypto";
const NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
function uuidv5(name, namespace) {
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
const h = createHash("sha1").update(ns).update(name).digest().subarray(0, 16);
h[6] = (h[6] & 0x0f) | 0x50;
h[8] = (h[8] & 0x3f) | 0x80;
const x = h.toString("hex");
return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;
}
uuidv5("python.org", NAMESPACE_DNS);
// "886313e1-3b8a-5372-9b90-0c9aee199e5d"The value above matches the well-known v5 result for python.org in the DNS namespace, which is a handy way to check any implementation.
Special Values and Other Versions
- Nil UUID:
00000000-0000-0000-0000-000000000000, all zeros. It is a placeholder meaning "no value". It has no valid version digit, so strict version-checking patterns reject it. - Max UUID:
ffffffff-ffff-ffff-ffff-ffffffffffff, all ones, defined in RFC 9562 as the counterpart to the nil value. - UUID v6: the same data as v1 with the timestamp bytes reordered so values sort by time. It exists mainly to ease migration of v1 systems, and new designs should prefer v7.
- UUID v8: reserved for custom layouts. Only the version and variant bits are fixed, so two systems' v8 values are not interchangeable.
How Likely Is a Collision?
A v4 UUID has 122 random bits, because 6 of the 128 are fixed for version and variant. Using the birthday approximation, you would need to generate roughly 2.7 quintillion (2.7 x 1018) UUIDs before the chance of any collision reaches 50 percent. At realistic volumes the practical risk is dominated by bugs, not mathematics: a weak random number generator, a cloned virtual machine image that reuses a seed, or copying an ID by hand. Always generate IDs with a cryptographically secure source, such as crypto.randomUUID() in browsers and Node.js, and keep a unique constraint on the column as a safety net.
Storage and Practical Pitfalls
- Store as binary where you can. A UUID is 16 bytes, but its text form is 36 characters. A native
uuidtype (PostgreSQL has one) or aBINARY(16)column more than halves the key size, which matters most in engines with a clustered primary key, such as MySQL InnoDB, where every secondary index repeats the primary key. - Be consistent about case. Hex digits are case-insensitive, but string comparison is not. Normalise to lowercase before comparing or storing as text.
- A UUID is an identifier, not a secret. RFC 9562 says implementations should not assume UUIDs are hard to guess and must not use them as security capabilities. Authorize every request on the server, and use a proper token for secrets, such as the ones covered in the JWT decoder guide.
- v7 reveals when a record was created. If creation time is sensitive, for example for user accounts, expose a separate public ID in the API, or use v4 for the externally visible one.
- Text sorting only works for v7 and v6. Sorting v4 IDs gives an arbitrary order, so pagination needs a separate created-at column.
- Validate the shape. This pattern accepts versions 1 to 8 with the RFC variant, and rejects the nil UUID:
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iYou can try it in the Regex Tester, and the regex cheat sheet explains the pieces. To see a version for yourself, read the first digit of the third group: 4 in f47ac10b-58cc-4372-a567-0e02b2c3d479, and 7 in the v7 example above.
Migrating from v4 to v7
You do not need to rewrite existing keys. Both versions are valid 128-bit UUIDs in the same column type, so new rows can start using v7 while old rows keep their v4 values. Index locality improves for new inserts only, and the old data stays where it is. If you want to sort by creation time across the whole table, keep a real timestamp column. Do not rely on mixed v4 and v7 values to order correctly.
Which Should You Choose?
For most new applications that use UUIDs as database keys, UUID v7 is the better default: RFC 9562 says implementations should use it instead of v1 or v6 where possible. If you just need an opaque random ID and don't care about sorting, UUID v4 remains a fine choice.
The decision often comes down to your specific requirements:
- Write-heavy tables with large indexes: Choose v7 for better index locality
- Security tokens: Do not use a UUID at all. Generate a random token from a cryptographically secure source
- Time-based queries: Choose v7 to enable efficient time-range filtering
- Privacy-sensitive applications: Choose v4 to avoid revealing creation time
Need to generate one quickly? Use our UUID Generator to create v1, v4, and v7 UUIDs instantly. You can generate single UUIDs or batch generate multiple IDs for testing and development.
Frequently Asked Questions
What is the difference between UUID v4 and v7?
v4 is almost entirely random, while v7 begins with a millisecond timestamp followed by random bits. That makes v7 sortable by creation time and friendlier to database indexes, at the cost of exposing roughly when the ID was created.
Are UUIDs really unique?
Not guaranteed, but collisions are astronomically unlikely when they are generated with a secure random source. Add a unique database constraint so the rare failure is caught instead of silently overwriting data.
Is UUID the same as GUID?
Yes in practice. GUID is Microsoft's name for the same 128-bit format, though some Microsoft tools display the value in uppercase or with braces.
Should I use a UUID or an auto-increment ID?
Auto-increment integers are smaller and fast, but they require a central counter and reveal how many rows exist. UUIDs can be generated anywhere, such as in a client or across services, without coordination, and v7 recovers much of the insert-locality advantage.
Can I get the creation time from a UUID?
From v7, yes: the first 48 bits are the Unix timestamp in milliseconds, as the timeOf function above shows. From v1 you can also decode a timestamp, but v4 contains no time information at all.
Written by Kashyap Thakar
Spotted a mistake? Let me know
Try these tools
Use these tools alongside this guide