How to Implement a Distributed ID Generator
Generate unique ids across many nodes without coordination: UUIDv7, ULID and Snowflake, and the trade-offs of each for storage and indexing.
On this page
Introduction
Every record needs a unique id, and generating it somewhere sensible is a design decision with consequences for storage, indexing and performance. A database sequence is simple but centralises generation and reveals ordering. Random UUIDs need no coordination but hurt index locality and storage. Time-ordered ids such as UUIDv7, ULID and Snowflake give uniqueness without coordination and sort by creation time, which keeps indexes efficient. Choosing among them depends on what you need from the id.
What an Id Must Provide
An id must be unique, obviously, but also: generatable without coordination if you run many nodes, sortable by creation time if you want efficient pagination and indexes, opaque if you do not want to leak counts or ordering, and compact if you store billions. No single scheme gives all of them, so the choice is about which properties matter.
The two big tensions are coordination versus local generation, and sortability versus opacity. A database sequence is coordinated and sequential; a random UUID is local and opaque; a time-ordered id is local and sortable but leaks creation time and rough ordering.
# id properties to weigh
[ ] unique (all schemes)
[ ] generatable without a coordinator (for many nodes)
[ ] sortable by creation time (for pagination + index locality)
[ ] opaque (no leaked counts/ordering)
[ ] compact (storage at scale)
# no scheme gives all; pick by what matters for the record
Random UUIDs and Their Cost
A UUIDv4 is 122 random bits, generated anywhere without coordination and practically collision-free. The cost is that it is random, so inserts scatter across the index: each insert touches a random page, causing page splits and poor cache locality, and the index grows fragmented. On a write-heavy table this is a measurable throughput cost.
Random UUIDs are also large (16 bytes) compared to a 64-bit integer, so they cost more storage and more index space. They are opaque, which is their virtue, but the indexing cost is real and is why time-ordered alternatives exist.
# UUIDv4
+ no coordination, opaque, collision-free in practice
- 16 bytes (vs 8 for a bigint)
- RANDOM => writes scatter across the index: page splits, poor locality
# the random write pattern is the main cost on a write-heavy table
Time-Ordered Ids: UUIDv7 and ULID
UUIDv7 puts a millisecond timestamp in the high bits and fills the rest with randomness, so ids are still unique and local but sort by creation time. ULID is similar: a 48-bit timestamp plus randomness, encoded in a compact string. Both keep inserts roughly sequential, which restores index locality, while remaining opaque enough for most purposes.
They leak creation time and rough ordering, which matters if the id is user-visible and the ordering is sensitive. The timestamp is coarse (milliseconds) so ids created in the same millisecond fall back to the random part for ordering; a strict per-millisecond order needs a counter added, as Snowflake does.
// UUIDv7: 48-bit ms timestamp + version/variant + randomness (illustrative).
function uuidv7(): string {
const ts = Date.now();
const timeHex = ts.toString(16).padStart(12, '0'); // 48 bits of time
const rand = crypto.getRandomValues(new Uint8Array(10)); // 80 bits of randomness
const r = Buffer.from(rand).toString('hex');
// layout: time | ver 7 | randA | variant | randB (RFC 9562)
return `${timeHex.slice(0,8)}-${timeHex.slice(8,12)}-7${r.slice(0,3)}-${r.slice(3,7)}-${r.slice(7,19)}`;
}
// sortable by creation time => inserts stay roughly sequential
Snowflake and Variants
Snowflake packs a timestamp, a node id and a per-millisecond sequence into 64 bits: uniqueness comes from the combination, not from randomness. It is compact (fits a bigint), sortable, and needs no coordination because each node has a distinct node id assigned at configuration.
The catch is the node id: it must be unique and stable across the fleet, which is a coordination point (assigned from a config service, the machine’s identity, or a range of ids per region). A duplicated node id produces duplicate ids, and clock drift can produce out-of-order ids, so the clock must be monotonic enough.
# Snowflake 64-bit layout (common variant)
[ 41 bits timestamp ][ 10 bits node id ][ 12 bits sequence ]
# - unique from the node id + sequence, not randomness
# - compact (bigint), sortable, no runtime coordination
# - requires a UNIQUE, STABLE node id per instance (a config point)
# - guarded against clock going backwards (reject or wait)
Choosing for Storage and Indexing
For a database primary key, a time-ordered id keeps the index efficient: inserts go to the right end, pages fill sequentially, and range scans by id follow the time order. A random UUID scatters writes; a sequential bigint from a sequence is efficient but centralised. Time-ordered ids are the common sweet spot for distributed systems.
If the id is internal only, a Snowflake bigint is the most compact. If it must be a UUID (for a standard or a client that expects one), UUIDv7 gives the UUID format with time ordering, which is why it is the modern recommendation over UUIDv4 for primary keys.
# pick by use
internal PK, want compact -> Snowflake bigint
must be a UUID -> UUIDv7 (time-ordered, unlike v4)
human-readable sortable -> ULID (compact string, time-ordered)
no ordering wanted at all -> UUIDv4 (accept the index cost)
Uniqueness and Failure Modes
Every scheme has a uniqueness argument: UUID randomness (collision probability negligible), or a node id plus sequence. The failure modes are where the assumptions break: a duplicated Snowflake node id, a clock that jumps backwards (so the same millisecond is reused), or a random generator seeded identically on two nodes.
Guard the clock: if time goes backwards, either wait until it catches up or reuse the sequence carefully, so ids never repeat or go out of order. Test node-id uniqueness as an operational invariant, because a duplicated node id is a silent uniqueness bug that surfaces as a primary-key violation.
# failure modes to guard
[ ] duplicated node id (Snowflake) => duplicate ids; enforce uniqueness
[ ] clock goes backwards => reuse the ms; wait or bump the sequence
[ ] random seeded identically => collisions; use a CSPRNG
# make node-id uniqueness an operational check, not an assumption
Common Pitfalls and Conclusion
Do not use UUIDv4 as a primary key on a write-heavy table without accepting the index cost; use UUIDv7 instead. Do not assign two nodes the same Snowflake node id. Do not ignore a clock that goes backwards. And do not assume any id scheme removes the need to validate uniqueness at the storage layer, where a duplicate must be rejected.
A distributed id generator gives every node a way to mint unique ids without coordinating per id. Choose by the properties you need: UUIDv7 for a time-ordered UUID, ULID for a compact sortable string, Snowflake for a compact bigint with a node id, UUIDv4 only when opacity outweighs the index cost. Guard the assumed invariants (node ids, the clock) and let the storage layer enforce uniqueness as the backstop.
Sources: RFC 9562: UUIDs (incl. UUIDv7), ULID specification, Snowflake id (Twitter) overview.
FAQ
- Why is a random UUID bad as a database primary key?
- Because randomness makes inserts scatter across the index, causing page splits and poor locality, and it is 16 bytes rather than 8. The write pattern is the main cost on a write-heavy table. UUIDv7 keeps the UUID format but is time-ordered, restoring locality.
- What is the catch with Snowflake ids?
- The node id must be unique and stable across the fleet, which is a coordination point; a duplicated node id produces duplicate ids. Clock drift can also break ordering, so the generator must guard against the clock going backwards.
Report a problem with this articleOpens a pre-filled issue on GitHub.