CONCEPT SHEET · Concepts

Unique ID Generation

One-liner: Pick IDs that are unique across nodes without coordination and, ideally, time-sortable: Snowflake-style 64-bit or UUIDv7/ULID.

ArticleConcepts© Arthur Bernier Jr598 words1 code block

Say this#

How it works#

Snowflake layout (64 bits):

TEXT
| 0 | 41 bits: ms since custom epoch | 10 bits: worker id | 12 bits: sequence |      ~69 years                         1024 workers          4096 ids / ms / worker
  1. Each worker gets a unique ID (config or Zookeeper).
  2. On request: read clock; if same ms, increment sequence; if sequence overflows, spin to next ms.
  3. If clock moved backwards: refuse or wait; alert.
  4. Result: sortable, unique, 64-bit (fits BIGINT), no network call per ID.

Variants: Instagram (41 time + 13 shard + 10 seq, generated inside Postgres with a PL/pgSQL function), Sony Sonyflake (39 time in 10 ms + 8 seq + 16 machine), Discord snowflakes.

UUIDv7 layout: 48-bit ms timestamp | ver(4) | 12 rand | var(2) | 62 rand. Stored as 128-bit, string 36 chars.

Trade-offs#

ChoiceProCon
Auto-incrementSimple, compact, sortableSingle DB bottleneck; sharding needs offsets/step; predictable
UUID v4No coordination, unguessable128 bits; random index inserts hurt (InnoDB clustered PK especially)
UUID v7 / ULIDNo coordination, sortable, index-friendly128 bits; leaks creation time
Snowflake64 bits, sortable, very fast, fits BIGINTNeeds worker-ID assignment and clock discipline
Ticket serverWorks with legacy auto-increment codeExtra service; two-server trick limits scale
Hi/Lo blocksFew round tripsGaps; not time-ordered across nodes

Numbers#

  • Snowflake: 4096 IDs per ms per worker ≈ 4M IDs/s per worker; 1024 workers; 41-bit ms timestamp lasts ~69 years from epoch.
  • UUID: 128 bits; v4 has 122 random bits; collision probability negligible (~1 in 2^61 for 2^30 IDs).
  • ULID string 26 chars; UUID string 36 chars (32 hex + 4 dashes); BIGINT 8 bytes.
  • UUIDv7 timestamp resolution 1 ms; monotonic within a node via counter bits if implemented.

In the interview#

See also