Distributed ID Generation: Sequences, UUIDv7, Snowflake and ULID
A team splits its orders table across 16 Postgres shards. Each shard keeps its bigserial primary key. Within a week, support has two customers holding order 1,000,457, from different shards, and the refund tool has refunded the wrong one. The quick fix is to switch new orders to random UUIDv4 keys.
That fixes uniqueness and creates a new problem. The orders index grows past the buffer cache, every insert now lands on a random leaf page, the cache hit ratio for the index falls from 99% to about 85%, and insert p99 triples. The team has learned the two halves of the ID problem the hard way: an ID must be unique without asking a single central counter, and it should still arrive in roughly increasing order so the database can append instead of scatter.
This article covers the options, from database sequences to Snowflake IDs and UUIDv7, and how to size one for your own throughput.
What distributed ID generation is
An ID generator hands out identifiers that are unique across every machine that creates records, now and for the lifetime of the system. Every design trades off five requirements:
- Uniqueness: no two records ever get the same ID, including after crashes, restarts and clock problems.
- Ordering: none, roughly time-ordered (k-sorted, close in time means close in value), or strictly monotonic.
- Size: 64 bits fits a
bigintcolumn and a CPU register; 128 bits (UUID) doubles index size and every foreign key. - Coordination: none, one-time configuration (a worker number), or a network call per ID or per batch.
- Opacity: whether the ID leaks business volume (sequential order numbers), creation time, or is guessable.
How it works
Auto-increment and sequences
A single database sequence is the simplest generator: compact, strictly increasing on one node, and free. Its limits show up at scale:
- One writer. Every ID comes from one primary. With sharding, each shard’s sequence collides with the others.
- Not gapless. Postgres and MySQL never reuse a sequence value after a rollback, and Postgres sequences with
CACHEskip values on crash. Do not rely on them for legally gapless invoice numbers; those need a separate counter row updated under a lock. - Leaks volume. Order 1,000,457 tells competitors how many orders you have taken, and sequential IDs invite enumeration of other customers’ records if authorization is weak.
Multi-primary MySQL setups sometimes interleave sequences with auto_increment_increment and auto_increment_offset (server 1 issues 1, 3, 5; server 2 issues 2, 4, 6). That works until you need a third server.
Ticket servers
Flickr described its ticket servers in 2010: dedicated MySQL instances whose only job is a single-row table with an auto-increment column. A client runs REPLACE INTO tickets (stub) VALUES ('a') followed by SELECT LAST_INSERT_ID(). Two servers, one issuing odd and one even numbers, avoid a single point of failure.
The costs are a network round trip per ID and a central dependency on the write path. Batching fixes the first.
Sequence ranges (hi/lo)
Instead of one ID per call, a client reserves a block. It atomically increments a central counter by 1,000 and gets the range 57,000 to 57,999, then hands those out from memory. Hibernate’s hi/lo and pooled optimizers work this way, and so does a Postgres sequence with INCREMENT BY 1000.
Coordination drops by a factor of the block size: at 100,000 IDs per second with blocks of 1,000, the central counter sees 100 increments per second. IDs are unique and 64-bit, but only roughly ordered across nodes (node A may be issuing 57,xxx while node B issues 58,xxx), and a crashed node wastes the rest of its block.
UUIDv4
A version 4 UUID has 122 random bits and needs no coordination at all. Collisions are not a practical concern: by the birthday bound, generating a trillion (10^12) UUIDv4 values gives a collision probability of roughly 10^24 / 2^123, about 10^-13.
The problem is locality. Random keys spread inserts uniformly across the whole B-tree, so the index’s entire leaf level becomes the working set, and page splits leave pages around 70% full. In InnoDB, where the primary key is the clustered index, the table itself fragments the same way, as described in indexing internals. On an LSM engine random keys hurt less, but range scans by creation time are impossible.
flowchart LR subgraph RAND["UUIDv4: random keys"] I1["insert"] --> P1["leaf 17"] I2["insert"] --> P2["leaf 90,412"] I3["insert"] --> P3["leaf 3,208"] N1["every leaf is hot<br/>cache misses, half-full pages"] end subgraph ORD["UUIDv7 or Snowflake: time-ordered"] J1["insert"] --> R1["rightmost leaf"] J2["insert"] --> R1 J3["insert"] --> R1 N2["few hot pages<br/>stay cached, pages fill up"] end style P1 fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style P2 fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style P3 fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style N1 fill:#FAEEDA,stroke:#854F0B,color:#633806 style R1 fill:#E1F5EE,stroke:#0F6E56,color:#085041 style N2 fill:#E1F5EE,stroke:#0F6E56,color:#085041
UUIDv7
RFC 9562, published in May 2024 and replacing RFC 4122, standardised UUID version 7. Its 128 bits are laid out as:
| Bits | Field |
|---|---|
| 48 | Unix timestamp in milliseconds |
| 4 | Version (7) |
| 12 | rand_a: random, or a sub-millisecond fraction or counter for monotonicity |
| 2 | Variant |
| 62 | rand_b: random |
That gives time ordering at millisecond granularity plus 74 bits of randomness, with no coordination. It drops into any uuid column, so it is the easiest upgrade from UUIDv4. Postgres 18 added a built-in uuidv7() function; most languages have libraries. The trade-offs are 16 bytes instead of 8, and the timestamp is readable by anyone holding the ID.
Snowflake IDs
Twitter announced Snowflake in 2010: a 64-bit ID built from a timestamp, a worker number and a per-worker sequence. The layout:
flowchart LR S["1 bit<br/>sign, always 0"] --- T["41 bits<br/>ms since custom epoch"] --- W["10 bits<br/>worker ID<br/>1,024 workers"] --- Q["12 bits<br/>sequence<br/>4,096 per ms"] style S fill:#F1EFE8,stroke:#888780,color:#444441 style T fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style W fill:#FAEEDA,stroke:#854F0B,color:#633806 style Q fill:#E1F5EE,stroke:#0F6E56,color:#085041
Each worker generates IDs locally:
- Read the current time in milliseconds since the epoch.
- If it equals the last timestamp, increment the sequence. If the sequence overflows past 4,095, spin until the next millisecond.
- If it is a new millisecond, reset the sequence to 0.
- Return
(timestamp << 22) | (worker_id << 12) | sequence.
The bit math:
- Lifetime: 2^41 ms = 2,199,023,255,552 ms. Divide by 1,000 x 86,400 x 365.25 and you get about 69.7 years. Twitter’s epoch is in November 2010, so its IDs run out around 2080. Choose your own epoch close to launch day, never 1970, or you waste 40 years of range.
- Throughput: 4,096 IDs per ms per worker is about 4.1 million per second per worker, and 1,024 workers.
- Sign bit: kept at 0 so the ID is positive in signed 64-bit types such as Java
longand Postgresbigint.
Worker IDs are the only coordination. Assign them from configuration, from a Kubernetes StatefulSet ordinal, or by acquiring a lease in etcd or ZooKeeper at startup. Two live processes with the same worker ID will generate duplicates, so treat the assignment like any other lease, with the fencing concerns covered in leader election, leases and locks.
Variants are common. Discord’s public API uses Snowflake-format IDs with an epoch at the start of 2015. Instagram described in 2012 an ID made of 41 bits of milliseconds, 13 bits of logical shard ID and 10 bits of per-shard sequence, generated inside Postgres by a PL/pgSQL function, so the shard can be read straight from the ID.
ULID and KSUID
ULID is a community specification, not an RFC: 48 bits of millisecond timestamp followed by 80 random bits, written as 26 characters of Crockford base32 that sort lexicographically in time order. Its optional monotonic mode increments the random part for IDs in the same millisecond. Functionally it is very close to UUIDv7, and it fits in a uuid column, but new systems usually prefer the standardised UUIDv7.
KSUID, from Segment, is 160 bits: a 32-bit timestamp in seconds since a custom epoch in May 2014 and 128 random bits, written as 27 base62 characters. Second-level precision means IDs within the same second are not ordered, and at 20 bytes it is larger than a UUID.
MongoDB’s ObjectId is a related design: 12 bytes made of a 4-byte timestamp in seconds, a 5-byte per-process random value and a 3-byte counter.
| Scheme | Bits | Ordered | Coordination | Notes |
|---|---|---|---|---|
| Sequence | 64 | Strict, one node | Central database | Leaks volume, breaks with sharding |
| Hi/lo ranges | 64 | Rough | One call per block | Gaps on crash |
| UUIDv4 | 128 | No | None | Poor B-tree locality |
| UUIDv7 | 128 | By ms | None | RFC 9562, leaks creation time |
| Snowflake | 64 | By ms, k-sorted | Worker ID assignment | Fits bigint, needs clock care |
| ULID | 128 | By ms | None | Base32 text form, not an RFC |
| KSUID | 160 | By second | None | Base62 text form |
Worked example: sizing a 64-bit ID for 100,000 IDs per second
Where it breaks
Clocks move backwards
NTP can step a clock back, a VM can resume on a host with a different clock, and leap seconds have caused rollbacks in the past. If a Snowflake worker reads a timestamp earlier than its last one, it can reissue an ID it already gave out. Defences:
- Never go backwards: keep the last timestamp and use the larger of it and the current time. Small rollbacks then borrow from the future and continue the sequence.
- Wait out small rollbacks: if the clock is behind by a few milliseconds, sleep until it catches up.
- Refuse large ones: if it is behind by more than a threshold, say 100 ms, stop issuing IDs, alert, and let other workers take the traffic.
- Persist a high-water mark across restarts, so a process that reboots with a rolled-back clock cannot reissue old timestamps.
- Configure NTP or chrony to slew rather than step, and use leap-second smearing.
Why physical clocks cannot be trusted for ordering in the first place is covered in time, clocks and ordering.
Time order is not event order
Snowflake and UUIDv7 IDs are only roughly ordered across workers, because each worker’s clock is off by a few milliseconds and IDs from the same millisecond on different workers sort by worker ID. Do not use them to decide which of two concurrent writes happened first, and do not assume a reader who has seen ID X has seen every smaller ID. Cursor pagination over them is fine as long as you accept that late-committing rows can appear behind the cursor; see pagination patterns.
64-bit IDs in JavaScript
JavaScript numbers are doubles, which represent integers exactly only up to 2^53. A 64-bit Snowflake ID parsed as a JSON number silently loses its low bits. Send IDs as strings in JSON APIs, which is why Twitter’s API added id_str fields and Discord’s API returns IDs as strings.
Duplicate worker IDs
Two processes sharing a worker ID generate identical IDs whenever their sequences meet in the same millisecond. Typical causes: a copied config file, a scaled-up deployment that hashed pod names into too few bits, or a lease that expired during a GC pause while the old process kept running. Use leases with expiry and have the process stop issuing IDs when it cannot renew.
IDs are not secrets
Time-ordered and sequential IDs are guessable. Never use an ID as an access token or an unguessable link; generate a separate random token (at least 128 bits from a cryptographic RNG) and enforce authorization on every lookup.
Real-world systems
- Postgres:
bigserialand identity columns backed by sequences;uuidv7()built in from Postgres 18, alongsidegen_random_uuid()for version 4. - MySQL:
AUTO_INCREMENTper table, plusauto_increment_incrementandauto_increment_offsetfor interleaving. - Twitter: Snowflake, announced in 2010, 41-bit timestamp, 10-bit worker, 12-bit sequence.
- Discord: Snowflake-format IDs with a 2015 epoch, returned as strings in its public API.
- Instagram: 64-bit IDs with 41 bits of time, 13 bits of logical shard and 10 bits of sequence, generated in Postgres (2012).
- Flickr: odd and even MySQL ticket servers (2010).
- MongoDB: 12-byte ObjectId with a seconds timestamp, per-process random value and counter.
How to apply it
| Situation | Good default |
|---|---|
| Single database, no sharding planned | Identity column or sequence; expose a separate random public ID if volume must stay private |
| Sharded or multi-region, IDs created in many services, 128 bits acceptable | UUIDv7 |
| Must fit 64 bits (bigint, compact indexes, existing schema) | Snowflake-style with your own epoch and leased worker IDs |
| Central database already in the path, 64-bit, low ops effort | Sequence ranges (hi/lo) |
| Need the shard encoded in the ID for routing | Instagram-style shard bits inside a Snowflake layout |
| Short public codes (URL shortener) | Encode a 64-bit ID in base62, up to 11 characters |
Checklist before shipping a generator:
- Work out lifetime, throughput per worker and worker count with the bit math above.
- Choose an epoch near launch day and document it.
- Decide how worker IDs are assigned and what happens when assignment fails.
- Handle clock rollback explicitly and test it by stepping the clock in a staging environment.
- Send 64-bit IDs as strings to browsers.
- Never treat IDs as secrets.
Interview questions
1. Design an ID generator for 100,000 IDs per second across several regions, with 64-bit IDs that sort roughly by time.
Generate IDs locally in each service process using a Snowflake layout: sign bit 0, 41 bits of milliseconds since a custom epoch (about 69.7 years), 10 bits of worker ID, 12 bits of sequence. 100,000 per second spread over even 10 workers is 10 per ms per worker, far below the 4,096 limit. Worker IDs come from a lease in a coordination service or a StatefulSet ordinal, with region encoded in the top 2 worker bits if useful. Handle clock rollback by never going below the last issued timestamp, waiting out small skew and refusing large skew. No network call per ID means no central bottleneck and no cross-region latency.
2. Why did switching the primary key from bigint to UUIDv4 make inserts slower?
Random keys land on random leaf pages, so instead of appending to the rightmost few pages, each insert touches a different page somewhere in the index. Once the index is larger than memory, many inserts need a disk read first, and random page splits leave pages partly empty, so the index is larger too. In InnoDB the effect is worse because the primary key is the clustered index, so the table rows themselves are scattered and every secondary index stores the 16-byte key. UUIDv7 keeps uniqueness without coordination while restoring append-mostly inserts, and it fits the same uuid column type.
3. A Snowflake worker’s clock jumps back 2 seconds after an NTP correction. What happens and how should the generator respond?
If the generator trusts the clock, it starts issuing timestamps it already used, and with the sequence reset to 0 it reissues IDs that exist, causing duplicates. The generator should remember its last timestamp and detect the rollback. For a few milliseconds, it can wait or keep using the last timestamp with the sequence continuing. For 2 seconds, the safe response is to stop issuing IDs, report unhealthy so traffic moves to other workers, and alert. Persisting the last timestamp prevents the same problem after a restart, and configuring time sync to slew instead of step makes jumps rare.
✅ Key takeaways
- Requirements decide the design: uniqueness, ordering, size, coordination and opacity.
- Sequences are perfect on one node but collide across shards, leak volume and are not gapless.
- Random UUIDv4 keys destroy B-tree locality; time-ordered IDs (UUIDv7, Snowflake, ULID) keep inserts near the right edge of the index.
- UUIDv7 (RFC 9562, 2024) needs no coordination and Postgres 18 generates it natively; Snowflake fits 64 bits but needs worker IDs and clock handling.
- Snowflake math: 41 bits of ms is about 69.7 years from your epoch, 12 sequence bits is 4,096 IDs per ms per worker.
- Handle clock rollback, duplicate worker IDs and JavaScript’s 53-bit integers explicitly, and never use IDs as secrets.
🧠 Check your understanding
0 / 4-
1How long does a 41-bit millisecond timestamp last from its epoch?
2 to the 41 milliseconds is about 2.2 trillion ms, or 69.7 years. 136 years is what a 32-bit timestamp in seconds gives, the KSUID range, which is the tempting mix-up.
-
2A Postgres team needs IDs generated in 30 services without coordination and wants fast B-tree inserts. 128 bits is acceptable. What is the best fit?
UUIDv7 is time-ordered, so inserts stay near the right edge of the index, and it needs no coordination. UUIDv4 also needs no coordination but scatters inserts across the index; Snowflake needs worker ID management.
-
3A Snowflake worker receives 6,000 ID requests within one millisecond. With 12 sequence bits, what should it do?
The sequence allows 4,096 IDs per millisecond; once exhausted, the generator spins until the clock ticks. Wrapping to 0 within the same millisecond would reissue IDs already handed out, creating duplicates.
-
4A web client shows wrong order IDs for some 64-bit Snowflake IDs returned as JSON numbers. Why?
Integers above 2 to the 53 lose precision when parsed into a double, so the low bits change. The fix is to send IDs as strings. Snowflake IDs keep the sign bit at 0, so they are not negative.
Where to go next
- Sharding and partitioning: how IDs interact with shard keys and routing.
- Time, clocks and ordering: why wall clocks drift and what logical clocks offer instead.
- Leader election, leases and locks: assigning worker IDs safely with leases and fencing.
- Design a URL shortener: a capstone that turns 64-bit IDs into short base62 codes.
Finished this lesson?
Mark it complete to track your progress across the roadmap.