Sub topic 1
Why unique IDs are hard when nodes cannot coordinate
Every record in a system needs a name: an order, a user, a message, a log line. On one machine with one database, naming is easy. The database hands out 1, 2, 3, and so on. The problem changes once several machines create records at the same time and cannot cheaply ask each other what is already taken.
This chapter explains why that is hard, what goes wrong with the obvious fixes, and what questions the rest of the tutorial uses to compare solutions.
Prerequisites
This chapter assumes you have:
- Basic programming skills in Python or a similar language.
- Familiarity with relational databases, primary keys, and indexes.
- A general idea of what a distributed system is: multiple nodes, network calls, and partial failure.
- Basic comfort with binary numbers. Later chapters use bit shifting, but this one does not.
What "unique" means
An ID is unique if no two different things ever share it. The words "ever" and "different things" matter.
- Across space: two nodes in different data centers must not issue the same ID.
- Across time: a node that crashes and restarts must not reissue an ID it used before.
- Across failures: a node that was cut off from the network, but kept running, must still not clash with the others.
A uniqueness bug is also quiet. Nothing fails when two nodes issue the same ID. The failure shows up later: a duplicate-key error on insert, or worse, two customers' data merged under one key.
The core difficulty
Uniqueness is a global property. To be sure an ID is unused, you must know about every ID that has been used. In a single process, that knowledge is a variable. Across machines, it is shared state, and shared state needs communication.
Communication between nodes has three costs:
- Latency. A network round trip takes at least hundreds of microseconds inside a data center and tens or hundreds of milliseconds across regions. Generating an ID should take nanoseconds.
- Availability. If a node must ask another node before issuing an ID, it cannot issue IDs while that node is unreachable.
- Throughput. If every node asks the same place, that place becomes the limit on the whole system's write rate.
So the real question is how to get uniqueness while communicating as little as possible. Each scheme in this tutorial answers it differently.
The obvious fix that fails: a counter per node
The simplest idea is that each node keeps its own counter. No network calls, no waiting. The following code simulates two nodes doing this.
class Node:
def __init__(self, name):
self.name = name
self.counter = 0
def next_id(self):
self.counter += 1
return self.counter
a = Node("a")
b = Node("b")
ids_a = [a.next_id() for _ in range(3)]
ids_b = [b.next_id() for _ in range(3)]
print("node a:", ids_a)
print("node b:", ids_b)
print("collisions:", sorted(set(ids_a) & set(ids_b)))Both nodes start at 0 and count the same way, so they produce the same sequence: [1, 2, 3] from each, and the collision set is [1, 2, 3]. Each node is internally consistent, but nothing connects them.
A second failure hides in the same design. The counter lives in memory. After a restart, counter is back to 0 and the node reissues IDs it already used. Saving the counter to disk helps, but only if the write is durable before the ID is handed out, and that adds a disk write to every ID.
The sequence diagram below shows the same failure at the database.
Another obvious fix that fails: the clock
If counters collide because nodes start at the same point, use something that already differs by moment: the current time. Two events at different times get different IDs.
def timestamp_id(clock_ms):
# clock_ms is a function returning the current time in milliseconds.
return clock_ms()
# Simulate two nodes whose clocks read the same millisecond.
same_instant = lambda: 1_700_000_000_000
id_from_node_1 = timestamp_id(same_instant)
id_from_node_2 = timestamp_id(same_instant)
print(id_from_node_1, id_from_node_2)
print("duplicate:", id_from_node_1 == id_from_node_2)This fails for two reasons.
- Resolution. A busy node can create many records in one millisecond. Even on a single node, a timestamp alone repeats.
- Simultaneity. Two nodes can create records in the same millisecond. A timestamp tells you when, not who.
A third problem is that clocks are not reliable. Nodes disagree about the time by milliseconds or more, and a clock can jump backwards when it is corrected. Chapter "Clock skew and backwards clocks" returns to this. For now, remember that time is a useful ingredient but not a complete answer.
The fix that works but costs: a central authority
If independent nodes collide, make them share. One database sequence, or one service, issues all IDs. Since a single place decides, uniqueness is easy to guarantee.
The cost is the coordination described earlier:
- Every ID needs a network round trip to the authority.
- If the authority is down or unreachable, nobody can create records.
- The authority's capacity limits the whole system.
- Replicating the authority for availability brings back the original problem. Two replicas that both accept requests during a network partition can issue the same number.
This is a case of the trade-off distributed systems keep returning to. During a network partition, you must choose between availability (nodes keep issuing IDs) and strict global coordination (nodes refuse to issue IDs they cannot verify). A scheme that needs no coordination chooses availability, and it must obtain uniqueness some other way.
Three ways to get uniqueness without asking
Without asking, a node can only rely on information it already has. There are three sources, and every scheme in this tutorial combines them.
| Source of uniqueness | Idea | Example scheme |
|---|---|---|
| Partitioned space | Give each node its own slice of the ID space, so slices never overlap | Worker ID bits, pre-allocated blocks |
| Randomness | Pick from a space so large that repeats are vanishingly unlikely | UUID v4 |
| Time | Use the clock so that different moments give different IDs | UUID v7, Snowflake |
Each source has a weakness:
- Partitioned space needs someone to assign the slices, which is a small amount of coordination done once instead of per ID.
- Randomness gives probabilistic uniqueness, not a guarantee. The probability is tiny but not zero.
- Time depends on clocks behaving.
Real schemes mix them. A Snowflake-style ID, for example, combines time, a worker slice, and a per-millisecond counter.
Properties to judge a scheme by
"Unique" is rarely the only requirement. Here are the questions the rest of the tutorial uses to compare schemes. The next chapter treats them in detail.
- Uniqueness guarantee: certain, or only probable?
- Ordering: do IDs sort by creation time, or in no useful order?
- Size: 64 bits, 128 bits, or a long string? Size affects storage and index cost.
- Coordination: none, once at startup, or on every ID?
- Predictability: can an outsider guess other valid IDs from one they have seen?
No scheme wins on every property. A 128-bit random ID needs no coordination but has no useful order and is large. A central counter is small and ordered but needs coordination on every ID.
Common mistakes
- Treating "unlikely" as "impossible" without checking the numbers. Random IDs are fine when the space is large enough. A later chapter shows how to calculate that, and the answer depends on how many IDs you create.
- Forgetting restarts. An in-memory counter that resets is a duplicate generator.
- Assuming clocks agree. Two nodes' clocks differ, and one node's clock can move backwards.
- Relying on the database to catch duplicates. A unique constraint turns a silent error into a loud one, but it does not fix it. The rejected write must then be retried, and a client may never learn that its request failed.
- Assuming consecutive means gapless. Schemes that preallocate or cache IDs can leave gaps after crashes. Treat IDs as labels, not as a count of records.
Where this goes next
The next chapter makes the properties above precise and shows how they conflict. After that, the tutorial walks through the schemes in order: central counters and block allocation, random IDs and the collision math, the cost of random keys in B-tree indexes, time-ordered IDs, Snowflake-style IDs, and the failure modes of worker assignment and clocks. It ends with predictability and a guide to choosing.
Exercise
A team runs three application servers. Each keeps an in-memory counter starting at 0 and uses the counter value as the primary key for new orders. Give two distinct ways this design can produce duplicate IDs, and say which of the three sources of uniqueness (partitioned space, randomness, time) the team could add to fix each one.
Show answer
First, the servers all count from 0 independently, so server 1 and server 2 both issue ID 1. Fix: partition the ID space, for example by including a per-server number in the ID, so each server's IDs come from a separate slice. Second, a server that restarts loses its in-memory counter and reissues IDs it already used. Fix: include time in the ID, so that IDs issued after the restart carry a later timestamp, or persist the counter durably before handing out IDs. Randomness would also fix both, because a random ID does not depend on any counter, but it gives only a probabilistic guarantee.
Exercise
Why does a single central ID service guarantee uniqueness, and what two costs does it add compared with generating IDs locally?
Show answer
One authority decides every ID, so no two requests can be given the same value. The costs are a network round trip on every ID (latency) and a dependency on the service being reachable (availability), and its capacity also caps the whole system's write throughput.