Summary#
Every row, message, order and event needs an identifier that no other one shares. On one database, an auto-increment column does this for free. Once many servers create records at once, possibly in several regions, you need a scheme that stays unique without every server asking a single counter for permission. There are three families. Central counters, such as a database sequence, a ticket server or Redis INCR, give small, dense, ordered numbers, but every ID depends on one service; handing out blocks of 1,000 IDs at a time removes most of that cost. Random IDs, such as UUID version 4, need no coordination at all, because 122 random bits make collisions astronomically unlikely, but they are 128 bits long and scatter inserts across a B-tree index. Time-ordered IDs put a timestamp first: Twitter's Snowflake packs a 41-bit millisecond timestamp, a 10-bit machine ID and a 12-bit sequence into 64 bits, allowing 4,096 IDs per millisecond per machine; UUID version 7, ULID and KSUID do the same in 128 to 160 bits with random bits instead of a machine ID. Time-ordered IDs sort roughly by creation time and keep index inserts local, but they depend on clocks, so a generator must handle the clock going backwards. Pick by the properties you need: uniqueness always; sortability if you page or index by ID; compactness if IDs appear in URLs or 64-bit columns; and no coordination if writers are many and spread out.
Why It Exists#
A single database server can number its rows 1, 2, 3, and so on, because one process owns the counter. Modern systems break that assumption in several ways:
- Many writers. Hundreds of application servers create orders at the same moment. If they all ask one database for the next number, that database becomes a bottleneck and a single point of failure.
- Many databases. Data is sharded across 64 databases. Each has its own auto-increment counter, so shard 3's order 1001 and shard 9's order 1001 collide when they meet in a data warehouse, a cache or an API.
- Many regions. A user in Europe and a user in Asia create posts at the same time, in data centres 200 ms apart. A cross-region round trip per ID would add that latency to every write.
- IDs before the database. A mobile app working offline, or a service that publishes an event before writing to its database, must create the ID itself.
- IDs as keys elsewhere. The ID becomes a cache key, a Kafka message key, a URL path and an S3 object name, so it must be stable and unique across all of them.
At the same time, IDs carry quiet requirements. They become primary keys, so their format affects index performance. They appear in URLs, so length and readability matter. They are often sorted, so being roughly time-ordered makes "the 20 newest posts" an index range scan. And they are seen by users, so they may leak information, such as how many orders a shop takes per day, if they are sequential.
Unique ID generation is the problem of meeting these requirements together: unique everywhere, without a central bottleneck, as compact and as ordered as the use case needs.
How It Works#
Requirements (unique, sortable, compact)#
Before choosing a scheme, decide which of these properties matter. They pull against each other, and no scheme has all of them at full strength.
1. Unique. Two different entities must never get the same ID, within the scope that matters: one table, one service, or globally across every system that will ever see the ID. Uniqueness can be guaranteed, as with a counter, or probabilistic, as with random IDs, where a collision is possible but so unlikely that it is ignored. Probabilistic uniqueness is fine if the probability is far below the rate of other failures, such as hardware corrupting data. A database UNIQUE constraint can catch the rare collision as a safety net.
2. Sortable by time. If IDs increase with creation time, then:
- "Newest first" queries can use the primary key index directly:
WHERE id < :cursor ORDER BY id DESC LIMIT 20. - B-tree inserts land at the right-hand edge of the index, so recently used pages stay in memory, and pages fill completely instead of splitting halfway.
- Logs, events and messages can be ordered and deduplicated using just the ID.
There are degrees of sortability: strictly monotonic (every ID is greater than the previous one, everywhere), monotonic per generator (each machine's IDs increase, but machines interleave), and k-sorted, or roughly sorted, where IDs are ordered by time to within some error, such as clock skew between machines. Most distributed schemes give k-sorted IDs. Strict global order needs a single counter.
3. Compact. Smaller IDs mean smaller indexes, smaller foreign keys in every referencing table, less memory in caches and shorter URLs.
| Format | Size | Text form | Example length |
|---|---|---|---|
| 32-bit integer | 4 bytes | Decimal | Up to 10 digits; runs out at about 2.1 billion (signed) |
| 64-bit integer | 8 bytes | Decimal or base62 | Up to 19 digits, or 11 base62 characters |
| UUID | 16 bytes | 36-character hex with hyphens | 0190b3a2-6f0e-7cc4-9a3e-5d2b8c1f4e77 |
| ULID | 16 bytes | 26 characters, Crockford base32 | 01J2SV4VR0GZ8Q6X3M5N9PB7TA |
| KSUID | 20 bytes | 27 characters, base62 | 2Ri2ZqH9gKxV4s0bTz8wq5Lm3Ny |
A primary key appears in every secondary index too, in InnoDB for example, and in every foreign key that references it, so the difference between 8 and 16 bytes is multiplied many times. For a table of 1 billion rows with three secondary indexes and two referencing tables, moving from 8-byte to 16-byte keys adds roughly 8 bytes times 1 billion times 6 places, about 48 GB, before considering the effect of a larger key on index fan-out.
4. No coordination. Can a server create an ID without talking to anyone? Random and time-based schemes can. Counters cannot, though block allocation makes coordination rare.
5. Other properties that sometimes matter:
- Opaque: users should not be able to guess other IDs or learn business volumes from them.
- Fits in 64 bits: many databases, languages and existing schemas expect a
BIGINTkey. - Safe in JavaScript: JSON numbers are parsed as 64-bit floating point, so integers above 2 to the power 53, about 9 quadrillion, lose precision. Twitter's API returns
id_stralongside numeric IDs for this reason, and Discord sends its 64-bit IDs as strings. - URL-safe and readable: no characters that need escaping, ideally no ambiguous ones such as 0 and O, or 1, l and I.
- Embeds metadata: the ID tells you its creation time, or the shard where the row lives, which can be used for routing.
A worked requirements example. A social network creates 500 million posts a day, an average of about 5,800 per second and peaks of perhaps 30,000 per second, across 3 regions. Posts are stored in a sharded database and shown in feeds newest first. Requirements: globally unique; roughly time-sortable, so feed pagination by ID works; 64 bits, because the existing schema and caches use BIGINT; generated locally in each region with no cross-region calls; and able to support at least 10 years of growth. A Snowflake-style 64-bit ID meets all of these. UUID v4 fails sortability and size. A central sequence fails the regional and throughput requirements.
Requirements, in depth#
How "unique" depends on scope. An order ID that only needs to be unique within one merchant can be a per-merchant counter, (merchant_id, order_number), which is short, human friendly ("order 1042") and needs coordination only within one merchant's partition. A global ID, used as a key in many systems, needs a global scheme. Many systems have both: an internal global ID for storage and routing, and a short, scoped, human-facing number for receipts and support calls.
Ordering is about the index, not just the user. Consider a B-tree primary key with 16 KB pages, holding about 400 keys each for 16-byte keys plus pointers. With sequential keys, each insert goes to the right-most leaf page; when it fills, a new page is started and the full one is never touched again. The working set for inserts is a single page. With random keys, each insert lands on a random leaf among millions; the page must be read from disk if it is not cached, and pages split when full, leaving them about half to two-thirds full on average. For a 500 GB index that does not fit in memory, random inserts mean roughly one random disk read per insert, which on a database doing 20,000 inserts per second is 20,000 random reads per second. This is the most important practical difference between UUID v4 and time-ordered IDs, and it is largest in databases whose tables are clustered by primary key, such as MySQL's InnoDB and SQL Server. See Database Indexing and Storage Engines: B-Trees vs LSM Trees.
But ordering can hurt in a distributed database. In range-partitioned stores such as HBase, Bigtable, Spanner, CockroachDB or TiDB, keys are split into contiguous ranges, each served by one node. Monotonically increasing keys send every insert to the last range, creating a write hot spot on one node while the others idle. Common fixes:
- Prefix the key with a hash or shard number, so writes spread across ranges, at the cost of range scans by time.
- Use random IDs such as UUID v4, which spread naturally.
- Use bit-reversed sequences: Spanner offers a bit-reversed positive sequence, which reverses the bits of a counter so consecutive values land far apart.
Hash-partitioned stores, such as Cassandra and DynamoDB, hash the key anyway, so time-ordered IDs do not create hot spots there, but they also do not give range scans across partitions. The right ID depends on the storage engine: time-ordered for single-node B-trees, spread-out for range-partitioned distributed databases, either for hash-partitioned stores. See Partitioning and Sharding.
How many bits do you need? For random IDs, the birthday bound gives the chance of any collision among n IDs drawn from a space of N values: approximately n squared divided by 2N, while that is small. For time-based IDs, the question is capacity per time unit. Snowflake's 12-bit sequence gives 4,096 IDs per millisecond per worker, about 4 million per second per worker, and 1,024 workers give over 4 billion per second, far beyond almost any need. The timestamp width decides lifetime: 41 bits of milliseconds is 2 to the power 41 ms, about 69.7 years from the chosen epoch.
Information leakage. Sequential IDs reveal volumes: if a shop's order IDs go from 50,120 to 50,410 between two of your test orders a day apart, it takes about 290 orders a day. Statisticians call estimating a total from serial numbers the German tank problem, after Allied estimates of German tank production in the Second World War from captured serial numbers. Sequential IDs also invite enumeration: an attacker tries /invoices/1001, /invoices/1002 and so on. Authorisation checks must stop the second regardless, since unguessable IDs are not an access control, but random IDs make enumeration impractical and are a sensible extra layer. Time-ordered IDs reveal creation time, which can matter for privacy, for example showing when an account was created. See Security Fundamentals for System Design.
Auto-increment and ticket servers#
Auto-increment in one database. Relational databases generate IDs with a counter the database owns: AUTO_INCREMENT in MySQL, SERIAL or GENERATED ... AS IDENTITY columns backed by sequences in PostgreSQL, IDENTITY in SQL Server, and sequences in Oracle. Each insert takes the next value. IDs are compact, ordered and unique, and need no application code. For a single database, this is the right default.
Some details that surprise people:
- Gaps are normal. A PostgreSQL sequence hands out a value even if the transaction that took it rolls back, and the value is never reused. Sequences with a
CACHEsetting pre-allocate values per session, so a crash or disconnect discards the cached values. MySQL's InnoDB may also skip values after rollbacks or in bulk inserts. IDs are unique and increasing, not gapless. If a business rule needs gapless numbers, such as invoice numbers in some jurisdictions, generate them separately, inside a transaction that locks a counter row, and accept the contention. - Commit order is not ID order. Transaction A takes ID 100, transaction B takes 101, and B commits first. A reader that saw 101 and then queried "IDs greater than 101" misses 100 forever. Systems that tail a table by ID, such as change-data pipelines and pollers, must allow for this, typically by re-reading a recent window or using the database's change log instead.
- Contention. Sequences are designed to be fast, since they are not transactional, but in a very busy database the counter is still a shared hot spot, and the insert hot spot at the right edge of the index can become a contention point under extreme parallel insert rates.
- Running out. A signed 32-bit
INTkey overflows at about 2.1 billion. Several well-known outages were caused by tables hitting this limit, and the fix, migrating a huge table toBIGINT, is painful. Use 64-bit keys from the start for anything that may grow.
Multiple databases with interleaved counters. With two or more primaries, configure each to generate a disjoint arithmetic sequence. In MySQL, auto_increment_increment = 2 with auto_increment_offset = 1 on one server and 2 on the other gives odd IDs on one and even IDs on the other. This removes coordination, but adding a third server later requires changing the increment everywhere without overlapping existing values, and the IDs are no longer ordered across servers.
Ticket servers. Flickr described a pattern in 2010 that they called ticket servers: dedicated MySQL databases whose only job is to hand out IDs. Each ticket server has one table with an auto-increment column and a single row, and gets a new ID with:
-- One table per ID space, with a single row that is replaced each time
REPLACE INTO tickets64 (stub) VALUES ('a');
SELECT LAST_INSERT_ID();REPLACE deletes and reinserts the row, bumping the auto-increment value, and LAST_INSERT_ID() is per connection, so concurrent callers each see their own value. For availability, Flickr ran two ticket servers, one producing odd numbers and one even, using the increment and offset settings above, with clients alternating between them. If one failed, the other carried on. The IDs were 64-bit, compact and roughly ordered, and the approach used technology the team already ran. The costs: a network round trip to the ticket server per ID, servers that must be kept highly available, and only rough ordering, since the two servers drift apart.
Redis as a counter. INCR id:orders atomically increments a counter and returns the new value. Redis executes commands one at a time on its event loop, so two simultaneous callers always receive different values. One Redis instance handles over 100,000 increments per second. The risk is durability: with asynchronous replication or infrequent fsync, a failover or restart can lose recent increments, so the counter can go backwards and reissue IDs. Mitigations: enable append-only persistence with fsync per write or per second and, after any failover, jump the counter forward by a safe margin; and keep a UNIQUE constraint on the ID column in the database as the final guard.
Block, or segment, allocation. Instead of one round trip per ID, a service asks the counter for a block, such as 1,000 IDs, and hands them out from memory:
- The service calls
INCRBY id:orders 1000in Redis, or runsUPDATE id_alloc SET max_id = max_id + 1000 WHERE biz = 'orders' RETURNING max_idin a database. - If the result is 58,000, the service owns IDs 57,001 to 58,000.
- It hands them out locally, in microseconds, with an in-memory atomic counter.
- When the block is nearly used up, it fetches the next one in the background.
The counter store now sees one request per 1,000 IDs. A service creating 10,000 IDs per second makes 10 counter calls per second. If the service crashes, the unused part of its block is lost, which leaves a gap but does not break uniqueness. IDs from different instances interleave, so ordering is only rough: instance A may be handing out 57,xxx while instance B hands out 58,xxx at the same moment.
Double buffering. Meituan's open-source Leaf service, in its "segment" mode, keeps two buffers per ID type: while one block is being consumed, the next is fetched once the current one is, say, 10% used, so a slow database never makes a caller wait. It also adjusts the block size to the consumption rate, so busy ID types fetch bigger blocks. This is a good pattern for any block allocator.
Regional ranges. For multi-region deployments, give each region a disjoint range, for example region A IDs from 0 to 1 billion and region B from 1 billion to 2 billion, or reserve high bits for the region. Each region allocates locally with no cross-region traffic. When a region's range runs low, an operator or automated process assigns it a new one. See Multi-Region Data.
Auto-increment and ticket servers, in depth#
Short codes from counters. A URL shortener needs codes that are unique, as short as possible and cheap to generate. Three approaches compare well:
- Prefix of the URL: useless, since many URLs share prefixes.
- Hash of the URL, such as SHA-256, encoded and truncated: deterministic, so the same URL maps to the same code, which deduplicates, and no counter is needed. But truncation makes collisions possible, and their probability grows with the number of stored codes, so inserts need a uniqueness check and retry with a salt. If you do not want the same URL to give the same code, or want codes to be unguessable, use a keyed hash, such as HMAC, or a random number.
- Counter plus base62: guaranteed unique, with no collision checks, and as short as possible for the number of codes issued.
Base62 encoding. Base62 uses the digits 0 to 9, lowercase a to z and uppercase A to Z: 62 symbols that are all safe in URL paths. Base64 adds + and /, which are a space in query strings and a path separator respectively, hence base62. Each character carries log2 of 62, about 5.95 bits. Capacities:
| Length | Codes available | Enough for |
|---|---|---|
| 6 characters | 62 to the power 6, about 56.8 billion | A large shortener for decades |
| 7 characters | About 3.5 trillion | Almost anything |
| 8 characters | About 218 trillion | Random codes with a low collision rate |
| 11 characters | About 52 quintillion, more than 2 to the power 64 | Any 64-bit integer |
One billion encodes as 15ftgG in base62 (with the alphabet ordered digits, then uppercase, then lowercase; other orderings give different strings of the same length), so a counter-based shortener stays at 6 characters until about 56 billion links.
Making counter codes unguessable. Sequential codes let anyone enumerate every short link by counting. If that matters, apply a reversible permutation before encoding, such as multiplying by a large odd constant modulo 2 to the power 64, or a small block cipher over the ID's bit width, such as a Feistel network with a secret key. The result is still unique, since a permutation never maps two inputs to one output, and it can be decoded back to the counter value, but consecutive counters produce unrelated codes. Libraries like Sqids, formerly Hashids, do a weaker version of this for display. Treat any of these as obfuscation, not security.
The counter's failure modes. A Redis counter that loses its last few increments on failover could reissue codes already in use. The URL table's UNIQUE constraint on the short code catches this: the insert fails and the service takes the next value. Losing values only creates gaps, which do not matter. Uniqueness, not continuity, is the requirement. See Design a URL Shortener (Bitly).
Scaling the counter. With block allocation, one Redis instance easily serves a fleet of write servers. With 100,000 new URLs a day, about one per second, even a call per ID is trivial. The counter becomes a concern only at hundreds of thousands of IDs per second, where blocks reduce counter traffic by the block size, or regional ranges avoid shared state entirely.
Gaps, holes and the "max ID" trap. Code that estimates a table's size from its maximum ID, or treats IDs as dense array indexes, breaks with any of these schemes: sequences skip, blocks are abandoned, and ranges leave holes. Count rows if you need counts.
Stored procedures as generators. Instagram's 2012 engineering post, "Sharding & IDs at Instagram", described generating 64-bit IDs inside PostgreSQL, with a PL/pgSQL function per logical shard: 41 bits of milliseconds since a custom epoch, 13 bits of logical shard ID, and 10 bits from a per-shard sequence taken modulo 1,024. Every ID is generated by the database that stores the row, needs no extra service, sorts by time, and tells you which shard holds it. It is a hybrid: a Snowflake-style layout, with a database sequence as the sequence field.
UUID v4 vs v7#
A UUID, universally unique identifier, is a 128-bit value, usually written as 32 hexadecimal digits in five hyphenated groups: 8-4-4-4-12. It was standardised in RFC 4122 (Leach, Mealling and Salz, 2005), which RFC 9562 (Davis, Peabody and Leach, 2024) replaced, adding versions 6, 7 and 8. Every UUID reserves a few bits to mark its version (the first hex digit of the third group) and its variant (the first one to three bits of the fourth group, 10 for standard UUIDs), so you can tell a v4 from a v7 by looking at it.
The versions in brief:
| Version | Contents | Use today |
|---|---|---|
| 1 | 60-bit timestamp in 100 ns intervals since 15 October 1582, clock sequence, 48-bit node ID (originally the MAC address) | Legacy; leaks the MAC address and its timestamp bytes do not sort |
| 3 and 5 | MD5 (v3) or SHA-1 (v5) hash of a namespace UUID and a name | Deterministic IDs for the same name, such as a URL or DNS name |
| 4 | 122 random bits | The default random ID |
| 6 | Version 1 with the timestamp bytes reordered so it sorts | Migration path from v1 |
| 7 | 48-bit Unix timestamp in milliseconds, then random bits | Time-ordered default for new systems |
| 8 | Custom layout, only version and variant fixed | Vendor-specific formats |
UUID version 4. All bits except the 6 version and variant bits are random: 122 bits of randomness. A server generates one locally, in well under a microsecond, with no coordination. The chance of a collision follows the birthday bound: with n UUIDs, the probability of any duplicate is about n squared divided by 2 times 2 to the power 122.
- After 1 trillion (10 to the power 12) UUIDs: about 10 to the power minus 13, effectively zero.
- After 100 trillion: about 10 to the power minus 9.
- A 50% chance needs about 2.7 quintillion (2.7 times 10 to the power 18) UUIDs, which at 1 billion per second takes about 86 years.
The real collision risk is not the mathematics but bad randomness: a generator seeded identically on many virtual machines cloned from one image, a non-cryptographic random generator with a small state, or a bug that reuses a buffer. Use the operating system's cryptographic generator, through crypto.randomUUID() in JavaScript, uuid.uuid4() in Python, java.util.UUID.randomUUID() in Java, or gen_random_uuid() in PostgreSQL.
The problem with v4 as a primary key. Random values scatter inserts across the whole index, as described above: poor cache locality, page splits, more I/O and larger, fragmented indexes. In InnoDB, where the table is stored in primary key order, a random UUID key slows inserts noticeably once the table outgrows memory. v4 also carries no time information, so you need a separate created_at column and index for "newest first" queries. In hash-partitioned and range-partitioned distributed databases, though, its randomness is an advantage, since it spreads writes evenly.
UUID version 7. RFC 9562 defines v7 as:
- 48 bits: Unix timestamp in milliseconds, big-endian, so it sorts first. 48 bits of milliseconds lasts until about the year 10889.
- 4 bits: version,
0111. - 12 bits:
rand_a, random, or optionally extra timestamp precision or a counter. - 2 bits: variant,
10. - 62 bits:
rand_b, random.
A v7 UUID sorts by creation time to the millisecond, as bytes or as its text form, while keeping 74 random bits for uniqueness within a millisecond. That is far fewer random bits than v4, but they only need to be unique among IDs created in the same millisecond: even a million IDs in one millisecond have a collision probability of about 10 to the power 12 divided by 2 times 2 to the power 74, about 3 times 10 to the power minus 11.
Monotonicity within a millisecond. With purely random bits after the timestamp, two v7 UUIDs from the same generator in the same millisecond sort randomly relative to each other. RFC 9562 describes options for generators that want strict ordering: use the 12 rand_a bits as a counter that increments within a millisecond, or as sub-millisecond time, or increment the random part by a random amount. The RFC also allows the generator to keep a timestamp no lower than the last one it used, so a clock that steps back does not break per-generator ordering.
Support. Many languages have v7 libraries, and PostgreSQL 18 added a built-in uuidv7() function. Where the database lacks it, the application generates v7 and inserts it as an ordinary UUID column, since databases store all versions the same way.
UUID v4 vs v7, in depth#
Comparing v4 and v7 as primary keys.
| Property | UUID v4 | UUID v7 |
|---|---|---|
| Random bits | 122 | 74 (or fewer, if a counter is used) |
| Sorts by creation time | No | Yes, to the millisecond |
| B-tree insert locality | Poor: random pages | Good: recent pages, like an auto-increment |
| Leaks creation time | No | Yes, to the millisecond |
| Hot spot in range-partitioned stores | No | Yes, like any time-ordered key |
| Needs a clock | No | Yes; clock jumps affect order, not uniqueness |
| Collision risk | Negligible | Negligible, assuming good randomness |
For a new system on a single-node relational database, v7 is usually the better default when 128-bit keys are acceptable: you keep coordination-free generation and gain locality and ordering. Use v4 when the creation time must not be revealed, when the key is an external token, or when the storage is a range-partitioned store that benefits from spread-out keys.
Storing UUIDs efficiently. Store UUIDs in a native 16-byte type, PostgreSQL's uuid, or BINARY(16) in MySQL, never as a 36-character string, which more than doubles the size and makes comparisons slower. MySQL 8 provides UUID_TO_BIN(uuid, 1), whose swap flag rearranges v1 UUIDs' timestamp fields so they sort; for v7, no swap is needed, since the timestamp is already first. Be careful with databases or drivers that sort UUIDs in a non-byte order: SQL Server's uniqueidentifier, for example, compares the last group of bytes first, which defeats the ordering of v7 unless you account for it.
Deterministic name-based UUIDs. Versions 3 and 5 hash a namespace and a name, so the same input always yields the same UUID. This is useful for idempotent imports ("the UUID of the customer with external ID 4471 in system X"), and for deriving IDs on several machines without coordination. Version 5, with SHA-1, is preferred over version 3, with MD5. Neither is secret: anyone who knows the namespace and name can compute the UUID.
Why version 1 fell out of favour. It embeds the generating machine's MAC address, which leaks hardware identity, and, was reported in 1999 to have helped investigators link the Melissa macro virus to the computer that created it, through the identifiers embedded in Word documents. Its timestamp is stored with the low-order bits first, so v1 UUIDs do not sort by time as bytes. Version 6 reorders the fields so they sort, and version 7 replaces the node ID with random bits.
Snowflake IDs (timestamp, machine, sequence)#
In 2010, Twitter was moving from MySQL to Cassandra and needed IDs for tweets that were unique across many generator machines, roughly time-ordered, and 64 bits so they fit existing code. Its answer, Snowflake, open-sourced that year, became the template for 64-bit distributed IDs.
The layout. A Snowflake ID is a 64-bit integer, split into fields from the most significant bit:
| Bits | Field | Meaning |
|---|---|---|
| 1 | Sign | Always 0, so the ID is a positive signed 64-bit integer |
| 41 | Timestamp | Milliseconds since a custom epoch (Twitter's is in November 2010) |
| 10 | Machine ID | Identifies the generator: Twitter split it into 5 bits of data centre and 5 bits of worker |
| 12 | Sequence | Counter for IDs generated by this machine within the same millisecond |
Generating an ID. Each generator holds the last timestamp it used and a sequence counter:
next_id():
now = current time in ms since epoch
if now < last_ts: // clock moved backwards
wait until now >= last_ts, or fail // never reuse a past timestamp
if now == last_ts:
seq = (seq + 1) mod 4096
if seq == 0: // 4096 IDs used this ms
wait until the next millisecond; now = that ms
else:
seq = 0
last_ts = now
return (now << 22) | (machine_id << 12) | seqThe shifts place the timestamp in the top bits, so comparing two IDs compares their timestamps first. Generation is purely local, needs no network call and takes well under a microsecond, so Snowflake generators are often a library embedded in each service rather than a separate service.
The capacity numbers.
- Lifetime: 2 to the power 41 milliseconds is about 69.7 years from the epoch. Choosing a recent custom epoch, rather than 1970, gives the full span from launch.
- Generators: 2 to the power 10 is 1,024 machine IDs.
- Throughput: 4,096 IDs per millisecond per generator, about 4.1 million per second, and in total over 4 billion per second across 1,024 generators.
Why it works. Uniqueness comes from the combination of fields: two generators can never collide because their machine IDs differ; one generator never collides with itself because, within a millisecond, its sequence increments, and across milliseconds, the timestamp differs. Rough ordering comes from the timestamp being first: IDs from different machines are ordered by their creation time, up to the clock skew between machines, and IDs from one machine are strictly increasing.
The machine ID is the coordination. Snowflake avoids per-ID coordination, but it moves the coordination to assigning machine IDs: no two live generators may have the same ID, or they will produce duplicates in the same millisecond. Options:
- Static configuration: set the worker ID in each server's configuration. Simple for a fixed fleet, error-prone with autoscaling.
- A coordination service: on startup, each generator claims an ID from ZooKeeper or etcd, for example with an ephemeral sequential node or a lease on a key,
/snowflake/workers/17, and releases it on shutdown. Twitter's original Snowflake registered its workers in ZooKeeper, and Meituan's Leaf in Snowflake mode assigns worker IDs through ZooKeeper sequential nodes. - Kubernetes StatefulSet ordinals: pods named
idgen-0,idgen-1and so on use their ordinal as worker ID. - Derived from the network: Sony's Sonyflake uses the lower 16 bits of the machine's private IP address by default. This works if addresses are unique within the deployment and stable.
- A database lease table: claim a worker ID row with a conditional update and a lease, renewed periodically.
Variants. Many organisations adjusted the field widths to their needs:
| Scheme | Layout | Notes |
|---|---|---|
| Twitter Snowflake | 41-bit ms, 10-bit machine, 12-bit sequence | The original, 2010 |
| Discord | Same widths, epoch 1 January 2015; machine bits split into 5-bit worker and 5-bit process | IDs sent as strings in JSON |
| 41-bit ms, 13-bit logical shard, 10-bit sequence | Generated inside PostgreSQL per shard | |
| Sonyflake | 39 bits of 10 ms units, 8-bit sequence, 16-bit machine | About 174 years; 256 IDs per 10 ms per machine |
| MongoDB ObjectId (12 bytes) | 4-byte seconds, 5-byte random per process, 3-byte counter | 96 bits; generated by drivers |
Sonyflake's trade-off is instructive: coarser time units extend the lifetime to about 174 years and allow 65,536 machines, but cap each machine at 25,600 IDs per second. Instagram's shard field puts routing information in the ID: given any post ID, the application knows which logical shard holds it, so no lookup table is needed.
Snowflake IDs, in depth#
Choosing the bit split for your system. Work backwards from requirements. Suppose you need 40 years of lifetime, up to 5,000 generator processes, and peaks of 50,000 IDs per second per process.
- Lifetime: 40 years is about 1.26 times 10 to the power 12 ms, which needs 41 bits (2 to the power 40 is about 34.8 years, too short).
- Generators: 5,000 needs 13 bits (8,192).
- That leaves 63 minus 41 minus 13, which is 9 bits of sequence: 512 per ms, 512,000 per second per process. Enough.
If your peaks were higher, you could trade machine bits for sequence bits, or time precision for both, as Sonyflake does.
Ordering across machines is only as good as the clocks. Two IDs created 1 ms apart on different machines whose clocks differ by 5 ms can be ordered the wrong way round. With NTP keeping skew to a few milliseconds within a data centre, Snowflake IDs are k-sorted with k of a few milliseconds: good enough for feeds and pagination, not for proving causality. If you need "A happened before B" across machines, use a mechanism that tracks causality, as described in Time and Ordering.
Sequence exhaustion. If a generator issues 4,096 IDs within one millisecond, it must wait for the next millisecond, which caps its rate and adds up to 1 ms of latency for the 4,097th caller. In practice, few single processes exceed 4 million IDs per second. Some implementations start each millisecond's sequence at a random value rather than 0, which spreads the low bits when IDs are used for sharding by modulo, at the cost of slightly reduced capacity per millisecond.
Using the ID for sharding. The low bits of a Snowflake ID are mostly the sequence, often 0 at low traffic, so id mod 16 is badly skewed: most IDs end in sequence 0 or 1. Shard by a hash of the ID, or by a field such as Instagram's embedded shard ID, never by the raw low bits.
JavaScript precision. Snowflake IDs exceed 2 to the power 53 after a short time: an ID is roughly the millisecond count shifted left by 22 bits, so it passes 2 to the power 53 once more than 2 to the power 31 milliseconds, about 25 days, have elapsed since the epoch. JSON parsers in browsers convert them to floating point and silently change the low digits. Twitter's API added string versions of IDs, id_str, for this reason. Send 64-bit IDs as strings in JSON, or use BigInt on the client.
Extracting the timestamp. Since the timestamp is in the top bits, (id >> 22) + epoch recovers the creation time to the millisecond. This is handy for debugging, for time-based partitioning ("which month's table holds this ID?"), and for range queries: the smallest Snowflake ID created after time T is (T - epoch) << 22, so "posts after T" becomes WHERE id >= that value, using the primary key index with no created_at column.
A Snowflake service versus a library. An ID service, a few highly available instances that applications call, centralises worker ID management and clock checks, at the cost of a network hop per ID or per batch. A library embedded in every service has no hop, but every service instance needs its own worker ID, which with thousands of autoscaled pods means a coordination service for ID leases. Many companies began with a service and moved to libraries, or did the reverse, depending on their fleet size and how much they trusted their clocks.
ULID/KSUID#
Random UUIDs do not sort, and Snowflake needs worker IDs. A family of formats sits in between: a timestamp prefix for ordering, plus enough random bits that no worker ID is needed. UUID v7 is the standardised member of this family; ULID and KSUID came earlier and are still widely used.
ULID, universally unique lexicographically sortable identifier, published as an open specification in 2016:
- 128 bits: a 48-bit Unix timestamp in milliseconds, followed by 80 random bits.
- Text form: 26 characters in Crockford's base32, an alphabet of digits and uppercase letters that omits I, L, O and U to avoid confusion with 1 and 0 and accidental words. For example
01J2SV4VR0GZ8Q6X3M5N9PB7TA. - Lexicographic sort: since the timestamp comes first and the alphabet is in ascending order, sorting ULID strings sorts them by time.
- Monotonic mode: if several ULIDs are generated in the same millisecond, the specification describes incrementing the random part by 1 instead of drawing new random bits, which keeps them strictly ordered within a generator. If the 80-bit random part would overflow, generation fails until the next millisecond, which in practice never happens.
- Binary compatibility with UUID: a ULID is 128 bits, so it can be stored in a UUID column, though it will not carry the UUID version bits.
KSUID, K-sortable unique identifier, published by Segment in 2017:
- 160 bits, 20 bytes: a 32-bit timestamp in seconds since a custom epoch of 1,400,000,000 Unix seconds (13 May 2014), followed by 128 random bits.
- Text form: 27 characters in base62, which sort in the same order as the binary form, because they are fixed-length.
- Trade-off: second resolution, so ordering within a second is random, but 128 random bits make collisions even less likely than UUID v4's 122, and the 32-bit seconds field lasts about 136 years from the epoch.
Other formats you will meet:
- NanoID: a random ID of configurable length and alphabet, by default 21 characters from a 64-symbol URL-safe alphabet, about 126 random bits. Not sortable; designed for short, URL-safe tokens.
- CUID2: a random-looking ID that hashes a timestamp, counter, random data and a host fingerprint, designed to be secure and not reveal its creation time, at the cost of sortability.
- TSID: a 64-bit time-sorted ID, similar to Snowflake, with a 42-bit timestamp and a 22-bit random or node-plus-counter part, encoded as 13 Crockford base32 characters.
- XID: a 12-byte format based on MongoDB's ObjectId layout, encoded as 20 base32 characters.
| Format | Bits | Time part | Random or other part | Text length | Sortable |
|---|---|---|---|---|---|
| UUID v4 | 128 | None | 122 random | 36 | No |
| UUID v7 | 128 | 48-bit ms | 74 random, or counter | 36 | Yes, ms |
| ULID | 128 | 48-bit ms | 80 random | 26 | Yes, ms |
| KSUID | 160 | 32-bit s | 128 random | 27 | Yes, s |
| Snowflake | 64 | 41-bit ms | 10 machine, 12 sequence | Up to 19 digits | Yes, ms |
| ObjectId | 96 | 32-bit s | 40 random, 24 counter | 24 hex | Yes, s |
| NanoID | About 126 | None | Random | 21 | No |
ULID/KSUID, in depth#
ULID versus UUID v7. They are nearly the same idea. Differences:
- Standardisation: v7 is an IETF standard with version and variant bits, so tools recognise it as a UUID; ULID is a community specification.
- Random bits: ULID has 80, v7 has 74.
- Text form: ULID's 26-character base32 is shorter and more readable than the 36-character hex UUID, and case-insensitive.
- Ecosystem: databases have native UUID types and functions, which makes v7 easier to store and index; ULID is usually stored as a UUID or as text.
For new systems, v7 is the safer default where UUID columns are available, and ULID's text form remains attractive where IDs are shown to people or used in URLs. Either can be converted to the other's binary layout, but they are not the same values.
How many IDs per millisecond is safe with random bits? With r random bits and m IDs generated in the same millisecond, across all generators, the chance of a collision in that millisecond is about m squared divided by 2 to the power r plus 1. Two traffic levels show where the limits are:
- 1 million IDs per second, 1,000 per millisecond, a very busy system. For ULID, with 80 random bits, the chance per millisecond is about 10 to the power 6 divided by 2.4 times 10 to the power 24, and over a year, 3.15 times 10 to the power 10 milliseconds, about 1 in 80 million. For v7, with 74 bits, it is about 1 in 1.2 million per year. Both are negligible.
- 1 billion IDs per second, a million per millisecond. For ULID, the per-millisecond chance is about 4 times 10 to the power minus 13, which over a year adds up to about 1 in 80. For v7, a collision within a year becomes more likely than not.
So random bits alone are comfortable at any realistic rate, but at extreme rates the random part is too small. That is why the specifications offer monotonic counters within a millisecond, which make one generator's IDs collision-free by construction, leaving only collisions between generators, and why a database UNIQUE constraint is a cheap safety net.
Monotonic generation and its leak. ULID's monotonic mode, and v7's counter option, increment the previous ID within a millisecond. That makes IDs from one generator predictable: knowing one ID, you can guess the next ones created in the same millisecond. If IDs are used as unguessable tokens, use fresh random bits, and accept that same-millisecond IDs sort arbitrarily.
KSUID's choice of seconds. Segment chose second resolution to give 128 random bits, enough that collisions need no further thought, and accepted that events within one second are not ordered by ID. For their use, event pipelines that also carry precise timestamps, that was the right trade. The lesson generalises: a format's time resolution decides how much order you get for free, and its random width decides how safe you are without coordination.
Clock problems#
Any ID that embeds a timestamp depends on the machine's clock, and clocks are less trustworthy than they look. See Time and Ordering for the underlying causes. The failures that matter for ID generation:
The clock jumps backwards. NTP corrects a drifting clock either by slewing, speeding up or slowing down the clock slightly until it is right, or by stepping, setting it to the correct time at once. A step backwards, for example after a virtual machine resumes from a pause, or after an administrator fixes a clock that ran fast, means the generator sees a timestamp earlier than one it has already used. If it simply carried on, it would reuse timestamp values it has already used, with the same machine ID and possibly the same sequence numbers, and would produce duplicate IDs.
Generator responses, from safest to most available:
- Refuse: return an error until the clock catches up. Twitter's original Snowflake threw an exception when it detected the clock moving backwards. Safe, but the generator is unavailable for the length of the jump.
- Wait: if the jump is small, such as under 5 ms, sleep until the clock passes the last timestamp, then continue. Callers see a short delay.
- Keep using the last timestamp: treat the generator's own
last_tsas the time, and keep incrementing the sequence; when the sequence overflows, advancelast_tsby 1 ms, a "logical" clock running slightly ahead of the real one. This keeps IDs unique and monotonic, at the cost of the timestamp field drifting ahead of real time until the clock catches up. Several implementations, and the UUID v7 specification's guidance, allow this. - Switch to a spare machine ID: some designs reserve a few extra worker IDs, and on a large backwards jump, switch to an unused one, which cannot collide with IDs issued before the jump.
The clock jumps forwards. Uniqueness is unaffected, but IDs issued after the jump sort after IDs that other machines will issue for a while, which reorders feeds slightly, and if the jump is huge, such as a clock set to a year in the future, the generator burns through its timestamp space. Sanity-check the clock against a reference on startup, and alert on large offsets.
Restarts with a clock behind the last issued ID. A generator that crashes and restarts has lost its in-memory last_ts. If its clock is now behind the time it last used, for example because the restart coincided with an NTP correction, it could reissue IDs. Defences:
- Persist the high-water mark: periodically write the latest timestamp used, for example every second, to the coordination service or local disk, and on startup refuse to issue IDs until the clock is past the stored value plus the persistence interval.
- Wait on startup: sleep for a period longer than any plausible backward step, such as a few seconds, before issuing IDs.
- Get a fresh machine ID on every start, if machine IDs are leased from a coordination service, and do not reuse one until it has been free for longer than the maximum clock error.
Meituan's Leaf in Snowflake mode is an example of the first approach: each worker periodically reports its time to ZooKeeper, and on startup compares its clock with its own last reported time and with other workers' times, refusing to start if the difference is too large.
Leap seconds. Unix time does not count leap seconds: when one occurs, a second is repeated, or smeared. With a repeated second, millisecond timestamps go back by 1,000 ms, which a Snowflake generator sees as a backwards jump. Large providers such as Google and AWS smear leap seconds over many hours, adjusting the clock by tiny amounts so it never steps, which avoids the problem. The international timekeeping bodies decided in 2022 to stop adding leap seconds by 2035, which will remove this source of trouble.
Machine ID collisions. The worst Snowflake failure is two live generators with the same worker ID: their IDs collide whenever they issue in the same millisecond with the same sequence number, which at moderate traffic is constantly. This happens with copied configuration files, a coordination lease that expired while the old holder kept running, or IP-derived IDs after address reuse. Treat the worker ID like a lock: lease it, stop issuing IDs when the lease cannot be renewed, and, as with any lease, account for pauses. See Distributed Locks.
Monotonic clocks do not solve it. A monotonic clock never goes backwards within a process, but it has no relation to wall-clock time and resets at reboot, so it cannot be used directly for a timestamp that must be comparable across machines and restarts. Some generators combine them: take the wall clock at startup, then add elapsed monotonic time, which removes in-process backward jumps, while the startup checks above handle restarts.
Clock problems, in depth#
How big are clock jumps in practice? Within a well-run data centre, NTP or PTP keeps clocks within a few milliseconds, often under one, and configured to slew rather than step, so backward jumps of more than a few milliseconds are rare. Exceptions: virtual machines resuming after being paused or migrated, containers on hosts with misconfigured time synchronisation, devices that boot with a wrong clock and step once NTP connects, and clocks corrected manually. Cloud providers' time services, such as Amazon Time Sync and Google's public NTP, are smeared and accurate, which helps. The design rule: assume small backward steps will happen, so wait for them, and large ones will happen rarely, so detect and refuse them.
Hybrid logical clocks as an ID source. A hybrid logical clock (HLC), introduced by Kulkarni, Demirbas and colleagues in 2014, combines a physical timestamp with a logical counter, and never goes backwards: each node's HLC value is the maximum of its physical clock and the largest timestamp it has seen, with a counter to break ties. CockroachDB uses HLC timestamps for transaction ordering, and its default for integer primary keys, the unique_rowid() function, combines a timestamp with the node ID. An HLC-based ID generator gets Snowflake-like IDs that also respect causality between nodes that exchange messages, at the cost of needing to see other nodes' timestamps.
Spanner and TrueTime. Google Spanner assigns commit timestamps using TrueTime, an API that returns an interval guaranteed to contain the true time, backed by GPS and atomic clocks, and waits out the uncertainty before committing. This gives timestamps that respect real-time order across the world (James C. Corbett and colleagues, "Spanner: Google's Globally-Distributed Database", OSDI 2012). Those are timestamps for transactions, not row IDs. Spanner's own guidance is to avoid monotonically increasing primary keys, precisely because they create hot spots, and to use UUID v4 or bit-reversed sequences instead.
Testing time handling. Inject a fake clock into the generator, then test: the same millisecond 5,000 times (sequence overflow), a 3 ms step back (wait), a 10-second step back (refuse or switch), a restart with a clock behind the stored high-water mark, and two generators accidentally given the same worker ID (which a uniqueness check in the test should catch). These cases are cheap to test and expensive to discover in production.
Choosing#
The decision comes down to a handful of questions.
1. Is there only one database that will ever generate these IDs? Then use its auto-increment or sequence, with a 64-bit type. Do not add complexity you do not need. Many large systems run for years on database sequences.
2. Must the ID fit in 64 bits? If existing schemas, caches or languages need a BIGINT, choose between:
- Snowflake-style IDs: time-ordered, generated locally, with the cost of managing worker IDs and handling clock problems.
- Block allocation from a counter: dense and ordered within each block, no clock dependence, with a dependency on the counter store when fetching new blocks.
3. Is 128 bits acceptable? Then the coordination-free options open up:
- UUID v7 or ULID: time-ordered, index-friendly, no worker IDs. The default for new systems on relational databases.
- UUID v4: no time leakage, spreads writes evenly, the right choice for external tokens and for range-partitioned stores where time order would create hot spots.
4. Does the ID appear in URLs or to humans? Prefer a compact text form: base62 for counters and 64-bit IDs, Crockford base32 for ULIDs, or short random codes, such as NanoID or base62, for share links. Keep a separate short scoped number, such as an order number per merchant, for phone calls and receipts.
5. Must the ID be unguessable or hide volume? Avoid raw counters in public. Use random IDs, a permuted counter, or a separate public ID column alongside an internal sequential key.
6. Where does the data live?
- Single-node B-tree databases, such as PostgreSQL or MySQL: time-ordered keys are best.
- Range-partitioned distributed databases, such as Spanner, CockroachDB, HBase or Bigtable: avoid monotonically increasing keys, or prefix them with a hash or shard.
- Hash-partitioned stores, such as Cassandra or DynamoDB: any format works for distribution; time order helps only within a partition's sort key.
| Use case | Good choice | Why |
|---|---|---|
| Single PostgreSQL app, internal tables | BIGINT GENERATED ALWAYS AS IDENTITY | Simplest; compact; ordered |
| Tweets, posts, messages at scale | Snowflake-style 64-bit | Time-sortable feeds; fits BIGINT; local generation |
| Microservices creating records independently | UUID v7 | No coordination; index-friendly |
| Events in a pipeline, produced by many clients | UUID v7, ULID or KSUID | Generated at the source; sortable for deduplication windows |
| URL shortener codes | Counter with blocks, base62 encoded | Shortest possible codes; guaranteed unique |
| API keys, password-reset tokens, invite codes | Cryptographically random, 128 bits or more | Must be unguessable; never time-based |
| Spanner or CockroachDB primary keys | UUID v4, or hash-prefixed keys | Avoid range hot spots |
| Offline-first mobile app records | UUID v7 or v4, generated on device | No server available at creation time |
| Idempotent import of external records | UUID v5 of namespace and external ID | Same input always gives the same ID |
Choosing, in depth#
Internal and external IDs. A common, robust design uses two identifiers: an internal 64-bit key, a sequence or Snowflake, used for joins, foreign keys and indexes, and an external, opaque public ID, a UUID or random base62 string, stored in a uniquely indexed column and used in URLs and APIs. Internal keys stay compact and ordered, external IDs reveal nothing and can never be enumerated, and the internal scheme can change without breaking anyone's links. The cost is an extra indexed column and a lookup from public ID to internal key on each request.
Migrating ID schemes. Changing the ID format of a live system is hard, because IDs spread everywhere: foreign keys, caches, logs, client storage, URLs and partner systems. If you must:
- Make new IDs distinguishable from old ones, for example by starting a new 64-bit scheme above the highest existing value, or by giving the new format a different length or prefix.
- Never reuse the old ID space.
- Keep old IDs valid forever in public URLs, translating them if necessary.
- Prefer adding a new ID column and migrating references gradually over rewriting primary keys in place.
Prefixing IDs with their type. Stripe popularised IDs such as cus_ followed by a random string for customers, ch_ for charges and pi_ for payment intents. A type prefix makes logs and support tickets readable, catches bugs where an ID of the wrong type is passed, and lets routing layers dispatch by type. The cost is a few bytes per ID, which matters little for external IDs.
The cost of getting it wrong. Common regret stories: a 32-bit key that overflowed after years of growth and required a weekend-long migration; random UUID v4 primary keys on a large InnoDB table that made inserts slow once the table outgrew memory; sequential public IDs that let competitors estimate order volumes; duplicate IDs from two Snowflake workers configured with the same worker ID; and JavaScript clients silently corrupting 64-bit IDs. Each is avoided by asking the six questions above before the first table is created.
When to Use It#
- Sharded or multi-primary databases, where per-database auto-increment would collide.
- Many services creating records independently, such as microservices that publish events before or without a central database.
- Multi-region systems, where a cross-region call per ID would add 100 ms or more of latency.
- Client-side generation, such as offline mobile apps or idempotent API clients that create an ID before sending the request.
- Time-ordered data at scale, such as feeds, chat messages and logs, where ID order replaces a separate timestamp index.
- Short public identifiers, such as short links and share codes, where a counter with base62 gives the shortest codes.
When NOT to Use It#
- A single database that is the only writer: use its sequence or identity column. A custom generator adds failure modes for no benefit.
- When natural keys exist and are stable, such as ISO country codes or a SKU that never changes. Even then, many teams prefer a surrogate key, because "never changes" rarely holds.
- Time-based IDs as secrets: never use Snowflake, ULID or UUID v7 as an API key, session token or password-reset token. Use at least 128 bits from a cryptographic random generator.
- Time-ordered keys on range-partitioned distributed databases without a hash prefix: they create a write hot spot on one range.
- Gapless numbering requirements, such as legal invoice sequences: no distributed ID scheme is gapless; use a separate, locked counter.
- Building a Snowflake service when UUID v7 would do: worker ID management and clock handling are real operational work.
How to Implement It#
- Write down the requirements: scope of uniqueness, ordering needed, size limit (64 or 128 bits), public exposure, generation rate and lifetime.
- Prefer built-in generation: a database identity column,
gen_random_uuid(), PostgreSQL 18'suuidv7(), or a well-tested library, rather than writing a generator. - For Snowflake-style IDs, choose the epoch and bit split from the lifetime, generator count and peak rate, and document it, since it can never change.
- Assign worker IDs safely: lease them from etcd, ZooKeeper or a database table, stop issuing IDs when the lease is lost, and never run two generators with one ID.
- Handle the clock: wait out small backward steps, refuse large ones, persist a high-water mark, and alert on clock offset.
- Store IDs in native types:
BIGINTfor 64-bit IDs,uuidorBINARY(16)for 128-bit ones, never strings in primary keys. - Send 64-bit IDs as strings in JSON, and encode them compactly, in base62 or Crockford base32, for URLs.
- Keep a
UNIQUEconstraint on every ID column as the final guard against bugs, misconfiguration and bad randomness. - Monitor: duplicate-key errors, clock offset, sequence exhaustion waits, worker ID lease failures and block fetch latency.
A compact Snowflake generator in TypeScript, using BigInt for 64-bit arithmetic:
const EPOCH = 1735689600000n; // 2025-01-01T00:00:00Z, fixed forever
const MAX_BACKWARD_MS = 5n;
export class Snowflake {
private lastTs = -1n;
private seq = 0n;
constructor(private readonly worker: bigint) { // 0..1023, leased, never shared
if (worker < 0n || worker > 1023n) throw new Error("worker out of range");
}
next(): bigint {
let now = BigInt(Date.now()) - EPOCH;
if (now < this.lastTs) {
if (this.lastTs - now > MAX_BACKWARD_MS) throw new Error("clock moved backwards");
now = this.lastTs; // small step back: reuse last ms
}
if (now === this.lastTs) {
this.seq = (this.seq + 1n) & 4095n;
if (this.seq === 0n) now = this.lastTs + 1n; // sequence full: move to next ms
} else {
this.seq = 0n;
}
this.lastTs = now;
return (now << 22n) | (this.worker << 12n) | this.seq;
}
}Two details make this safe. A small backward step reuses the last millisecond, with the sequence continuing, instead of a past one. A full sequence moves lastTs one millisecond ahead of the wall clock, so now can run ahead briefly under extreme load, which the backward-step check then treats as the clock being behind, keeping IDs strictly increasing.
| Technology | Fits when |
|---|---|
PostgreSQL identity columns and sequences, MySQL AUTO_INCREMENT | One database generates all IDs |
PostgreSQL gen_random_uuid() and uuidv7() | UUIDs generated in the database |
Language UUID libraries (crypto.randomUUID, uuid packages with v7) | UUIDs generated in the application or on clients |
| Twitter Snowflake-style libraries, Sonyflake, TSID | 64-bit time-ordered IDs with worker IDs |
Redis INCR and INCRBY | Counters and block allocation, with a database uniqueness check |
| Database segment table or Meituan Leaf | Block allocation with double buffering at high rates |
| etcd or ZooKeeper | Leasing worker IDs and storing clock high-water marks |
| ULID and KSUID libraries | Sortable IDs with readable, compact text forms |
| NanoID or a cryptographic random generator with base62 | Short, unguessable public codes and tokens |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Database auto-increment | Simple; 8 bytes; ordered; no code | One database; leaks volume; gaps; hard to merge shards | Single database owns the entity |
| Ticket server or Redis counter | Compact; roughly ordered; works across databases | A call per ID; counter must be highly available and durable | Moderate rates; short codes needed |
| Block allocation | Compact; one counter call per thousands of IDs | Gaps on crash; ordering only per block | High rates of 64-bit IDs without clocks |
| UUID v4 | No coordination; no leakage; spreads writes | 16 bytes; random index inserts; no order | Public tokens; range-partitioned stores |
| UUID v7 or ULID | No coordination; sortable; index-friendly | 16 bytes; reveals creation time; range hot spots | New systems on single-node databases |
| KSUID | 128 random bits; sortable to the second | 20 bytes; second resolution | Event IDs where collisions must be unthinkable |
| Snowflake | 8 bytes; time-sortable; local generation; embeds time | Worker ID management; clock handling; JavaScript precision | Large-scale 64-bit IDs, such as posts and messages |
Common Pitfalls#
- 32-bit primary keys that overflow at 2.1 billion rows. Use 64-bit keys from the start.
- Random UUID v4 primary keys on large InnoDB tables, causing slow inserts and bloated indexes once the table outgrows memory. Use v7, or a sequential internal key.
- Storing UUIDs as
VARCHAR(36): more than twice the size, slower comparisons. Use native types. - Two Snowflake workers with the same worker ID, from copied configuration or expired leases: frequent duplicates.
- Ignoring backward clock steps, so a generator reissues IDs after an NTP correction or VM resume.
- Sending 64-bit IDs as JSON numbers, which JavaScript rounds above 2 to the power 53.
- Sharding by the low bits of a Snowflake ID, which are mostly the sequence and badly skewed.
- Time-ordered keys in Spanner, Bigtable or HBase, creating a hot range.
- Using time-based IDs as secrets, when they are predictable to the millisecond.
- Assuming IDs are gapless or that commit order matches ID order when tailing a table by ID.
- Using a weak or identically seeded random generator on cloned VMs, turning theoretical collision odds into real duplicates.
- Exposing sequential IDs publicly, enabling enumeration and volume estimates.
Real-World Examples#
- Twitter created Snowflake in 2010 for tweet IDs during its move to Cassandra, with a 41-bit millisecond timestamp, 10-bit worker ID and 12-bit sequence, and added
id_strto its API so JavaScript clients would not corrupt the IDs. - Discord uses Snowflake-format IDs for users, messages and channels, with an epoch of the first second of 2015, and documents how to extract the timestamp from any ID.
- Instagram described in 2012 generating 64-bit IDs inside PostgreSQL with PL/pgSQL, combining a millisecond timestamp, a 13-bit logical shard ID and a 10-bit sequence, so every ID also identifies its shard.
- Flickr described ticket servers in 2010: two MySQL servers handing out odd and even 64-bit IDs through
REPLACE INTOandLAST_INSERT_ID(). - MongoDB drivers generate 12-byte ObjectIds client-side, with a 4-byte timestamp, a 5-byte random value per process and a 3-byte counter, so documents have IDs before reaching the server.
- Segment published KSUID in 2017, with a 32-bit seconds timestamp and 128 random bits, for its event pipeline.
- Sony published Sonyflake, with 10 ms time units, an 8-bit sequence and a 16-bit machine ID taken by default from the private IP address.
- Meituan open-sourced Leaf, with a database segment mode using double buffering, and a Snowflake mode with worker IDs assigned through ZooKeeper.
- Stripe uses prefixed IDs such as
cus_andpi_, which make the object type visible in every log line and support ticket.
In the Interview#
Deep Dive: Designing an ID scheme for a global platformShow
Requirements. A messaging platform runs in 4 regions, with up to 200,000 messages per second at global peak and 80,000 in the busiest region. Message IDs must be unique globally, sort by time within a conversation for pagination, fit in 64 bits for compact storage in a wide-column store, and be generated in the region where the message is sent, with no cross-region calls. Lifetime: at least 30 years.
Bit budget.
- Timestamp: 41 bits of milliseconds from a 2025 epoch, about 69 years.
- Region: 2 bits for 4 regions, 3 bits to allow 8 in future. Take 3.
- Worker: 7 bits, 128 generators per region.
- Sequence: 63 minus 41 minus 3 minus 7 leaves 12 bits, 4,096 per millisecond per worker.
Capacity per region is 128 workers times about 4 million per second, vastly more than 80,000. The real constraint is the worker count, which bounds how many service instances can embed a generator. If message-sending services autoscale beyond 128 pods per region, either run a dedicated ID service with a few instances, which callers reach in under a millisecond within the region, or have pods fetch blocks of Snowflake IDs from those instances, amortising the hop.
Worker leases. Each generator instance leases a worker ID from the regional etcd cluster with a 10-second lease, renewed every 3 seconds, and stores its latest issued timestamp in the lease's key every few seconds. On losing the lease, it stops issuing IDs immediately. A new instance claiming a worker ID reads the stored timestamp and waits until its clock passes it, plus a margin of a few seconds, before issuing. This closes the "same worker ID, overlapping time" gap, even if an old instance was paused when its lease expired, because the new instance only issues IDs with timestamps later than any the old one could have recorded, and the old one stops when it notices its lease is gone. If an old instance resumed from a long pause and issued IDs before checking its lease, its timestamps would be from the new time too, which is the residual risk; checking the lease's remaining validity, measured on a monotonic clock, before each batch closes most of it, and the store's uniqueness check catches the rest.
Ordering semantics. Messages in one conversation are written by different senders in different regions. Two messages sent 2 ms apart from different regions may be ordered the wrong way by ID if their clocks differ by more than 2 ms. For a chat UI, that is acceptable, but the server should assign the ID when it accepts the message in the conversation's home region if strict per-conversation order matters, because then one region, and often one partition owner, orders the conversation.
Client-generated IDs for idempotency. Mobile clients also generate a client message ID, a UUID v4, when the user taps send, and retry with the same ID if the network fails. The server deduplicates on it within a window, and assigns the Snowflake ID only once. The two IDs serve different purposes: one for idempotency, one for ordering and storage. See Idempotency.
What breaks and what saves us.
| Failure | Effect | Defence |
|---|---|---|
| Clock steps back 3 ms | Generator would reuse a millisecond | Wait out small steps |
| Clock steps back 2 s | Same, for longer | Refuse and alert; instance drains |
| Two instances with worker 37 | Duplicate IDs | Leases, stop on lease loss, wait past stored timestamp |
| etcd unavailable | New instances cannot claim workers | Existing instances keep issuing while their leases last |
| Region added | Needs a new region code | Spare region bits reserved up front |
Deep Dive: The mathematics of collisionsShow
The birthday problem. With n values drawn uniformly at random from N possibilities, the probability that at least two are equal is approximately 1 minus e to the power of minus n squared over 2N. When n squared is much smaller than N, this is about n squared over 2N. The name comes from the surprise that 23 people have about a 50% chance of sharing a birthday among 365 days: the number of pairs grows with n squared, 253 pairs for 23 people. Collisions become likely when n reaches about the square root of N, so a random ID with b bits gives meaningful collision risk after about 2 to the power b/2 IDs.
| Random bits | Square root of space | About 50% collision after | One-in-a-billion collision after |
|---|---|---|---|
| 32 | 65,536 | 77,000 | About 3 |
| 48 | 16.8 million | 20 million | About 750 |
| 64 | 4.3 billion | 5 billion | About 190,000 |
| 80 | 1.1 trillion | 1.3 trillion | About 49 million |
| 122 (UUID v4) | 2.3 times 10 to the power 18 | 2.7 times 10 to the power 18 | About 100 trillion |
| 128 | 1.8 times 10 to the power 19 | 2.2 times 10 to the power 19 | About 820 trillion |
The one-in-a-billion column uses n equal to the square root of 2N times 10 to the power minus 9. The lesson: 64 random bits are not enough for a system that will create billions of IDs, since collisions become likely in the billions, and even 80 bits allow a non-trivial chance at tens of billions. That is why random IDs use 122 to 128 bits, and why 64-bit IDs use structure, timestamps plus worker IDs plus sequences, or counters, rather than randomness.
Random short codes. A URL shortener using random 7-character base62 codes, about 3.5 times 10 to the power 12 possibilities, has a different question: not "any collision ever?", which is certain after a few million codes, but "how often does an insert collide with an existing code?". With n codes stored, a new random code collides with probability n divided by N. At 1 billion stored codes, that is 1 billion divided by 3.5 trillion, about 0.03%, so about 1 insert in 3,500 needs a retry. At 100 billion codes, it is 3%, still workable with retries, but each retry costs a database check. A UNIQUE constraint plus a bounded number of retries, such as 3 to 5, handles this; if retries become common, lengthen the code by one character, which divides the collision rate by 62.
Hash truncation. Taking the first 8 base62 characters of a SHA-256 hash gives about 47.6 bits. Hash outputs behave like random values for this purpose, so the birthday table applies: a 50% chance of some collision is reached at about 17 million URLs. Deterministic hashing does not avoid collisions, it only makes them repeatable, and the same retry-with-salt scheme is needed.
When randomness fails. All of this assumes good randomness. Real duplicate UUIDs in production have come from virtual machines cloned with the same random generator state, from containers that started with an identical seed, from non-cryptographic generators with only 32 or 48 bits of internal state, and from client devices with broken generators. The defence is to use the operating system's cryptographic generator, and to keep a uniqueness constraint, so a collision is an error to handle, not silent corruption.
Deep Dive: IDs, deduplication and exactly-once pipelinesShow
IDs as idempotency keys. In distributed systems, messages are retried, so the same logical operation can arrive several times. If the producer assigns a unique ID when the operation is first created, every downstream consumer can deduplicate on it. This is the basis of idempotent APIs, where a client sends an idempotency key with a payment request, and of effectively-once processing in pipelines, where consumers record processed event IDs. The ID must be created before the first attempt and reused on every retry, which is why client-side generation, UUID v4 or v7 on the client, is the norm for idempotency keys. See Delivery Semantics.
Bounded deduplication windows. Storing every ID ever seen is expensive. With time-ordered IDs, a consumer can keep only IDs from, say, the last 24 hours, and reject anything older as too late, because the ID itself says when it was created. With random IDs, the consumer must store the arrival time separately. Time-ordered IDs also make deduplication stores friendlier: recent IDs cluster in the same index pages or SSTables, and old ones expire together. A Bloom filter over recent IDs can answer "definitely not seen" cheaply before an exact lookup. See Probabilistic Data Structures.
Kafka's producer IDs and sequence numbers. Kafka's idempotent producer is an ID scheme applied to messages: the broker assigns each producer a producer ID, and the producer numbers every message per partition with a sequence number. The broker rejects any message whose sequence is not the next one expected for that producer and partition, which removes duplicates caused by producer retries. It is a counter per producer and partition, a scoped ID that needs no global coordination.
Ordering and IDs in event logs. In an event log, the offset assigned by the broker is a perfect, gapless, per-partition ID, as it is assigned by the single leader of the partition. Many systems use (partition, offset) as a unique event ID for downstream processing, and keep the producer's own ID for end-to-end deduplication across retries that reach the log twice.
Content-addressed IDs. Some systems derive the ID from the content itself, using a cryptographic hash: Git identifies objects by the SHA-1 or SHA-256 of their contents, and content-addressed storage systems do the same. Identical content gets the same ID, deduplicating automatically, and the ID verifies the data's integrity. The cost is that the ID cannot be known before the content is final, and any change creates a new ID.
Key Takeaways#
- Decide the requirements first: scope of uniqueness, time ordering, size (64 or 128 bits), public exposure, rate and lifetime. They decide the scheme.
- With one database, use its sequence or identity column with a 64-bit type. Gaps and commit-order differences are normal.
- Counters scale across many servers with ticket servers, Redis
INCRand, best, block allocation, which needs one counter call per thousands of IDs; aUNIQUEconstraint guards against counter loss. - UUID v4 has 122 random bits and needs no coordination, but its random inserts hurt B-tree indexes. UUID v7 and ULID put a millisecond timestamp first, so they sort and insert locally.
- Snowflake packs 41 bits of milliseconds, 10 bits of worker ID and 12 bits of sequence into 64 bits: about 69 years, 1,024 workers and 4,096 IDs per millisecond each. The worker ID must be unique, so lease it.
- Time-based IDs depend on clocks: wait out small backward steps, refuse large ones, persist a high-water mark across restarts, and never run two generators with one worker ID.
- Time-ordered keys help single-node B-trees but create hot spots in range-partitioned stores. Send 64-bit IDs as strings in JSON. Never use time-based IDs as secrets.
- Many systems use two IDs: a compact internal key for storage and an opaque public ID for URLs and APIs.