UUID Generator: How It Works
A UUID is a 128-bit identifier designed so that independent systems can generate IDs simultaneously without coordinating and still never collide. This generator produces them; this page explains which version to use, because the choice has real consequences for database performance.
The format
Thirty-two hexadecimal digits in five hyphenated groups: 8-4-4-4-12.
f47ac10b-58cc-4372-a567-0e02b2c3d479
^ ^
version variantThe first digit of the third group gives the version; the first digit of the fourth encodes the variant.
The versions that matter
| Version | Based on | Use when |
|---|---|---|
| v1 | Timestamp + MAC address | Rarely — it leaks hardware identity and creation time |
| v3 / v5 | Hash of a namespace and name | The same input must always produce the same ID |
| v4 | Random | The general default |
| v7 | Unix timestamp + random | Database primary keys — sorts chronologically |
v4 is the right answer for most purposes. v7 is the better answer for database keys, for reasons below. v5 is for deterministic IDs — the same URL always hashing to the same UUID.
The collision question
A v4 UUID has 122 random bits, giving roughly 5.3 × 1036 possibilities. To reach a 50% chance of a single collision you would need to generate about 2.7 × 1018 of them. Generating a billion per second, that takes roughly 85 years. Collisions are not a practical concern, provided the generator uses a cryptographically secure random source — which is the actual risk, not the mathematics.
Why v4 hurts database performance
This is the practical point most teams learn late. A v4 UUID is random, so inserting rows with UUID primary keys writes to random positions in a B-tree index. That fragments the index, causes page splits, and destroys the sequential-write pattern databases are optimised for. On large tables the effect is substantial.
v7 solves it by placing a millisecond timestamp in the high bits, so newly generated values sort roughly in creation order. New rows append to the end of the index like an auto-increment integer while retaining the distributed-generation benefit. If you are choosing a UUID primary key today, v7 is usually the better default.
UUID or integer?
| UUID | Auto-increment integer | |
|---|---|---|
| Generate before insert | Yes | No |
| Safe to expose publicly | Yes — not guessable | No — reveals volume and allows enumeration |
| Merge across databases | Trivial | Requires remapping |
| Storage | 16 bytes binary, 36 as text | 4–8 bytes |
| Index performance | Poor for v4, good for v7 | Excellent |
Store UUIDs in a native binary or UUID column type where the database offers one. Storing them as 36-character strings roughly doubles the space and slows every comparison.