Unique ID Generation

Generating unique IDs across many machines: UUIDs, Snowflake, ULID and ticket servers.

What is it?

Every record needs an ID. On one database, an auto-increment column does the job. Once writes are spread across many servers, shards or regions, you need IDs that are unique without every insert asking one central counter.

Common options:

- UUID v4: 122 random bits. Unique in practice, no coordination, but random order. - UUID v7: starts with a millisecond timestamp, then random bits, so IDs sort roughly by creation time. - Snowflake (from Twitter): a 64-bit integer made of a timestamp, a machine id and a per-machine sequence number. - ULID: 128 bits, a 48-bit millisecond timestamp plus 80 random bits, written as 26 sortable characters. - Ticket servers: a central service hands out numbers, often in blocks.

The trade-offs are size, sortability, coordination, and how much the ID leaks (like creation time or volume).

Explain like I'm 10

A deli's ticket dispenser works great for one counter. With 100 counters, you either give each counter its own prefix (counter 7 hands out 7-001, 7-002...), or let everyone pick a random 30-digit number and trust that two people will never pick the same one.

Examples

A simplified Snowflake generator

const CUSTOM_EPOCH_MS = 1288834974657n; // Twitter's original epoch
let lastTimestampMs = -1n;
let sequence = 0n;

function nextId(machineId /* 0..1023 */) {
  let now = BigInt(Date.now());

  if (now < lastTimestampMs) {
    throw new Error("Clock moved backwards; refusing to generate IDs");
  }
  if (now === lastTimestampMs) {
    sequence = (sequence + 1n) & 4095n;           // 12-bit sequence
    if (sequence === 0n) {                         // 4096 used this ms
      while (now <= lastTimestampMs) now = BigInt(Date.now());
    }
  } else {
    sequence = 0n;
  }
  lastTimestampMs = now;

  return ((now - CUSTOM_EPOCH_MS) << 22n)          // 41-bit timestamp
       | (BigInt(machineId) << 12n)                // 10-bit machine id
       | sequence;                                 // 12-bit sequence
}

Uniqueness comes from the layout: two machines differ in machine id, and two IDs from one machine in the same millisecond differ in sequence. BigInt is used because the result doesn't fit in a JS number safely.

How it works

Auto-increment is simple and compact, but it's one counter in one database: a bottleneck and single point of failure for writes, awkward across shards, and it leaks business volume (order 10,500 tells competitors how many orders you have).

UUID v4 needs no coordination. The chance of a collision is negligible at any realistic scale, assuming a good random source. But 128 bits is big, and random values inserted into a B-tree index land on random pages, causing page splits and poor cache locality as the table grows.

UUID v7 (standardized in RFC 9562, 2024) puts a 48-bit Unix millisecond timestamp first, so new IDs are mostly appended to the end of the index. It keeps the UUID format and needs no coordination. ULID solves the same problem in a different encoding.

Snowflake layout (64 bits): 1 unused sign bit, 41 bits of milliseconds since a custom epoch (about 69 years), 10 bits of machine id, 12 bits of sequence. It fits in a BIGINT and sorts by time. Costs: machine ids must be assigned uniquely (via config or a coordinator like ZooKeeper), and it depends on clocks.

Ticket servers: a dedicated database hands out numbers. Flickr ran two MySQL servers, one producing odd and one even numbers, for redundancy. A common optimization is handing each app server a block (say 1,000 IDs) at a time so most IDs need no network call.

Sortability and clock skew: time-based IDs are only roughly ordered across machines, because clocks differ by milliseconds or more. Never rely on them for strict global ordering. If a machine's clock jumps backwards (an NTP correction), a naive generator can issue duplicates; it should wait or refuse until time catches up.

Snowflake ID (64 bits)
| 0 | 41 bits: ms since epoch | 10 bits: machine | 12 bits: sequence |
  ^ sign bit (unused)            1024 machines      4096 IDs/ms/machine

UUID v7 (128 bits)
| 48 bits: Unix ms | 4: version | 12: random | 2: variant | 62: random |

Option          Size     Sortable   Coordination        Leaks
Auto-increment  64 bit   yes        one DB              counts
UUID v4         128 bit  no         none                nothing
UUID v7 / ULID  128 bit  ~by time   none                creation time
Snowflake       64 bit   ~by time   machine-id setup    time, machine
Ticket server   64 bit   yes        central service     counts

Why does it exist?

Distributed systems write from many places at once. Asking one central counter for every ID adds latency and a single point of failure, while purely random IDs hurt database performance and can't be sorted. These schemes are different balances of uniqueness, ordering, size and independence.

When to use it

- Auto-increment: a single database that isn't going to be sharded soon, for internal IDs that aren't exposed publicly. - UUID v7 or ULID: a good modern default for distributed inserts into B-tree indexed tables. - UUID v4: when IDs must reveal nothing, including creation time. - Snowflake: very high throughput where a compact 64-bit, time-sortable integer matters (feeds, messages, events). - Ticket server with blocks: when you need dense, mostly sequential numbers (invoice numbers) across services.

When not to use it

Don't expose sequential IDs in public URLs if guessing neighbors is a risk; always enforce authorization anyway. Don't use UUID v4 as the clustered primary key of a huge, write-heavy table if you can use a time-ordered ID. Don't use time-based IDs as a strict ordering of events across machines.

Common mistakes

  • Treating time-based IDs from different machines as a precise global order, ignoring clock skew.

  • Ignoring backward clock jumps in a Snowflake-style generator, producing duplicate IDs.

  • Assigning the same machine id to two instances (for example, cloned containers), causing collisions.

  • Sending 64-bit IDs to JavaScript as JSON numbers, which lose precision above 2^53; send them as strings.

  • Relying on unguessable IDs as the only access control instead of checking permissions.

Practice exercises

  1. Easy:

    List three problems with using a single database's auto-increment for IDs in a sharded system.

  2. Medium:

    How many IDs per second can a Snowflake deployment with 1024 machines generate at most? When does the 41-bit timestamp run out if the epoch is set to today?

  3. Hard:

    Design ID generation for a multi-region chat app where message IDs must be unique, roughly time-ordered within a conversation, and generated without cross-region calls.

Interview questions

Why doesn't auto-increment work well in distributed systems?

It relies on one counter in one database, so every insert depends on that node: a bottleneck and single point of failure. Separate shards would produce overlapping values, and sequential IDs leak volume and are easy to enumerate.

What's the downside of UUID v4 as a primary key?

It's 128 bits (larger indexes), and it's random, so inserts land on random B-tree pages, causing page splits, fragmentation and poor cache locality. Time-ordered IDs like UUID v7 append near the end of the index instead.

What's the difference between UUID v4 and v7?

v4 is almost entirely random (122 random bits). v7 starts with a 48-bit Unix millisecond timestamp followed by random bits, so values sort roughly by creation time while still needing no coordination.

Describe the Snowflake ID layout.

64 bits: 1 unused sign bit, 41 bits of milliseconds since a custom epoch (about 69 years), 10 bits of machine id (1024 machines), and 12 bits of sequence (4096 IDs per millisecond per machine).

What happens if the clock goes backwards on a Snowflake generator?

It could generate a timestamp it already used, and with the sequence reset, duplicate IDs. Generators detect this and either wait until the clock passes the last timestamp or refuse to generate and raise an error.

What is a ULID?

A 128-bit ID with a 48-bit millisecond timestamp and 80 random bits, encoded as 26 characters in Crockford Base32. It sorts lexicographically by time and needs no coordination.

What is a ticket server, and how do you avoid it being a bottleneck?

A central service (often a database) that hands out increasing numbers. To scale it, hand out blocks of IDs to each client so most IDs are generated locally, and run more than one server with interleaved ranges (Flickr used odd/even) for availability.

Are time-sortable IDs globally ordered?

Only roughly. Each machine's clock differs, so an ID from machine A can be larger than a later one from machine B. They're great for index locality and approximate ordering, not for strict causal order.

Why might you avoid exposing time-based IDs publicly?

They reveal when something was created, and Snowflake-style IDs also reveal the machine and per-millisecond volume. If that's sensitive, use random IDs externally (or a separate public ID) and keep the sortable ID internal.

Your frontend shows wrong IDs that differ in the last few digits. Why?

64-bit integer IDs were sent as JSON numbers, and JavaScript numbers are doubles that represent integers exactly only up to 2^53 - 1. Larger IDs get rounded. Serialize them as strings.