Sub topic 2
What to Ask of an ID: Uniqueness, Ordering, Size, and Coordination
This chapter assumes you can read basic Python, know what a primary key and a B-tree index are, can follow bit shifting, and have a rough idea of a distributed system (several nodes, network calls, partial failure). It does not cover specific schemes in depth. Later chapters do that. Here you build the checklist that you will use to judge every scheme.
Why write requirements before picking a scheme
Teams often pick an ID format first, by habit (AUTO_INCREMENT, "just use a UUID") or by copying a famous design (Snowflake). The ID then ends up in primary keys, URLs, logs, message queues, and other services' databases. Changing it later means migrating every one of those places.
The better order is to decide which properties you need, and then choose the cheapest scheme that provides them. Each property has a cost, and some of them conflict. Five properties cover most decisions: uniqueness, ordering, size, coordination, and predictability.
Uniqueness
Uniqueness means no two entities ever receive the same ID. Ask three sub-questions.
What is the scope? An ID can be unique within one table, within one tenant, across all your services, or across all systems in the world. A wider scope costs more. A per-table counter is cheap. A globally unique ID needs either a large random space or a structure that separates generators from each other, such as a worker field.
What kind of guarantee do you get? There are two kinds:
- A deterministic guarantee holds by construction. A single counter, or a Snowflake ID with distinct worker IDs, cannot repeat unless something is misconfigured.
- A probabilistic guarantee holds with overwhelming likelihood. Random IDs can collide, but with enough bits the chance is far below the rate of hardware faults.
Neither kind is free of failure. Deterministic schemes fail when an operational assumption breaks, for example two workers get the same worker ID. Probabilistic schemes fail when the randomness source is weak, for example a virtual machine clone that reuses a seeded random generator.
Who enforces it? A unique index on the ID column is your last line of defence. A duplicate then becomes a rejected insert instead of silent corruption. It also means a collision shows up as an error you can retry.
Ordering
"Sortable" has several meanings. Be exact about which one you need.
| Level | Meaning | Typical use |
|---|---|---|
| None | IDs carry no order | Opaque identifiers, public tokens |
| Roughly time-ordered | IDs created at clearly different times sort in creation order, but close IDs may swap | Insert locality, "newest first" pages |
| Monotonic per generator | Each node's IDs strictly increase | Cursor pagination within one source |
| Global total order | Every ID is greater than all earlier IDs, anywhere | Rarely needed, needs strong coordination |
Roughly time-ordered IDs are often called k-sortable: an ID is at most k positions away from its true sorted place. They are cheap because each node only reads its own clock.
A global order that matches the real order of events is expensive. It needs one sequencer or a consensus protocol, and every ID then costs a round trip. Most systems that think they need it actually need a weaker property, such as ordering within one user's data.
IDs from different nodes also order by clock readings, not by real time. If one node's clock runs behind, its later events can get smaller IDs.
# Two nodes stamp events with their own clocks.
# Node B's clock is 50 ms behind, so its later event gets an earlier stamp.
events = [
("A", 1000, 1000), # (node, real_ms, stamped_ms)
("B", 1010, 1010 - 50),
]
by_id = sorted(events, key=lambda e: e[2])
by_real = sorted(events, key=lambda e: e[1])
print([e[0] for e in by_id]) # ['B', 'A']
print([e[0] for e in by_real]) # ['A', 'B']Sorting by ID puts B first even though A acted first. Treat time-ordered IDs as a good hint for storage and display, not as proof of causality. If you need to know which event happened first, use a version number, a logical clock, or a consensus log.
Size and format
An ID is stored in every row that has it, in every index that includes it, and in every foreign key that references it. Secondary indexes in many engines, InnoDB for example, also store the primary key in each entry. A 16-byte key instead of an 8-byte key therefore costs more than 8 bytes per row. The cost repeats in each table and index, and it shrinks the number of entries that fit in a memory page.
Common sizes:
- 64 bits (8 bytes) fits a native
BIGINTorlong. It is compact, but it leaves little room for random bits. - 128 bits (16 bytes) fits a UUID. It leaves room for a timestamp and many random bits, so generators need no coordination.
- Text forms are larger. A UUID in canonical hex is 36 characters, and a ULID in Crockford Base32 is 26 characters. Storing text instead of 16 raw bytes more than doubles the space.
Size also has a client-side limit. JavaScript numbers are 64-bit floats, so integers are exact only up to 2^53 − 1. A 64-bit ID such as a Snowflake ID loses its low digits if a browser parses it as a number. Many APIs return such IDs as strings for this reason.
A useful exercise is to calculate how many bits a plain counter needs for your expected volume:
import math
JS_SAFE_BITS = 53
def bits_needed(ids_per_second, years):
total = ids_per_second * 60 * 60 * 24 * 365 * years
return math.ceil(math.log2(total))
for rate in (1_000, 100_000, 10_000_000):
bits = bits_needed(rate, 10)
print(rate, bits, bits <= JS_SAFE_BITS)This prints 39, 45, and 52 bits, all within the JavaScript limit. That is the cost of a bare counter. Every field you add for coordination-free generation, such as worker bits and a sequence, comes out of the same 64-bit budget. That is why layouts like Snowflake spend 41 bits on time (about 69.7 years of milliseconds) and leave only 22 bits for everything else.
Coordination
Coordination is how much generators must talk to each other, or to a shared service, before they can issue an ID. It is the property that most strongly affects availability and latency, and it comes in four levels:
- Per ID. Every ID needs a call to a central service, such as a database sequence. The ID is simple and gap-free, but the service is a bottleneck and a single point of failure.
- Per block. A generator reserves a range of IDs and hands them out locally. Calls are rare, but a crash wastes the unused part of a range.
- At startup. A generator obtains a unique worker ID once, then issues IDs alone. Snowflake-style IDs work this way. The risk moves to the assignment step.
- Never. Generators use only local randomness and a local clock. UUID v4 works this way. There is nothing to assign, and the uniqueness guarantee is probabilistic.
Less coordination gives better availability and latency, including during network partitions, when nodes cannot reach a central service. You pay for it with weaker guarantees (probabilistic uniqueness) or with operational assumptions (unique worker IDs, sane clocks).
Predictability and information leakage
An ID is data that other people can read. A sequential ID reveals how many records exist and how fast you create them. It also makes enumeration easy: if /orders/1042 exists, someone will try /orders/1043. A timestamp-prefixed ID reveals when a record was created and sometimes which machine made it. Unpredictable IDs do not replace access control, but sequential public IDs make a missing access check much easier to exploit. A later chapter treats this in detail. For now, add one question to your checklist: "Will this ID be visible to people outside the system?"
Other properties worth a line each
- Density. Gap-free counters have no holes. Block allocation and failed transactions create gaps. Most systems can tolerate gaps, but some audit requirements cannot.
- Self-describing content. A timestamp inside the ID lets you filter by age without a join, but it also makes the ID depend on the clock.
- Human use. IDs that people read aloud or type benefit from short alphabets that avoid look-alike characters.
- Idempotency. If a client generates the ID before sending a request, the server can safely deduplicate retries. This needs client-side generation, so it favors low-coordination schemes.
How the properties pull against each other
The conflicts you will meet most often are these:
- Strict ordering conflicts with low coordination. Strict global order needs a sequencer.
- Small size conflicts with coordination-free uniqueness. Random uniqueness needs many bits, and a 64-bit ID leaves too little room.
- Time-based ordering conflicts with clock independence. Anything that embeds time inherits clock faults.
- Unpredictability conflicts with compact, ordered IDs. Counters and timestamps are guessable by nature.
No scheme is best in every row. You are choosing which weakness your system can live with.
A requirements checklist
Use these questions when you review a design:
- What is the uniqueness scope, and what happens on a duplicate? Is there a unique index?
- Do you need sort order? Is "roughly by creation time" enough?
- How many IDs per second, for how many years? How many bits does that need?
- Which clients read the ID, and can they handle 64-bit integers or long strings?
- What must still work during a partition or when the central database is down?
- Is the ID visible to outsiders, and what would a guesser learn from it?
- Will writers be single-region or many regions, and does that change who can coordinate?
Exercise
A team proposes 64-bit IDs made of a millisecond timestamp, a worker ID, and a sequence. The web front end is written in JavaScript and parses API responses with JSON.parse. Name one requirement the proposal meets and one problem it causes, and give a fix for the problem.
Show answer
It meets the requirements for compact size (64 bits fits a BIGINT), rough time ordering, and no per-ID coordination. The problem is that JSON.parse turns the ID into a 64-bit float, which is exact only up to 2^53 − 1, so the low digits of large IDs are silently rounded and two different IDs can look equal. The fix is to send the ID as a JSON string (and keep it as a string or BigInt in the client).
Exercise
Two servers issue time-ordered IDs from their own clocks. Server X's clock is 200 ms ahead of server Y's. A user action on Y at real time 5,000 ms is followed by an action on X at real time 5,100 ms. Which action gets the smaller ID, and what does this tell you about using ID order to decide which action came first?
Show answer
Y stamps 5,000 and X stamps 5,100 + 200 = 5,300, so Y's action still gets the smaller ID here and the order happens to be correct. But if the actions were reversed (X first at 5,000, then Y at 5,100), X would stamp 5,200 and Y would stamp 5,100, so the later action on Y would get the smaller ID. ID order follows clock readings, so it cannot be trusted to give the real order of events across nodes when clocks differ.