Distributed systems · L1Unique ID generation

Unique ID generation

Every row, request and event needs a name that no other has. Learn the main ways to create IDs, and what each one costs your database, your clocks and your security.

L1 Must-knowDistributed systems19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 22 Oct 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

This story is made up, but each part of it is common.

A shop app keeps orders in one PostgreSQL table. The id column is an auto-increment number. It has worked for three years.

The table grows too big, so the team splits it into two shards. Each shard is a copy of the old schema, and each still counts its own IDs. On day one, both shards create order 1,000,001.

Support searches for order 1,000,001 and finds two. A refund goes to the wrong customer. Payment webhooks carry only the order ID, so some payments are marked on the wrong order.

There is a second problem. The order page URL is /orders/1000001. A curious customer changes the number by one and sees a stranger's address. The endpoint did not check who owns the order.

Both bugs come from the same choice: an ID that was only unique inside one database, and easy to guess.

Section 2 of 8

The idea in simple words

An ID names one thing, forever. You use IDs as primary keys. You use them as idempotency keys, so a retried request is not done twice. You often sort by them, and you may use them as shard keys.

A good ID scheme answers four questions. Can many machines create IDs without asking each other? Do IDs sort by time? How big are they? Can outsiders guess them?

The key idea. Pick the ID scheme for the scale you will have, not the scale you have today. Changing it later means changing every table, API and URL that holds an ID.

Section 3 of 8

How it works

Auto-increment and sequences

The database hands out 1, 2, 3 and so on. IDs are small, ordered and easy to read. In PostgreSQL, a sequence never takes a number back, even when the transaction fails. So you will see gaps, and you cannot use a sequence for "gapless" numbers like invoice numbers. 5

The limit is that one database owns the counter. With two databases, you must split the number space. MySQL has two settings for this. auto_increment_increment is the step between values, and auto_increment_offset is the start. 7 Flickr ran two MySQL ticket servers this way. Both used a step of 2. One started at 1 and gave odd IDs, the other started at 2 and gave even IDs. 8 This works, but adding a third server means planning the numbers again.

UUID v4: random

A UUID is 128 bits. Version 4 fills 122 of them with random bits. The other 6 bits mark the version and variant. 1 Any machine can make one, with no coordination.

Random keys have a cost in a B-tree index. RFC 9562 says UUID v4 has "poor database-index locality". 1 Each new key lands on a random page. InnoDB reports that keys inserted in order leave index pages about 15/16 full. Keys inserted in random order leave them between 1/2 and 15/16 full. 9

UUID v7: time first

UUID v7 keeps the UUID format but puts time first. The first 48 bits are the Unix time in milliseconds. Then come the version, 12 random bits, the variant, and 62 more random bits. A generator may put a counter in some of the random bits, to keep order within one millisecond. 1

So new IDs sort after older ones, and new values sit near each other in the index. The RFC says this gives better database-index locality. It says the difference from random inserts "can be one order of magnitude or more". 1 It also says implementations should use v7 instead of the older time-based versions, v1 and v6, if possible. 1

PostgreSQL 18 has a built-in uuidv7() function, next to gen_random_uuid() for v4. 6

Snowflake: 64 bits, built from parts

In 2010, Twitter was replacing many MySQL systems with Cassandra or sharded MySQL. Neither had a built-in way to create unique IDs. Twitter needed tens of thousands of IDs per second, from a highly available service. So it chose an approach with no coordination. 2

Each ID has three parts: a timestamp, a worker number and a sequence number. 2 The README gives the sizes. The time takes 41 bits, in milliseconds from a custom epoch, which lasts 69 years. The machine ID takes 10 bits, for up to 1,024 machines. The sequence takes 12 bits, so it rolls over every 4,096 IDs per machine. 3 That is 63 bits, so the ID fits in a signed 64-bit integer. Worker numbers were chosen at startup through ZooKeeper, or set in a config file. 2

Step through how one ID is built.

Building a Snowflake-style 64-bit IDtime · 41 bits 10 12 ms since epochmachinesequence 1,000 msread from the clock 7fixed 0, 1…+1 each join the bitsseq 0 → 4,194,332,672seq 1 → 4,194,332,673 next ms: 1,001seq 0 → 4,198,526,976✓ later ms, bigger ID clock jumps back to 999wait: no IDs until after 1,001 SeniorPath
  1. The generator reads the clock. It counts milliseconds from its own start date, the epoch. In this example, 1,000 ms have passed. This goes in the top 41 bits.
  2. The machine number goes in the next 10 bits. It is set when the generator starts. Here it is 7. No two running generators may share one.
  3. The last 12 bits are a counter. It starts at 0 and goes up by one for each ID in the same millisecond. That gives 4,096 IDs per millisecond.
  4. Join the parts: time × 2²² + machine × 2¹² + sequence. The first ID is 4,194,332,672. The next one in the same millisecond is one bigger.
  5. One millisecond later, the time part is bigger. Time sits in the top bits, so this ID is bigger than every ID from millisecond 1,000 on this machine.
  6. NTP moves the clock back to 999. New IDs could repeat or go backwards. So the generator refuses to make IDs until the clock passes the last time it used.
Step 1 of 6

IDs from one machine sort by time, because time sits in the top bits. Across machines, the order is only rough. Twitter called its IDs "roughly sortable". 2 The README says they are "k-sorted" within a bound: it promised 1 second and aimed for tens of milliseconds. 3

ULID, in one paragraph

A ULID is 128 bits, like a UUID: a 48-bit millisecond timestamp, then 80 random bits. It is written as 26 characters, not the 36 of a UUID, and the text sorts in time order. The spec says it allows 1.21e+24 unique IDs per millisecond. Within one millisecond, order is not guaranteed. An optional monotonic mode adds one to the random part instead. If that overflows, generation fails. 4 In our view, UUID v7 now gives you most of the same benefits in the standard UUID format.

Clocks can break your IDs

Any time-based ID depends on the wall clock, and wall clocks can jump back. RFC 9562 lists clock rollbacks, leap seconds and counter rollovers as causes of out-of-order IDs. It says generators should check that each new ID is bigger than the last. 1 Snowflake protects itself. If the clock goes back, it refuses to create IDs until the time passes the last time it used. 3 Its README suggests running NTP in a mode that never moves the clock back. 3

Do not hand out guessable IDs

Sequential IDs in URLs invite people to try the next number. OWASP's example of this bug uses a "fairly predictable, perhaps sequential" ID. It is a form of insecure direct object reference. 10 Random IDs make guessing harder, but OWASP says that is "generally not sufficient by itself". 10 The fix is an access check on every request. See authentication and authorization. RFC 9562 also warns: do not assume UUIDs are hard to guess, and never use one as a secret that grants access. 1

How likely is a clash?

For UUID v4, think of 122 random bits. That is about 5.3 × 10^36 possible values. By our own arithmetic, with the standard birthday estimate, you would need about 2.3 × 10^18 IDs before the chance of even one clash reaches about 40%. RFC 9562 itself gives no numbers. It says true global uniqueness cannot be guaranteed without shared knowledge. It asks you to weigh what a clash would cost your application. 1 Our view: in practice, a clash is far more likely to come from a bug, like a copied seed or a reused machine number, than from bad luck.

Section 4 of 8

Trade-offs

SchemeNeeds coordination?Sorts by time?SizeIndex-friendly?
Auto-incrementYes One database owns the counter.Yes Small: one integer column.Yes Inserts go to the end.
Ticket servers (odd and even)A little: you plan the offsets. 8Only roughly. The two servers drift apart. 864 bits. 8Yes
UUID v4No No 128 bits. 1No Poor locality. 1
UUID v7No Yes , by millisecond. 1128 bits.Yes 1
Snowflake-styleOnly to assign machine IDs. 2Yes , roughly. 364 bits. 3Yes
ULIDNo Yes , by millisecond. 4128 bits, 26 characters. 4Yes

Simple rule: one database and private IDs? Auto-increment is fine. Many writers, or IDs created on clients? Use UUID v7. Need 64-bit IDs at very high rates? Use a Snowflake-style generator, and treat machine IDs and clocks as part of the design.

Section 5 of 8

At work: how a senior uses this

  • Ask early: "Will this table ever live on more than one database?" If yes, do not depend on auto-increment.
  • Separate the internal key from the public ID if you must. A table can keep a small integer key and also store a random public ID for URLs.
  • Never let an ID replace an authorization check. Test that user A cannot read user B's object by changing the ID.
  • For Snowflake-style IDs, write down how machine IDs are assigned and freed. Two generators with the same machine ID can create the same IDs.
  • Alert when an ID generator refuses to work because of the clock. It means NTP or the host has a problem.
  • Use 64-bit integer columns, or the database's UUID type. Do not store UUIDs as long strings without a reason.
  • Never promise gapless IDs from a sequence. If finance needs gapless numbers, design that separately.
Section 6 of 8

With AI

What to ask the agent

"List every table in this schema with its primary key type. For each one, say whether it would still be unique if we split the table across two databases."

"Find every API route that takes an ID from the URL or body. For each, show where the code checks that the caller may access that object. Flag any route without such a check."

"Write a test for our ID generator. Make 1 million IDs on 8 threads, check that none repeat, and check that IDs from one thread always go up. Then move the fake clock back by 5 ms and show what happens."

What to check yourself

  • The UUID version the agent's code produces is the one you want. Check the library docs, and do not assume.
  • Any bit layout adds up to 64 or fewer bits, and the time part lasts long enough from your chosen epoch.
  • The agent did not treat random IDs as security. Every object access still has an owner check.
  • Generated IDs are not used as the only sort key across machines when exact order matters.
  • Database functions, like uuidv7(), exist in the version you run in production.
Section 7 of 8

Check yourself

1. You split an orders table over two MySQL shards. Both still use AUTO_INCREMENT with default settings. What happens?

Show answer

Both shards start at 1, so two different orders get the same ID. Each server counts on its own. You must give them different offsets, or generate IDs outside the databases.

2. Why can random UUID v4 primary keys slow down inserts into a large B-tree index?

Show answer

Each new key lands on a random page, so the index loses locality and pages end up less full. RFC 9562 says UUID v4 has poor database-index locality. InnoDB says random inserts leave pages 1/2 to 15/16 full.

3. In a Snowflake-style ID, why do IDs from one machine sort by time?

Show answer

Because the timestamp is in the top bits, so a later millisecond always gives a bigger number. The time sits above the machine and the sequence bits. Any later millisecond beats any value in the lower bits.

4. Your order page URL is /orders/10452, using an auto-increment ID. What is the main risk?

Show answer

Someone can try 10451, 10453 and so on. If the server does not check ownership, they see other people's orders. Sequential IDs are easy to guess. The real fix is an authorization check on every request. Random IDs only make guessing harder.

5. A Snowflake-style generator sees that the clock moved back by 2 ms. What should it do?

Show answer

Refuse to create IDs until the clock passes the last time it used. An older time could repeat earlier IDs or break the order. Twitter's Snowflake refuses until the time is after the last one it used.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 10 sources and related lessons
  1. K. Davis, B. Peabody, P. Leach, RFC 9562, “Universally Unique IDentifiers (UUIDs)”, IETF, May 2024 (opens in a new tab)
    The UUID standard. Section 5.4 is UUID v4 (random), section 5.7 is UUID v7 (time-ordered), section 6.2 covers clocks and counters, section 8 covers security.
  2. Twitter Engineering, “Announcing Snowflake”, 1 June 2010 (archived copy on archive.org, because blog.x.com blocks automated readers) (opens in a new tab)
    Why Twitter needed a new ID service when it moved to Cassandra and sharded MySQL, and the three parts of each ID.
  3. Twitter, snowflake repository README (snowflake-2010 branch), GitHub (opens in a new tab)
    The requirements, the 41 + 10 + 12 bit layout, and how it handles a clock that runs backwards.
  4. ULID specification, GitHub (ulid/spec) (opens in a new tab)
    The ULID layout, its text encoding, and the optional monotonic rule for IDs made in the same millisecond.
  5. PostgreSQL documentation: Sequence Manipulation Functions (opens in a new tab)
    Why values from nextval are not given back when a transaction aborts, so sequences can have gaps.
  6. PostgreSQL 18 documentation: UUID Functions (opens in a new tab)
    The built-in gen_random_uuid, uuidv4 and uuidv7 functions.
  7. MySQL 8.4 Reference Manual: Replication Source Options and Variables (auto_increment_increment, auto_increment_offset) (opens in a new tab)
    How the two settings control the step and the start of AUTO_INCREMENT values, with examples.
  8. Flickr Engineering, “Ticket Servers: Distributed Unique Primary Keys on the Cheap” (February 2010) (opens in a new tab)
    Two MySQL servers that hand out IDs, one odd and one even.
  9. MySQL 8.4 Reference Manual: The Physical Structure of an InnoDB Index (opens in a new tab)
    How full index pages get when keys arrive in order, and when they arrive in random order.
  10. OWASP Cheat Sheet Series, Authorization Cheat Sheet (opens in a new tab)
    Predictable IDs in URLs, insecure direct object references, and why random IDs alone are not enough.

Case studies: Instagram: Making sortable 64-bit IDs inside sharded Postgres · Pinterest: Sharding MySQL with IDs that say where data lives

Related: Time, clocks and ordering · B-tree vs LSM-tree · Sharding and consistent hashing · Idempotency, retries and timeouts · Authentication and authorization

Before this: time, clocks and ordering. Related: B-tree vs LSM-tree for why key order matters, sharding for shard keys, and idempotency and retries for idempotency keys.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper