Skip to content

Lesson 14 of 38Data internals

Generating Unique IDs

Auto-increment, UUIDv4, UUIDv7, ULID, and Snowflake: how each one works, what it costs your index, and which to choose for a sharded system.

16 min read0/5 questions

Every row, order, message, and upload needs an ID, and on one database server you never think about it: id SERIAL PRIMARY KEY and you are done. Then the system grows. You shard the database, run writers in three regions, and want mobile clients to create records offline. Now two machines can hand out the same number, or one central counter becomes the thing every write waits on. Picking an ID scheme is a small decision that is very hard to undo later, because IDs end up in URLs, foreign keys, logs, caches, and other companies' databases. This lesson gives you the options and how to choose.

Start with requirements

Before naming a scheme, ask what the ID must do. These are the questions an interviewer wants to hear you ask:

  • Unique: across what? One table, one service, or every system you will ever merge with?
  • Sortable by time? Do you want ORDER BY id to mean "newest last", and do you want new rows to land at the end of the index?
  • Size: does it have to fit in 64 bits (a BIGINT, a single CPU register), or can it be 128 bits?
  • Unguessable? Will it appear in a URL where someone could try the next value?
  • No coordination? Can any machine, or a phone with no signal, create one without asking anyone?
  • Rate: how many per second, per machine?

No scheme wins on all six. The rest of this lesson is about which ones each scheme gives up.

Auto-increment and its limits

A database sequence (SERIAL, IDENTITY, MySQL AUTO_INCREMENT) is the default for good reasons. It is 64 bits, strictly increasing, cheap, and perfect for a B-tree because every insert goes to the rightmost leaf page.

The problems appear at scale or in public:

  • One counter, one place. Every insert in the system depends on the server that owns the sequence. That is fine for one database and a problem when you shard, because each shard's counter starts at 1 and you get duplicates.
  • It leaks information. If your order IDs go from 50,120 on Monday to 51,320 on Tuesday, a competitor knows you took 1,200 orders. Statisticians estimated German tank production in World War II from serial numbers this way.
  • It invites enumeration. If /invoices/50121 works, someone will try /invoices/50122. When the server forgets to check that the invoice belongs to the caller, that is an IDOR (insecure direct object reference), one of the most common real security bugs. The real fix is the authorization check. An unguessable ID is a second layer, not a replacement.
  • Gaps are normal. Sequences are not transactional. A rolled-back insert still consumes its number. Never use them as invoice numbers that must have no gaps.

Two classic workarounds keep integers across machines:

  • Per-shard offsets. With 4 shards, shard 0 hands out 0, 4, 8, shard 1 hands out 1, 5, 9, and so on. MySQL supports this with auto_increment_increment and auto_increment_offset. Adding a fifth shard later is awkward.
  • Ticket servers. Flickr ran two small MySQL servers whose only job was handing out IDs, one giving odd numbers and one even. Every app server asked one of them. It works, but it adds a network hop and a dependency to every write, and you must run and fail over those servers.

UUIDv4: random and coordination-free

A UUID is 128 bits, usually written as 36 characters like 9b2f6c1e-4d7a-4e0b-9a51-3c8e2f7d6a10. Version 4 fills 122 of those bits with randomness (the other 6 mark the version and variant). Anyone can generate one anywhere, and the chance of a collision is negligible: you would need to generate around 2.7 quintillion of them to have a 50% chance of a single duplicate.

That makes UUIDv4 great for coordination-free creation and for public IDs nobody can guess. Its cost is in the database:

  • Random inserts. Each new key lands at a random spot in the B-tree. As you saw in How Databases Store Data, that means a random leaf page per insert, page splits everywhere, and half-empty pages. Worse, the whole index becomes the working set: the buffer pool must hold every leaf page to avoid disk reads, instead of just the right-hand edge.
  • Size. 16 bytes, twice a BIGINT, and repeated in every secondary index (InnoDB stores the primary key in every secondary index entry) and every foreign key. Store it in a native uuid column, never as a 36-character string.
  • No order. You cannot sort by it to get creation order.

On a small table none of this matters. On a table taking thousands of inserts per second with more data than memory, teams have measured big drops in insert throughput and much larger indexes compared to sequential keys.

UUIDv7 and ULID: time first, then random

UUIDv7, defined in RFC 9562 (May 2024), keeps the 128-bit UUID format but puts a 48-bit Unix timestamp in milliseconds at the front, followed by version bits and about 74 random bits. Because the time comes first, IDs created later sort later. New rows go to the right edge of the index, like a sequence, but no coordination is needed.

Postgres 18 ships a built-in uuidv7() function (plus uuid_extract_timestamp() to read the time back out). Most languages have a library. Within one millisecond, the RFC allows extra precision or a counter in some of the random bits so IDs from one generator stay in order. Check what your library does if strict ordering within a millisecond matters.

ULID is the older community spec with the same idea: 48 bits of millisecond time plus 80 random bits, written as 26 characters in Crockford base32 (01J9ZK3Q7X...), which sorts correctly as a string. If you are starting fresh in 2026, UUIDv7 is the standard choice because databases and tools understand the UUID type.

One trade-off is easy to miss: a UUIDv7 reveals when it was created. Usually that is harmless. For something like a user ID where signup time is sensitive, it is a leak.

Three ID layouts, high bits first
  1. UUIDv4: 122 random bits + 6 version/variant bits128 bits, no order
  2. UUIDv7: 48-bit Unix ms | 4 version | 12 rand | 2 variant | 62 rand128 bits, time-ordered
  3. Snowflake: 1 sign | 41-bit ms since epoch | 10 machine | 12 sequence64 bits, time-ordered

UUIDv4 is all randomness. Anyone can make one, and inserts land all over the index.

1/3

Snowflake: 64 bits, sorted, no central counter

Twitter built Snowflake in 2010 when it moved off a single MySQL sequence. It packs three fields into a signed 64-bit integer:

  • 1 bit unused (the sign bit, so the number stays positive).
  • 41 bits of milliseconds since a custom epoch. 2^41 ms is about 69.7 years, so you pick an epoch near your launch date, not 1970, to get the full lifespan. Twitter's epoch is in 2010, Discord's is 2015.
  • 10 bits of machine ID: 1,024 generators.
  • 12 bits of sequence: 4,096 IDs per millisecond per machine, about 4 million per second per machine.

Each generator is a few lines of code with no network call. IDs are roughly time-ordered across machines (they sort by millisecond first, then by machine within the same millisecond) and strictly ordered within one machine.

Variants move the bits around. Instagram used 41 bits of time, 13 bits of logical shard ID, and 10 bits of per-shard sequence, generated inside Postgres with a PL/pgSQL function, so the ID itself tells you which shard holds the row. Sonyflake uses 10 ms ticks to stretch the lifespan. The design is the same: time, then where, then a counter.

Predict the outputPython

With a 12-bit sequence field, how many IDs can one Snowflake generator issue per second at most?

print((1 << 12) * 1000)
Need a nudge? Hints walk you through it.

Here is a working generator. The clock is a fake one you control, so you can see sequence rollover and a clock that jumps backwards.

Pythonsnowflake.py
EPOCH_MS = 1_704_067_200_000 # our custom epoch: 2024-01-01T00:00:00Z TIME_BITS, MACHINE_BITS, SEQ_BITS = 41, 10, 12MAX_SEQ = (1 << SEQ_BITS) - 1 # 4095 class ClockMovedBackwards(Exception): pass class Snowflake: def __init__(self, machine_id, clock): assert 0 <= machine_id < (1 << MACHINE_BITS) self.machine_id = machine_id self.clock = clock # a function returning Unix time in ms self.last_ms = -1 self.seq = 0 def next_id(self): now = self.clock() if now < self.last_ms: raise ClockMovedBackwards(f"clock went back {self.last_ms - now} ms") if now == self.last_ms: self.seq = (self.seq + 1) & MAX_SEQ if self.seq == 0: # 4,096 IDs used this ms: wait for the next one while now <= self.last_ms: now = self.clock() else: self.seq = 0 self.last_ms = now return ((now - EPOCH_MS) << (MACHINE_BITS + SEQ_BITS)) | (self.machine_id << SEQ_BITS) | self.seq def decode(id_): return { "unix_ms": (id_ >> (MACHINE_BITS + SEQ_BITS)) + EPOCH_MS, "machine": (id_ >> SEQ_BITS) & ((1 << MACHINE_BITS) - 1), "seq": id_ & MAX_SEQ, } # A fake clock we control, so the output is the same every runfake_now = [1_760_000_000_000]gen = Snowflake(machine_id=37, clock=lambda: fake_now[0]) a = gen.next_id()b = gen.next_id() # same millisecond, so seq goes upfake_now[0] += 1c = gen.next_id() # next millisecond, seq resets for x in (a, b, c): print(x, decode(x))print("sorted by time:", a < b < c)print("fits in signed 64 bits:", c < 2**63) fake_now[0] -= 5 # NTP steps the clock back 5 mstry: gen.next_id()except ClockMovedBackwards as e: print("refused:", e) years = (2**41) / 1000 / 60 / 60 / 24 / 365.25print(f"41 bits of ms last {years:.1f} years")
Output
Press Run (⌘ Enter) to see what happens.

Notice that decoding needs no lookup. Any service holding an ID can tell when it was created, which is handy for debugging and for routing time-range queries.

Assigning machine IDs

The sequence handles uniqueness within one generator. Uniqueness across generators depends entirely on no two running generators sharing a machine ID. If two pods both think they are machine 37, they will produce identical IDs in the same millisecond, and nothing will warn you until a primary key insert fails or, worse, two records silently merge downstream.

Options, from simplest:

  • Static config: each server gets its ID in a config file. Fine for a fixed fleet, fragile with autoscaling.
  • Derived from the environment: a Kubernetes StatefulSet gives pods stable ordinals (idgen-0, idgen-1), which map neatly to machine IDs.
  • Leased from a coordinator: at startup the process claims a free ID in etcd or ZooKeeper with a lease that expires if it dies, and renews it while running. The next lesson explains why leases need care when a process pauses.

When the clock goes backwards

Snowflake trusts the wall clock, and wall clocks move. NTP can step the clock backwards to correct drift, a VM can resume from a snapshot, and leap-second handling varies. If the clock goes back 5 ms and you keep generating, you reuse timestamps you already issued, and with the same sequence values you can produce duplicate IDs.

The standard responses:

  • Refuse, as the code above does and as Twitter's original did: throw and let the caller retry. Safe, but the service is down until time catches up.
  • Wait if the jump is small (a few ms): sleep until the clock passes last_ms.
  • Keep using last_ms and borrow from the sequence until the real clock catches up. This is what some libraries do. It keeps running, but timestamps drift from real time.

Configure NTP (chrony) to slew (speed up or slow down gradually) rather than step on running servers. Inside one process you can also measure elapsed time with a monotonic clock (time.monotonic() in Python, performance.now() in JavaScript), which never goes backwards, though it has no meaning across machines or restarts.

A pod pause and a duplicate machine ID
Pod AetcdPod Bclaim machine ID 37, lease 10sgrantedlong GC pause, 15sclaim a free machine ID37 is free (lease expired)wakes, keeps issuing with ID 37

Pod A owns ID 37 while it keeps renewing the lease.

1/6

JavaScript and 64-bit IDs

Here is a bug that reaches production regularly. JavaScript numbers are 64-bit floats, exact only up to 2^53 - 1 (Number.MAX_SAFE_INTEGER). A Snowflake ID is up to 2^63. Send one as a JSON number and JSON.parse silently rounds it to a different ID. Twitter's API returns both id and id_str for exactly this reason.

TypeScriptbig_ids.ts
const id: bigint = 234599166771351553n; // a Snowflake ID from the Python run const asNumber: number = Number(id);console.log("as bigint:", id.toString());console.log("as number:", asNumber.toString());console.log("safe integer?", Number.isSafeInteger(asNumber)); // What JSON.parse does to the same ID sent as a numberconst parsed = JSON.parse('{"id": 234599166771351553}') as { id: number };console.log("JSON.parse:", parsed.id); // The fix: send it as a string, keep it as a string (or BigInt)const fixed = JSON.parse('{"id": "234599166771351553"}') as { id: string };console.log("as string:", fixed.id, "->", BigInt(fixed.id) === id); // Decode the timestamp with BigInt shiftsconst EPOCH_MS = 1704067200000n;const unixMs = (id >> 22n) + EPOCH_MS;console.log("created at:", new Date(Number(unixMs)).toISOString());
Output
Press Run (⌘ Enter) to see what happens.

Rule: in any API that a browser consumes, serialize 64-bit IDs as strings.

Predict the outputJavaScript

What does this print?

console.log(2 ** 53 + 1 === 2 ** 53)
Need a nudge? Hints walk you through it.

Public IDs vs internal keys

Many teams separate the two jobs:

  • Internal primary key: a BIGINT sequence or Snowflake. Small, sequential, fast joins. Never shown to users.
  • Public ID: a UUIDv4, a UUIDv7, or a random token with a prefix like Stripe's cus_... and pi_.... Prefixes make logs and support tickets readable and catch mistakes such as passing a customer ID where a payment ID was expected.

For short IDs in URLs, base62-encode a number or random bytes, as Design a URL Shortener does for its short keys later in the course. Seven base62 characters hold about 3.5 trillion values. If the input is a sequential counter, the short code is still guessable, so shuffle or encrypt the number first when enumeration matters.

Match the pairs0/4 matched

Match each requirement to the ID scheme that fits it best.

Choose an item, then its match on the other side.
Quick check
A team switches the primary key of a 2-billion-row, insert-heavy table from BIGINT to UUIDv4. Insert throughput drops sharply. What is the main cause?
Need a nudge? A hint rules out a wrong answer.
Put it in order4 steps

Order the fields of a Snowflake ID from the most significant bits to the least.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
UUIDv4
A 128-bit ID with 122 random bits. No coordination needed, but random inserts hurt B-tree locality.
UUIDv7
A 128-bit ID from RFC 9562 that starts with a 48-bit Unix millisecond timestamp, so it sorts by creation time.
ULID
A 128-bit ID with 48 bits of time and 80 random bits, written as 26 sortable base32 characters.
Snowflake ID
A 64-bit ID made of a timestamp, a machine ID, and a per-millisecond sequence, generated locally on each node.
custom epoch
The start time a Snowflake timestamp counts from, chosen near launch so the 41-bit field lasts about 69 years.
IDOR
Insecure direct object reference: serving an object by its ID without checking that the caller may see it.
monotonic clock
A clock that only moves forward within a process. Good for measuring intervals, meaningless across machines.