Sub topic 2
Random IDs and UUID v4: no coordination needed
Assume you know basic Python, relational databases, indexes, binary numbers, and distributed systems.
Random IDs and UUID v4
A UUID is a 128-bit identifier usually written as 32 hexadecimal digits with hyphens. UUID version 4 (UUID v4) fills 122 bits with random data. The remaining bits identify the version and format.
Each node can generate a UUID v4 without contacting a central service. This keeps ID generation available during network failures.
import uuid
order_id = uuid.uuid4()
print(order_id)Random IDs provide excellent uniqueness in practice, but they are not mathematically impossible to duplicate. The application should still enforce a unique database constraint.
How likely is a collision?
A collision occurs when two generated IDs are equal. The birthday bound estimates the chance that any pair in a set collides:
def collision_probability(n, bits):
return n * n / (2 * 2 ** bits)
print(collision_probability(10**9, 122)) # about 9.4e-20This approximation is useful while the probability is small. The number of pairs grows roughly as n², so generating many IDs matters more than comparing one new ID with one existing ID.
Why random keys hurt B-tree indexes
A B-tree index stores keys in sorted pages. Random UUIDs insert throughout the tree instead of near the newest entries. This can cause page splits, more cache misses, and larger indexes than sequential keys.
Time-ordered IDs: UUID v7 and ULID
UUID v7 places a millisecond timestamp near the beginning of the identifier and random data after it. ULID uses a similar timestamp-plus-random structure. IDs from different milliseconds sort approximately by creation time, while IDs created in the same millisecond are not necessarily ordered.
Snowflake-style IDs
A Snowflake-style ID packs a timestamp, worker ID, and sequence number into one integer. The worker ID must be unique, and the generator must handle clock changes.
import time
def snowflake(worker_id, sequence, epoch_ms=1_700_000_000_000):
timestamp = time.time_ns() // 1_000_000 - epoch_ms
if not 0 <= worker_id < 1024 or not 0 <= sequence < 4096:
raise ValueError("field is out of range")
return (timestamp << 22) | (worker_id << 12) | sequence
print(snowflake(worker_id=7, sequence=0))A repeated worker ID or a clock moving backward can produce duplicates. Use controlled worker assignment and reject or delay generation when the clock is unsafe.
Exercise
Which scheme best fits many independent nodes that need IDs during network partitions and do not require sortable IDs?
Show answer
UUID v4, with a database uniqueness constraint to detect the extremely unlikely collision.