Skip to content

Unique IDs and ordering

Phase 6 · Distributed systems · 15 min read

What you'll be able to do

  • Choose an ID scheme from the needs of a database, API, and distributed workers.
  • Estimate collision risk and the capacity of a timestamp-based generator.
  • Explain what an ID can and cannot tell you about event order or access rights.

An ID is a contract

An ID gives one thing a stable name. A database row uses it as a primary key; another table uses it to join; an API puts it in a URL. It might also serve as an idempotency key, sharding key, or sort key. A unique value alone does not promise useful ordering, secrecy, or balanced distribution.

Before choosing a format, write down which properties matter:

  • Uniqueness: within which scope, for how long, and how will duplicates be rejected?
  • Ordering: do you need approximate creation order, per-worker order, or a strict global order?
  • Size: integers, 16-byte UUIDs, and their text encodings cost different amounts in indexes and URLs.
  • Unguessability and privacy: can a stranger predict another ID, or infer when and where it was made?
  • Generation: can workers create IDs independently, or must they contact a coordinator?

Two workers can both generate local counter value 42. If their records enter one table, those counters are not globally unique. Give workers disjoint ranges, add worker identifiers, or use random IDs. Keep a storage uniqueness constraint when possible; it catches collisions.

Common choices

Scheme Strength Cost or limit
Database auto-increment Simple, compact; values are allocated in sequence, but commit order can differ Database coordinates writes; public values expose rough counts and are easy to enumerate
UUIDv4 128-bit format with 122 random bits; workers need no ID server Random insertion order hurts B-tree locality; text form is long
UUIDv7 or ULID-style Timestamp first, so values are roughly time sortable and usually more index friendly Clock behavior matters; timestamp reveals creation time
Snowflake-style Compact integer: timestamp, machine ID, local sequence Machine IDs must be unique; clock rollback and sequence exhaustion need rules
Content hash Same bytes produce the same ID, useful for deduplication An edit changes the ID; identical content may need distinct identities
Ticket server or allocated ranges Compact unique numbers without a database round trip per ID Range allocation does not preserve creation order across workers; unused ranges can leave gaps

For ranges, a coordinator gives worker A 1000..1999 and worker B 2000..2999. Each can issue 1,000 IDs locally; the coordinator must record allocations durably. Worker B may issue 2000 before worker A issues 1001, so a bigger number does not mean a later record. A database sequence has a similar gap: a transaction that took a lower value can commit after one that took a higher value.

Count the bits before trusting the generator

A common Snowflake-style layout uses one unused sign bit, then 41 bits of milliseconds since a chosen epoch, 10 bits for a machine ID, and 12 bits for a sequence within that millisecond:

A Snowflake-style 64-bit ID: sign bit, 41 bits of milliseconds, 10 bits of machine, 12 bits of sequence.

Those widths give 2^41 milliseconds, about 2^41 / (1000 × 60 × 60 × 24 × 365.25) ≈ 69.7 years. Ten bits give 2^10 = 1024 machine values (0..1023). Twelve bits give 2^12 = 4096 values (0..4095) per millisecond per machine, a theoretical 4096 × 1000 = 4,096,000 IDs per second if every millisecond can be used. This is format capacity, not a throughput benchmark. A restarted process must not reuse a machine ID and timestamp/sequence combination that another process could issue.

# Encode one ID when timestamp and sequence are already valid.
value = (milliseconds << 22) | (machine_id << 12) | sequence
timestamp = value >> 22
machine = (value >> 12) & 0x3FF

Random IDs have a different risk. With n independent draws from k random bits, there are n(n - 1) / 2 pairs, and each pair matches with probability 1 / 2^k. So the birthday approximation for collision probability is n(n - 1) / 2^(k+1) while the result is small. Two draws give exactly 1 / 2^k. For large n you can shorten the formula to n² / 2^(k+1). For UUIDv4's 122 random bits and one billion (10^9) IDs, this is about 10^18 / 2^123 ≈ 9.4 × 10^-20. That assumes sound randomness and independent draws; copied generator state is a separate failure mode.

Time order is not event order

Wall clocks can drift or jump backward when adjusted, including by time synchronization. Thus a timestamp-first ID gives rough creation order, not a reliable history across machines. A generator that sees a clock rollback can refuse to issue IDs, wait until time catches up, or advance a persisted logical component. At sequence 4095, it must wait for the next millisecond or reject the request; resetting the sequence within the same millisecond repeats an ID. The lab uses a strict rule: raise on rollback, wait on sequence exhaustion.

For distributed logs, happens-before is more useful than comparing wall times: an event precedes the next event on its worker, and sending a message precedes receiving it. A Lamport clock increments on local events and makes a receiver advance beyond the timestamp sent with a message. If A happened before B, Lamport(A) is smaller; the converse is not guaranteed. Vector clocks track a counter per participant, so comparing two of them shows whether one event happened before the other or the two are concurrent, at the cost of more metadata. A deterministic total order of known events can sort by Lamport timestamp and break ties with the worker ID, but that tie-break does not create a causal relationship. Agreeing on a live authoritative order of accepted events, where no later arrival can slot in earlier, requires coordination.

Public names, short codes, and access

An internal integer can be a great join key without being a good public URL. /orders/101, /orders/102, and /orders/103 invite enumeration and reveal activity. A separate opaque public ID makes guessing harder, but it is not authorization: every request must still verify that its caller may access the object. This is the insecure direct object reference (IDOR) problem covered in authentication basics and security basics.

Base62 uses digits plus upper- and lowercase letters: 62² = 3844 possible two-character codes. Encoding a counter shortens it but does not hide its sequence; a random code is less predictable but needs collision checking. Calculate the code space before treating short codes as secret.

Do not hash an email address into a public ID to “hide” it. Anyone who can guess the email can hash it too. Hashes of low-entropy personal data can still expose that data. Keep personal information out of ID inputs, or use a keyed construction when a deterministic private lookup is genuinely needed.

IDs meet indexes and shards

A B-tree index stores nearby keys near each other. Random UUIDv4 primary keys scatter inserts across pages and can cause page splits and extra writes. Time-ordered IDs tend to insert near the right edge, improving locality. That same pattern can overload one range shard if new writes all target the newest range. See partitioning before using an ID as the sharding key.

Changing an ID scheme after foreign keys, logs, caches, and shard routing depend on it needs a migration and often an old-to-new mapping. Store UUIDs in a native or binary representation where supported when index size matters; text takes more storage space.

For AI engineers

For AI engineers

A training script often writes a run folder named with the current time. Two workers starting in the same tick can choose the same name, and timestamps alone do not tell you which log event caused another. Give runs and experiments stable IDs, attach a request or trace ID to every LLM call, and reuse an idempotency key when retrying the same billable or state-changing request. The server must define what counts as the same request and retain its result for an appropriate window.

For RAG ingestion, give each document and chunk a stable ID so a second ingestion updates records rather than duplicating them. Keep two values apart. The slot ID comes from the document ID, chunking version, and chunk position, so it survives an edit to the text. The content digest is a hash of the normalized text; when it changes, re-embed and overwrite that slot. After each ingestion, delete the slots the new run no longer produced, such as the tail of a shortened document or every slot from an old chunking version. Otherwise stale vectors stay searchable. Inserting text near the start can shift many positions and force re-embedding. A content hash can also serve as a cache key.

Common mistakes

  • Publishing auto-increment IDs as protection: sequential URLs are easy to enumerate. Use access checks for every object and consider separate opaque public IDs.
  • Treating time.time() as monotonic: wall time can move backward; define rollback and sequence exhaustion behavior.
  • Trusting client-generated IDs: accept them only after validating format, ownership, and uniqueness. The client cannot grant itself access by choosing an ID.
  • Hashing personal data into IDs: an unkeyed hash of a guessable value can be reversed by trying candidates; avoid putting personal data in ID material.
  • Changing schemes after sharding: IDs may determine shard placement and foreign keys. Plan a mapping and migration before replacing them.
  • Storing UUIDs as text by default: when the database supports a compact native or binary type, it can reduce index size.

Check yourself

Two workers each produce sequence 7 at the same millisecond. When do their Snowflake-style IDs collide?

They collide if both use the same machine ID and timestamp, because all three encoded fields match. Distinct machine IDs keep them separate; the assignment must remain unique across restarts.

A UUIDv7 from worker A sorts before one from worker B. Can you conclude that A's event caused B's?

No. Timestamp order is approximate and clocks can differ. Even an accurate wall-time order does not establish a message or process relationship. A causality scheme such as Lamport or vector clocks needs event and message updates.

A URL shortener encodes its counter in base62. Is the result unpredictable, and what would random codes change?

No: base62 changes the representation, not the counter's sequence. Random codes are harder to predict but require enough code space and a uniqueness check when assigned.

A RAG job ingests the same document twice and creates duplicate chunks. What should be stable, and what should change when the text changes?

Keep a stable document identity and a stable slot ID built from the document ID, chunking version, and position, so re-ingestion can upsert. Track a content digest separately: when it changes, refresh the vector. Delete slots the new run no longer produces.

Lab

Build small ID tools in code/unique-ids/. Start with base62 codes and a collision estimate, then make RAG slot IDs and content digests. Build and decode Snowflake-style IDs with an injected millisecond clock. Handle sequence rollover and clock rollback, then model message order with a Lamport clock. Run: cd code/unique-ids && PYTHONPATH=starter python -m pytest tests -q

Go deeper