SysDesignAtlas

Unique ID Generation

Why auto-increment breaks when you shard, the Snowflake layout, UUID versions, and how to get sortable IDs without a coordinator.

HLDMedium11 min readidsnowflakeuuiddistributed
Confidence

#The requirements

Every distributed system needs to mint identifiers. The requirements conflict, which is what makes it an interview question:

  1. Unique — globally, forever, without servers having to ask each other (or a central service) every time they create an ID. That per-ID check would sit on every single insert, the busiest code path you have.
  2. Sortable by time — if newer IDs are always larger, "the 20 most recent" is a range scan, paging through results is natural, and new rows are added at the end of the index rather than poked into the middle.
  3. Compact — 64 bits is one ordinary integer column, and fits in a CPU register; 128 bits doesn't.
  4. High throughput — millions per second, generated locally.
  5. Non-guessable (sometimes) — sequential IDs leak how much business you do (order 5,000 today, order 5,900 tomorrow means ~900 orders a day), and let an attacker walk through other users' resources by trying the next number.

Requirements 2 and 5 are in direct opposition; that tension is the heart of the discussion.

#Auto-increment: why it stops working

A single database's AUTO_INCREMENT is perfect until you shard. Then every shard would produce ID 1, 2, 3 — collisions everywhere.

Patch 1 — stepped increments. Shard k of N starts at k and steps by N: shard 0 gives 0, 4, 8; shard 1 gives 1, 5, 9. Works, but adding a shard breaks the scheme entirely: with 5 shards every shard must now step by 5, and the new sequences collide with IDs the old step-by-4 scheme already handed out.

Patch 2 — a central ID service. One database hands out IDs. Now you have a single point of failure and a network round trip on every insert.

Patch 3 — ticket/range allocation. The central service hands out blocks ("you own 10,000–19,999"). Servers allocate locally and fetch a new block when low. This is genuinely good. The server talks to the central service once per 10,000 IDs instead of once per ID, so the coordination cost spread across all those IDs is close to zero. It's what several large systems actually use.

Downsides: IDs are only roughly time-ordered across servers — server A might still be handing out 10,500 from its old block while server B has started on 20,000, so a larger ID doesn't always mean newer. And a server that dies wastes its unused block (harmless — you have 2⁶³ of them).

#Snowflake IDs

The standard answer, and the one to lead with. It's a 64-bit number chopped into fields, and once a machine knows its own number at startup it can mint IDs forever without asking anyone anything — that's what "coordination-free" means here.

   ┌─┬───────────────────────┬──────────┬────────────┐
   │0│      timestamp        │ machine  │  sequence  │
   │ │      41 bits          │ 10 bits  │  12 bits   │
   └─┴───────────────────────┴──────────┴────────────┘
     ▲         ▲                  ▲            ▲
   sign    ms since a         1024 nodes   4096 per ms
   (always custom epoch                    per node
    0 = positive)  ~69 years

Why each field is that size:

  • 41 bits of milliseconds ≈ 69 years from your chosen epoch. Use a custom epoch (your project's start date), not the Unix epoch, or you burn decades of range immediately.
  • 10 bits of machine ID = 1,024 generators. Assigned via ZooKeeper/etcd, or derived from a pod ordinal or private IP.
  • 12 bits of sequence = 4,096 IDs per millisecond per node = 4M/s per node, ~4 billion/s across the cluster.

Properties you get:

  • Globally unique with zero coordination once each machine has its ID.
  • k-sortable — roughly time-ordered. The timestamp sits in the leftmost (most significant) bits, so an ID minted later is always a bigger number than one minted earlier. "Roughly" because two machines' clocks may differ by a few milliseconds, and IDs within the same millisecond are ordered by machine ID, not true time.
  • Compact — one 64-bit integer.
  • Locally generated, so no network call.

The two failure modes to name — this is where the depth is:

  1. Clock skew. Machine IDs prevent collisions between nodes, but if a single node's clock jumps backwards (NTP correction, VM migration), it can regenerate timestamps it already used and produce duplicates. Standard handling: detect that now < last_timestamp and either spin until the clock catches up (safe, briefly blocks) or refuse to serve and alert. Never silently proceed.
  2. Sequence exhaustion. More than 4,096 IDs in one millisecond on one node means waiting for the next millisecond. Fine in practice, but it's a bounded throughput per node and you should say so.

#UUIDs

128 bits, generated with no coordination at all.

UUIDv4 — 122 random bits. Collision probability is negligible (you'd need on the order of 10¹⁸ UUIDs for a 50% chance). Zero coordination, unguessable.

The problem: randomness destroys locality. In a clustered index (MySQL's InnoDB works this way), the rows themselves are stored on disk in primary key order, in fixed-size pages. With increasing keys, every insert goes to the last page, which is already in memory. With random keys, each insert lands in a random page somewhere in the table:

  • That page has to be read from disk if it isn't cached.
  • If it's full, it has to be split in two (a page split), leaving half-empty pages behind (fragmentation).
  • The set of pages you're actively writing to (the working set) is the whole table, which is too big to keep in memory.

On a large table this can be several times slower than sequential inserts. This is a real production issue and a great thing to raise.

UUIDv7 — the modern fix, and what to recommend today. A 48-bit Unix millisecond timestamp followed by random bits:

   ┌────────────────────┬──────┬─────────────────────┐
   │ unix_ts_ms (48)    │ ver  │  random (74 bits)   │
   └────────────────────┴──────┴─────────────────────┘

Time-ordered like Snowflake, uncoordinated like v4, standard across languages. It costs 128 bits instead of 64 and reveals creation time — but it solves the index-locality problem cleanly. For most systems, UUIDv7 is the right default, with Snowflake reserved for when 64-bit compactness genuinely matters.

UUIDv1 — timestamp plus MAC address. It leaks the generating machine's MAC (hardware) address. And although it contains a timestamp, the timestamp's low-order bits are stored first, so sorting v1 UUIDs as text or bytes does not sort them by time. Avoid.

#Sortable vs unguessable

You usually can't have both, and the correct answer is to stop trying.

Sequential and time-ordered IDs leak information:

  • A competitor can register two accounts an hour apart and subtract the IDs to get your signups per hour.
  • An attacker can enumerate — try /orders/1001, /orders/1002, and so on — to find other people's orders.

The clean resolution is two identifiers:

   internal_id  BIGINT       Snowflake/sequence — PK, joins, indexes
   public_id    TEXT         random 128-bit, base62 — URLs, APIs

The database gets locality and compactness; the outside world gets an opaque token. Add an index on public_id for lookups.

Never rely on unguessable IDs as authorization. Every request for /orders/{id} still has to check that the logged-in user actually owns that order. IDs leak — in logs, browser history, shared screenshots — and anyone holding a leaked ID would otherwise get straight in. An unguessable ID is defence in depth (an extra layer that makes attacks harder), not a permission system. Saying this is a small security-awareness signal that lands well.

#Short IDs for URLs

For a URL shortener you need something human-typable — 7 characters, not 20.

Base62 encoding (0-9a-zA-Z) of a counter gives 62⁷ ≈ 3.5 trillion combinations in 7 characters. But a plain counter makes the codes guessable — abc123 is followed by abc124. The usual fixes:

  • Pre-generate keys and shuffle them. Fill a pool with codes in random order, and hand out the next one from the pool.
  • Encrypt the counter with a format-preserving cipher — encryption whose output is the same size and shape as the input. Counter 1,000 becomes some random-looking 7-character code. Because encryption is reversible, two different counters can never produce the same code, so there are no collisions, ever, and no lookup table to store.

Hash-then-truncate (take the first 7 chars of an MD5) is the tempting alternative and it's worse. Truncated hashes collide much sooner than you'd expect: by the birthday bound, with N possible codes you reach a 50% chance of a collision after only about √N codes — around 2 million for 3.5 trillion codes, nowhere near exhausting the space. So you need a collision check and retry loop on every insert.

#Choosing

SituationChoice
General-purpose modern defaultUUIDv7
Need 64-bit, very high throughput, time-orderedSnowflake
Single database, no sharding plannedBIGSERIAL — don't over-engineer
Sharded SQL, want dense sequential IDsTicket/range allocation service
Public-facing, must be unguessableRandom 128-bit public_id + internal numeric PK
Short, typable codesBase62 over a shuffled/encrypted counter

#Check yourself

Why does auto-increment break when you shard?Show answer
Each shard counts 1, 2, 3 independently, so IDs collide. Stepped increments break when you add a shard, and a central ID service adds a round trip and a single point of failure.
Lay out a Snowflake ID and what each field allows.Show answer
1 sign bit, 41 bits of milliseconds since a custom epoch (about 69 years), 10 bits of machine ID (1,024 generators), 12 bits of sequence (4,096 per ms per machine, about 4M/s each).
What happens if a Snowflake generator's clock steps backwards, and what should it do?Show answer
It could reissue timestamps it already used and create duplicates. Track the last timestamp: for a small step, wait until the clock catches up; for a large jump, take the node out of rotation and alert.
Why do random UUIDv4 keys hurt a clustered index?Show answer
Rows are stored in key order, so random keys land in random pages — page splits, fragmentation and a working set that won't stay cached. Inserts can be several times slower than sequential ones.
What does UUIDv7 fix, and what does it cost?Show answer
A 48-bit millisecond timestamp up front makes it time-ordered (good index locality) while staying coordination-free. It's 128 bits instead of 64 and reveals creation time.
How do you get both index-friendly and unguessable IDs?Show answer
Use two: a numeric internal ID for the primary key and joins, and a random 128-bit public ID for URLs and APIs, indexed for lookups.
Why shouldn't an unguessable ID be your access control?Show answer
It's defence in depth, not permission: every request must still check the caller owns the resource.
Why is hash-then-truncate a poor way to make short URL codes?Show answer
Truncating a hash makes collisions likely well before the space runs out (the birthday bound), so every insert needs a collision check and retry. Encode a shuffled or encrypted counter instead.

#What to carry forward

  • Auto-increment works until you shard; ticket ranges, Snowflake or UUIDv7 work after.
  • Snowflake packs time, machine and sequence into 64 bits — guard against clocks going backwards.
  • Random UUIDv4 keys wreck B-tree locality; UUIDv7 is the modern default.
  • Sortable and unguessable conflict: use an internal ID plus a random public ID, and still check access.
  • Match the scheme to the scale — a single database's BIGSERIAL is the right answer when there's no sharding.
00:00
/ 11m