Sub topic 5
Random IDs and UUID v4: no coordination needed
This chapter assumes you know what a primary key is and how to read a 128-bit value in hexadecimal. It also assumes you can run short Python scripts. Earlier chapters covered why counters need coordination. Here you will see how random IDs remove that need, what a UUID v4 contains, and which mistakes make random IDs collide.
The idea: let chance do the coordination
A central counter guarantees uniqueness by making every node ask one authority for the next number. Random IDs take the opposite approach. Each node draws a number from a space so large that two nodes almost never draw the same one. No node asks anyone for anything.
This gives you three properties at once:
- No coordination. A node can create an ID while offline, in a mobile app, or in a different data center.
- No single point of failure. There is no ticket server or sequence to keep available.
- Creation before insertion. A client can generate an ID, use it to link related rows, and send everything in one request. It does not need a database round trip to learn the key.
You pay for this with size (128 bits instead of 64), no ordering, and a guarantee that is probabilistic instead of absolute.
What a UUID v4 contains
A UUID (universally unique identifier) is a standardized 128-bit value. It is defined in RFC 9562, which replaced RFC 4122. Version 4 is the random version. Of its 128 bits, 6 are fixed and 122 are random:
- 4 bits hold the version, the value 4.
- 2 bits hold the variant, the pattern
10. This marks the layout as the RFC one. - The remaining 122 bits come from a random source.
The canonical text form is 32 hexadecimal digits in five groups, 8-4-4-4-12, separated by hyphens. The fixed bits show up in predictable places.
In the string f47ac10b-58cc-4372-a567-0e02b2c3d479, the first digit of the third group is 4 (the version). The first digit of the fourth group is a. For a v4 UUID, that digit is always 8, 9, a, or b, which are the four hex digits whose top two bits are 10.
You can check this in Python:
import uuid
u = uuid.uuid4()
print(u)
print(u.version) # 4
print(u.variant) # specified in RFC 4122
print(u.hex[12]) # always '4'
print(u.hex[16] in "89ab") # always TrueThe index 12 is the first digit of the third group (8 + 4 digits come before it). Index 16 is the first digit of the fourth group.
Building one by hand
Library code hides how little work this is. The following function does what uuid.uuid4() does. It takes 16 bytes from the operating system, then forces the version and variant bits.
import os
import uuid
def uuid4_manual():
value = int.from_bytes(os.urandom(16), "big")
# Version field: bits 79-76 set to 0b0100.
value &= ~(0xF << 76)
value |= 4 << 76
# Variant field: bits 63-62 set to 0b10.
value &= ~(0x3 << 62)
value |= 0b10 << 62
return uuid.UUID(int=value)
u = uuid4_manual()
print(u, u.version)The bit positions are counted from the least significant bit. The same positions appear in the UUID v7 example in a later chapter, because v4 and v7 share the same version and variant fields.
The randomness source matters more than the bit twiddling. os.urandom reads from the operating system's cryptographically secure generator (CSPRNG), which is seeded from hardware and system events. That is the correct source for IDs.
Storage and format
A UUID is 16 bytes of information, but how you store it changes the cost a lot.
| Representation | Typical size | Notes |
|---|---|---|
| Native `uuid` type (PostgreSQL) | 16 bytes | Compact, validated, compares as bytes. |
| `BINARY(16)` (MySQL) | 16 bytes | Needs conversion functions in queries. |
| `CHAR(36)` text with hyphens | 36 bytes or more | More than twice the size, plus slower comparisons. |
| `BIGINT` auto-increment, for comparison | 8 bytes | Half the size of a binary UUID. |
Size has a knock-on effect. In a database where secondary indexes store the primary key, such as MySQL's InnoDB, every secondary index entry carries a copy of the key. A 36-byte text key makes every index entry larger than an 8-byte integer key would, and fewer entries fit on each page.
Text form adds a smaller problem: the same UUID can be written in upper or lower case, with or without hyphens, or with braces. Normalize to lowercase canonical form at the system boundary, or store the binary type so the question never comes up.
Common errors
Most real-world duplicate-ID incidents with random IDs come from the randomness source, not from the mathematics.
Using a non-cryptographic or identically seeded generator
General-purpose PRNGs such as Python's random module are deterministic. Two generators with the same seed produce the same sequence, and so the same IDs:
import random
import uuid
def weak_id(rng):
return uuid.UUID(int=rng.getrandbits(128), version=4)
a = random.Random(42)
b = random.Random(42)
print(weak_id(a) == weak_id(b)) # True: two "independent" nodes collideThis shows up when a program seeds from a timestamp with one-second resolution, when it hard-codes a seed in a test and ships it, or when many processes start at the same moment. Use uuid.uuid4(), os.urandom, or secrets for IDs. Seed-based generators are for simulations that must be repeatable.
Duplicated generator state
Some PRNG libraries keep their state in process memory. Two situations then produce identical streams:
- Forking. A process forks after the generator was initialized, and parent and child continue from the same state. Check whether your language runtime reseeds on fork. Do not assume it does.
- Cloned virtual machines. A VM snapshot is restored on several hosts. If the generator's state is part of the snapshot, every clone starts from the same point. Modern OS kernels have mechanisms to refresh entropy after a restore, but older images and user-space generators may not.
The defense is to draw from the operating system on each call, or to use a library documented as fork-safe.
Truncating the UUID
It is tempting to shorten a UUID to eight characters for a URL. That keeps 32 bits of randomness. With 32 bits, you expect a collision after roughly tens of thousands of IDs, not billions. If you need a shorter form, encode the full 128 bits with a denser alphabet such as base32 or base64url instead of cutting bits.
Treating uniqueness as proven
A random scheme gives overwhelming probability, not a proof. Keep the UNIQUE or PRIMARY KEY constraint on the column. If you create IDs on the client and the server stores them, have the server reject a duplicate insert and let the client retry with a new ID. The chance of that path running is tiny, but code that handles it costs a few lines.
Assuming the ID is ordered or meaningful
A v4 UUID carries no time and no node information. Sorting by it does not give creation order, and you cannot extract a timestamp from it. If you need a "newest first" listing, add a created_at column. If you want the ID itself to sort by time, that is the subject of the time-ordered chapter.
What the collision risk looks like
The next chapter derives the numbers. For now, keep one figure in mind. With 122 random bits, generating a billion UUIDs gives a probability of any collision on the order of 10^-19. That is far smaller than the chance of a hardware fault corrupting your data. Collisions from the mathematics are not the practical risk. The practical risks are the broken randomness sources and truncation listed above.
When v4 is a good fit
Choose UUID v4 when:
- IDs are created in many places with no shared service, including clients and offline devices.
- You do not need ordering from the ID itself.
- The table is small enough, or the access pattern read-heavy enough, that insert locality in the primary-key index does not matter. The index chapter explains that cost.
- You want IDs that do not reveal how many records exist or when they were created.
Consider something else when the table takes heavy write traffic and its primary key index must stay compact, or when you want to sort by ID.
Exercise
A team writes uuid.UUID(int=random.Random(int(time.time())).getrandbits(128), version=4) in a service that runs on 50 containers started by the same deployment at the same moment. Name two separate problems with this code.
Show answer
First, random.Random is a deterministic, non-cryptographic generator, so it is the wrong kind of source for IDs, and its output is predictable by anyone who guesses the seed. Second, the seed int(time.time()) has one-second resolution. Containers started in the same second get the same seed and produce the same ID sequence, so IDs collide across nodes. The fix is uuid.uuid4() or os.urandom(16), which draw from the operating system's CSPRNG.
Exercise
Look at the UUID 9b2d6c1e-4f3a-4c8b-d1a0-7e5f2a9c3b44. Is it a valid v4 UUID in the RFC layout? Explain how you checked.
Show answer
No. The third group starts with 4, so the version is correct. The fourth group starts with d, which is 1101 in binary. A v4 UUID must have the variant bits 10, so the first digit of the fourth group must be 8, 9, a, or b. The d means the variant bits are 11, so this value is not in the RFC layout.