Distributed patterns and operations

Unique ID generation and Snowflake

Choose between auto-increment, UUIDs, ticket ranges and Snowflake ids, and reason about bit budgets, clock problems and index locality.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A marketplace keeps its orders in one PostgreSQL database. The primary key is a BIGSERIAL column, so the database hands out 1, 2, 3 and so on, and that has worked for six years. Then the table grows too large for one machine and the team splits it across eight shards.

Each shard now has its own sequence, and each one carries on counting from the same place. Within a day there are eight different orders with the same number. Order ids are in URLs, in emails to customers and in the payment provider’s records, and each of those references now points at eight things.

The first fix people reach for is to stagger the sequences: shard 1 issues 1, 9, 17 and shard 2 issues 2, 10, 18. MySQL has settings for this (auto_increment_increment and auto_increment_offset). It works until you add a ninth shard, when every step is wrong. The second fix is one central sequence that every shard calls, which restores uniqueness and puts a network round trip and a single point of failure in front of every insert.

The underlying issue is that auto-increment is a shared counter, and a shared counter needs coordination between everyone who writes. The techniques in this lesson get unique ids with little or no coordination per id. Before choosing one, decide which of these properties you need beyond uniqueness:

  • Compact. A 64-bit integer is half the size of a UUID in every index and foreign key.
  • Sortable by time. Useful for pagination, and it matters for index performance.
  • No coordination per id, so creating an id never waits on the network.
  • Hard to guess, if ids appear in URLs and you do not want outsiders counting your orders.

No scheme gives you all four.

Random ids: UUID v4

A version 4 UUID is 128 bits, of which 122 are random. Any process can generate one with no coordination, and collisions are not a practical concern: you would need about 2.7 x 1018 ids for an even chance of a single collision.

The cost shows up in the database. A B-tree index keeps keys in sorted order, so random keys land on random pages. Once the index is larger than memory, most inserts touch a page that is not cached, and page splits happen all over the tree. In MySQL’s InnoDB the effect is larger, because the table itself is stored in primary key order and every secondary index carries a copy of the primary key. A UUID also takes 16 bytes, or 36 characters if someone stores it as text.

Time-ordered UUIDs: v7

UUID version 7, standardised in RFC 9562 in 2024, keeps the 128-bit format and changes the layout. The first 48 bits are a Unix timestamp in milliseconds, and 74 of the remaining bits are random. Later ids sort later, so inserts go to the right-hand edge of the index, and there is still no coordination. PostgreSQL 18 added a built-in uuidv7() function, and most languages have a library.

Two cautions: ids created in the same millisecond are not ordered among themselves unless the generator adds a counter, and anyone who sees a v7 id can read when the row was created.

Ticket servers and ranges

If you want small numeric ids, keep a counter but make it cheap to use. Flickr described this in 2010: a dedicated MySQL “ticket server” whose only job is to hand out the next number, run as a pair for availability, with one server issuing odd numbers and the other even.

To avoid a network call per id, application servers lease a block at a time.

Leasing blocks of ids from a ticket server4 components: App server A, App server B, Ticket server, Orders table. Connections: App server A to Ticket server (lease a block); App server B to Ticket server (lease a block); App server A to Orders table (insert); App server B to Orders table (insert).App server AApp server BTicket serverone durable counternext = 1Orders tableshardedlease a blocklease a blockinsertinsert

Step 1 of 7

Two app servers create orders in a sharded database, and every order needs an id that no other server will ever use. A small ticket server holds a single counter, which starts at 1.

Read the steps as text
  1. Two app servers create orders in a sharded database, and every order needs an id that no other server will ever use. A small ticket server holds a single counter, which starts at 1.
  2. Asking the ticket server for every id would put a network call in front of every insert. Instead, server A asks for a block of 1,000. The ticket server moves its counter from 1 to 1,001 in one atomic update and replies with the range.
  3. Server B does the same and receives 1,001 to 2,000. The two ranges cannot overlap, because the counter only ever moves forward.
  4. Each server now hands out ids from memory with no network call. A issues 1, 2 and 3 while B issues 1,001 and 1,002. The ids are unique, but they no longer follow time: order 1,001 can be older than order 3.
  5. Server A crashes after using 37 ids. The other 963 in its block are gone for good, because nobody recorded how far it had got.
  6. When A restarts it leases a fresh block, 2,001 to 3,000. The sequence now has a gap, and that is fine. A gap wastes a few numbers, while a duplicate would corrupt data.
  7. Range leasing gives compact numeric ids and touches the ticket server once per thousand inserts. The price is ids that are only roughly ordered, gaps after crashes, and one counter that must be durable and highly available.
Leasing blocks of ids from a ticket server

A short ticket server outage goes unnoticed while app servers still have ids in hand. The costs are rough ordering, gaps after crashes, and one more stateful service to keep durable. The URL shortener case study uses this approach, because short codes need small numbers.

Snowflake

In 2010 Twitter was planning to move tweets from MySQL to Cassandra, which has no auto-increment, and needed ids that fitted in 64 bits, sorted roughly by time, and could be generated at tens of thousands per second with no central counter. Its answer, Snowflake, packs three fields into one integer.

The 64 bits of a Snowflake id, highest bits first7 components: Sign bit, Timestamp, Machine id, Sequence, About 69.7 years, 1,024 generators, 4,096 ids per ms. Connections: Timestamp to About 69.7 years; Machine id to 1,024 generators; Sequence to 4,096 ids per ms.Sign bit1 bit, always 0Timestamp41 bits, ms since epochMachine id10 bitsSequence12 bits, resets each msAbout69.7 years2^41 milliseconds1,024generators2^10 values4,096 idsper ms2^12, per generator
The 64 bits of a Snowflake id, highest bits first

The capacity follows from the bit widths:

Field Bits Capacity
Timestamp, ms since a custom epoch 41 241 ms, about 69.7 years
Machine id 10 1,024 generators
Sequence 12 4,096 ids per ms per generator

One generator can issue about 4.1 million ids per second. If it uses all 4,096 sequence values in one millisecond, it waits for the next. The epoch is custom so that the 69.7 years start at the service’s launch and not in 1970, and the top bit stays zero so that the id is positive in languages with signed integers.

Because the timestamp sits in the high bits, sorting by id sorts by time, though only roughly: ids from different machines in the same millisecond are ordered by machine id, and clocks never agree exactly.

One trap: JavaScript numbers are exact only up to 253, so a browser silently rounds a 64-bit id parsed from JSON. Send ids as strings in APIs.

Clocks that go backwards

Snowflake’s uniqueness rests on each generator’s clock never repeating a millisecond, and clocks do not promise that. NTP can step a clock backwards to correct drift, a virtual machine can be paused and restored, and a leap second can make a second repeat. If the clock goes back 200 ms and the generator carries on, it issues timestamps it has already used with a sequence that restarts from zero. Those are duplicate ids.

The standard defences are:

  • Remember the last timestamp used. If the clock reads earlier than that, do not generate. Wait out a small step, and fail and alert on a large one. The original Snowflake refused requests until the clock caught up.
  • Survive restarts. A restarted process has forgotten its last timestamp. Persist it periodically, or delay start-up for longer than any plausible clock step.
  • Keep clocks disciplined. Configure time synchronisation to slew, which adjusts the clock gradually, in preference to stepping, and alert on drift.

Skew between machines does not cause duplicates, because their machine ids differ. It only weakens ordering: an id from a machine whose clock is 50 ms behind sorts earlier than it should.

Assigning machine ids

Two live generators with the same machine id will produce duplicates silently. This is the one piece of coordination that Snowflake keeps, moved from every id to once per process start. You can claim an id in ZooKeeper or etcd at start-up (the original Snowflake used ZooKeeper), lease one from a database table, or derive it from something the platform already guarantees to be unique, such as a Kubernetes StatefulSet ordinal. Taking the low bits of an IP address is common and risky, because uniqueness then depends on the network layout.

Sortable ids: the benefit and the cost

Auto-increment, UUID v7 and Snowflake ids all insert at the right-hand edge of a B-tree. That keeps the active pages in memory, and it lets you paginate with WHERE id > last_seen.

They have two costs. They leak information: creation time, and with plain sequential ids, your volume. And in stores that partition by ranges of the key, such as HBase, Spanner and CockroachDB, ever-increasing keys send every insert to the last range and create a write hotspot. Those systems recommend keys with a hashed or random prefix.

When to choose each

Scheme Size and order Choose it when
Auto-increment 64-bit, strict order One database issues every id, and exposing counts is acceptable
UUID v4 128-bit, no order Ids must be hard to guess, clients create them offline, or the store range-partitions by key
UUID v7 128-bit, ordered to the ms A sound default for new tables with no extra infrastructure
Ticket ranges 64-bit, rough order You need short numbers, as in short codes or invoice numbers
Snowflake 64-bit, ordered to the ms Very high write rates with 64-bit keys, and you can manage machine ids and clocks

Do not choose Snowflake by reflex. It brings clock monitoring and machine id assignment, and UUID v7 avoids both if 16-byte keys are acceptable. A hard-to-guess id is also not access control. The unique ID generator case study designs a Snowflake-style service end to end.

In the interview

Ids come up in almost every design, and “the database auto-increments it” is a weak answer once you have said the data is sharded.

A strong answer starts from requirements: “I need ids that are unique across shards, fit in 64 bits and sort by time, so I would use a Snowflake-style id: 41 bits of milliseconds, 10 bits of machine id and 12 bits of sequence, about 4,000 ids per millisecond per node for 69 years.” Then name the two operational risks, clocks going backwards and duplicate machine ids, and how you handle each. If the system does not need 64-bit keys, say that UUID v7 gives the same ordering with nothing to operate.

Key takeaways

  • Auto-increment is a shared counter, so it stops working as soon as more than one database issues ids.
  • UUID v4 needs no coordination but is 128 bits and random, which scatters inserts across a B-tree index.
  • UUID v7 puts a millisecond timestamp first, so ids sort by creation time and inserts stay at the right-hand edge of the index.
  • A ticket server leases blocks of numbers, which gives compact ids for one network call per block and leaves gaps after crashes.
  • Snowflake packs a 41-bit millisecond timestamp, a 10-bit machine id and a 12-bit sequence into 64 bits: about 69.7 years, 1,024 generators and 4,096 ids per millisecond each.
  • Snowflake must refuse to issue ids when its clock goes backwards, and every generator needs a machine id that no other live generator has.
  • Time-ordered ids help B-tree indexes, reveal creation time, and create write hotspots in stores that range-partition by key.

Check yourself

1. A Snowflake generator with a 12-bit sequence is asked for 10,000 ids within the same millisecond. What should it do?
2. NTP steps a generator's clock back by 300 ms. The generator ignores this and carries on. What is the risk?
3. A table with a random UUID v4 primary key has grown much larger than memory, and inserts have slowed down. What is the main cause?
4. An app server leases ids 5,001 to 6,000 from a ticket server and crashes after using 40 of them. What happens to the other 960?
5. A team moves a write-heavy table to a store that partitions data by ranges of the primary key, and keeps Snowflake ids as the key. What should they expect?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What are the fields of a Snowflake id?

One unused sign bit, a 41-bit millisecond timestamp from a custom epoch, a 10-bit machine id and a 12-bit sequence, 64 bits in all.

What capacity do Snowflake's bit widths give?

About 69.7 years of timestamps, 1,024 generators, and 4,096 ids per millisecond per generator (about 4.1 million per second each).

What should a Snowflake generator do when its clock goes backwards?

Compare the clock with the last timestamp it used and refuse to issue ids until the clock has passed it: wait for a small step, fail and alert for a large one.

How does UUID v7 differ from UUID v4?

Both are 128 bits. Version 4 has 122 random bits. Version 7 starts with a 48-bit Unix millisecond timestamp followed by 74 random bits, so ids sort by creation time.

How does a ticket server avoid a network call per id?

Each app server leases a block of ids, for example 1,000, and hands them out from memory. Unused ids in a block are lost if the server crashes.

Why can a 64-bit id break in a browser?

JavaScript numbers are exact only up to 2^53, so larger ids are silently rounded when parsed from JSON. Send 64-bit ids as strings.

Review the deck