What is a UUID?
A UUID (Universally Unique Identifier) is a 128-bit value written as 32 hexadecimal digits in five groups, for example 550e8400-e29b-41d4-a716-446655440000. Microsoft calls the same format a GUID. UUIDs can be created anywhere, without a central server, with a negligible chance of two ever colliding. The format is defined by RFC 9562 (2024), which replaced RFC 4122.
UUID v4 vs UUID v7: which should you use?
| Version 4 | Version 7 | |
|---|---|---|
| Contents | 122 random bits | 48-bit millisecond timestamp + 74 random bits |
| Sort order | Random | By creation time |
| Database primary keys | Works, but random inserts fragment B-tree indexes | Inserts append to the end of the index, like an auto-increment |
| Reveals creation time | No | Yes, to the millisecond |
| Best for | Public IDs, tokens of low sensitivity, test data | Primary keys, event and log IDs |
Rule of thumb: use v7 for database keys and anything you sort or paginate, and v4 when the creation time should not be visible. PostgreSQL 18 ships a native uuidv7() function.
Can two UUIDs collide?
With 122 random bits, you would need to generate about 2.7 × 1018 version 4 UUIDs for a 50% chance of a single duplicate. That is a billion UUIDs per second for about 86 years. In practice, collisions come from broken random number generators, not from the math.
Are UUIDs safe to use as secrets?
A v4 UUID generated with a cryptographically secure generator, as here, is unpredictable, but it is a weak choice for API keys or password-reset tokens: it carries only 122 bits, its format announces what it is, and v7 and older versions are partly predictable. For secrets, use the random token generator with 128 bits or more.
Generating UUIDs in code
- JavaScript (browser and Node.js 19+):
crypto.randomUUID()(v4) - Python:
import uuid; uuid.uuid4(), anduuid.uuid7()from Python 3.14 - PostgreSQL:
gen_random_uuid()(v4),uuidv7()(v7, PostgreSQL 18+) - Java:
UUID.randomUUID()(v4) - Go:
uuid.New()anduuid.NewV7()fromgithub.com/google/uuid