Sub topic 5
Random IDs and UUID v4: no coordination needed
This chapter assumes you know what a primary key is, can read basic Python, and understand that nodes in a distributed system may fail or lose contact with each other. You should also be comfortable with binary numbers and bit shifting.
The idea: let every node pick at random
A central counter needs every node to ask one place for the next number. Random IDs drop that step. Each node draws a large number from a random source and uses it as the ID. No node talks to any other node, so there is no shared service to fail or to become a bottleneck.
This works because the space of possible IDs is huge. If you pick two numbers at random from a range of 2^122 values, they almost never match. You give up a hard guarantee of uniqueness and accept a probability so small that it can be ignored in practice. The next chapter puts numbers on that probability.
What a UUID v4 contains
A UUID (universally unique identifier) is a 128-bit value, usually written as 32 hexadecimal digits in five groups:
f47ac10b-58cc-4372-a567-0e02b2c3d479Version 4 fills most of those bits with random data. Six bits are reserved for metadata:
- The 4-bit version field is
0100(the digit4). In the example it is the first digit of the third group. - The 2-bit variant field is
10. It makes the first digit of the fourth group one of8,9,a, orb. - The other 122 bits are random.
| Field | Bits | Value |
|---|---|---|
| Random data | 122 | From a random source |
| Version | 4 | `0100` |
| Variant | 2 | `10` |
You can check this in Python:
import uuid
u = uuid.uuid4()
print(u)
print(u.version) # 4
print(u.variant) # RFC_4122
print(u.int.bit_length() <= 128) # TrueWhere the randomness comes from
The guarantee is only as good as the random source. Python's uuid.uuid4() reads from the operating system's cryptographically secure generator (os.urandom). That source is seeded from hardware and system events.
Two common mistakes break this:
- A weak generator. Building IDs with
random.getrandbitsor a language's default pseudo-random generator can produce predictable or repeated values, especially when seeded with the clock. - Copied state. If you fork a process or clone a virtual machine image and the generator state is copied with it, two nodes can produce identical sequences. Standard OS-backed generators are designed to handle forking, but custom generators often are not.
Use your platform's UUID library or its secure random API, and avoid writing your own.
import os
import uuid
# Equivalent to uuid.uuid4(): 128 random bits with version and variant set.
raw = int.from_bytes(os.urandom(16), "big")
raw &= ~(0xF << 76)
raw |= 4 << 76
raw &= ~(0x3 << 62)
raw |= 0b10 << 62
print(uuid.UUID(int=raw))How it compares to the properties you care about
Judged against the requirements from earlier in the tutorial:
| Property | UUID v4 |
|---|---|
| Coordination | None |
| Availability | Every node can issue IDs offline |
| Uniqueness | Probabilistic, with negligible collision risk |
| Size | 128 bits (16 bytes binary, 36 characters as text) |
| Ordering | None. IDs carry no creation order |
| Predictability | Hard to guess if the source is secure |
Costs to expect
The 128-bit size is twice that of a 64-bit integer key. Every secondary index that stores the primary key repeats those extra bytes. Text storage is worse: a 36-character string takes more than twice the space of the 16-byte binary form, so use a native uuid or BINARY(16) column where your database offers one.
The lack of order has a bigger cost. Because each new ID lands at a random position, inserts scatter across a B-tree index instead of appending at the end. A later chapter covers this, and it is the main reason time-ordered IDs exist.
You also cannot sort by ID to get creation order. If you need that, store a separate timestamp column.
Exercise
A team builds IDs with Python's random.getrandbits(122), seeded at startup with the current time in seconds. Two services start in the same second. What goes wrong, and what should they use instead?
Show answer
Both services seed the generator with the same value, so they produce the same sequence of "random" IDs and collide almost immediately. They should use uuid.uuid4() or os.urandom, which draw from the operating system's secure random source and do not depend on a shared, guessable seed.
Exercise
A UUID starts its third group with the digit 7. Can it be a UUID v4? Which bits tell you?
Show answer
No. The first digit of the third group is the 4-bit version field, and a v4 UUID has 4 there. A 7 indicates version 7. The variant bits in the fourth group (8, 9, a, or b) are the same for both versions.