Unique IDs at scale: auto-increment, UUIDv4, UUIDv7 and Snowflake

Choosing an ID format feels like a five-minute decision, and it usually gets five minutes. Then, a few years later, it turns out to have decided how fast your inserts are, whether you can split the database, what your URLs tell competitors, and how easy it is to find things during an incident.
This is a solved problem: there are four well-understood answers, each with a clear sweet spot. Here's how to pick.
What we want from an ID
- Unique, obviously, including across services and regions.
- Generated without coordination, so creating a record doesn't need a round trip to a central counter.
- Index-friendly: new IDs should land near each other in a B-tree index, not scattered randomly.
- Roughly time-ordered, which helps indexes and makes "what happened around then?" easy.
- Compact enough for your storage and your keys.
- Safe to show to users without leaking business information.
No option is best at all six. That's why there are four options.
Option 1: database sequences (auto-increment)
BIGSERIAL, AUTO_INCREMENT, IDENTITY. The database hands out 1, 2, 3…
Good: compact (64 bits), perfectly ordered, ideal for indexes, and easy to read in a log.
Bad: the database is the coordinator, so you can't create an ID before talking to it, and two databases (after a split, or in two regions) produce clashing IDs. And they leak: if a customer sees order #109847 at the end of March and #104312 at the start, they know you took about 5,500 orders that month. So does any competitor willing to buy from you twice.
Use it for: internal keys inside a single database, never shown to users. That's still most tables in most systems, and it's a fine choice there.
Option 2: random UUIDs (UUIDv4)
122 random bits. Any service can generate one, anywhere, with no coordination, and collisions are not a practical concern.
The cost shows up in the database. Each new UUIDv4 lands at a random position in the primary key index. On a large table, inserts touch pages all over the index instead of the same few "hot" pages at the end, which means more page splits, more cache misses and more disk I/O as the table grows. The bigger the table, the more you feel it. They're also 128 bits, twice the size of a BIGINT, in every index and every foreign key.
Use it for: identifiers that don't sit in a large B-tree index (idempotency keys, correlation IDs, tokens), or small tables where it doesn't matter.
Option 3: time-ordered UUIDs (UUIDv7)
UUIDv7, standardised in RFC 9562 in 2024, keeps the UUID format but puts a millisecond timestamp in the first 48 bits and fills the rest with random bits. You get the coordination-free generation of UUIDv4, and IDs created around the same time sort next to each other, so inserts go to the end of the index like a sequence.
Generating one by hand is a few lines:
private static final SecureRandom RANDOM = new SecureRandom(); static UUID uuidV7() { long millis = System.currentTimeMillis(); long msb = (millis << 16) // 48-bit Unix timestamp in milliseconds | (0x7L << 12) // version 7 | RANDOM.nextInt(1 << 12); // 12 random bits long lsb = (RANDOM.nextLong() & 0x3FFF_FFFF_FFFF_FFFFL) | 0x8000_0000_0000_0000L; // RFC variant bits return new UUID(msb, lsb); } In production, prefer a maintained library or your database's built-in generator if it has one; they handle details such as ordering within the same millisecond.
The trade-off: the creation time is readable from the ID. That's usually fine, and occasionally useful in debugging. If the creation time is sensitive, don't expose the ID (see below).
Use it for: primary keys in new systems with more than one writer. It's my default.
Option 4: Snowflake-style IDs
Twitter published this design in 2010, and many systems use variations of it: a 64-bit integer made of a timestamp, a worker number and a per-worker sequence:
| 41 bits: ms since a custom epoch | 10 bits: worker id | 12 bits: sequence | That's about 69 years of timestamps, 1,024 workers, and 4,096 IDs per millisecond per worker. You get time order and coordination-free generation in half the space of a UUID.
synchronized long nextId() { long now = System.currentTimeMillis() - EPOCH; if (now < lastMillis) { throw new IllegalStateException("Clock moved backwards; refusing to issue IDs"); } if (now == lastMillis) { sequence = (sequence + 1) & 0xFFF; if (sequence == 0) { // 4,096 used this millisecond: wait for the next while ((now = System.currentTimeMillis() - EPOCH) <= lastMillis) { Thread.onSpinWait(); } } } else { sequence = 0; } lastMillis = now; return (now << 22) | (workerId << 12) | sequence; } The space saving costs two operational problems that UUIDs don't have:
- Worker IDs must be unique. Two instances with the same worker ID can generate the same ID. You need a way to assign them: a lease in a coordination service, a database row each instance claims at startup, or the pod's ordinal in a stateful set.
- Clocks go backwards. NTP corrections and virtual machine migrations happen. The generator has to detect it and wait or refuse; it must never reuse a timestamp.
Use it for: when IDs must be 64-bit integers: an existing BIGINT schema, very large tables where 128-bit keys are too costly, or systems that need IDs to be sortable as numbers.

Two questions decide most cases. Explore the interactive diagram
The rule that removes most of the dilemma
The ID in your database and the ID in your URL don't have to be the same thing.
Keep an efficient internal key (a sequence or UUIDv7) for joins and indexes, and give anything a user can see a separate, opaque public ID: a random string, or an encoded form of the internal key that can't be reversed. Then you can choose the internal key purely for performance, and the public ID purely for privacy. You also stop users guessing neighbouring IDs, which makes some authorization bugs harder to exploit. (It doesn't replace the authorization check; I wrote about that in IDOR: the most common API bug.)
Side by side
| Sequence | UUIDv4 | UUIDv7 | Snowflake-style | |
|---|---|---|---|---|
| Size | 64 bits | 128 bits | 128 bits | 64 bits |
| Needs coordination | Yes (the database) | No | No | Worker IDs only |
| Index-friendly inserts | Yes | No | Yes | Yes |
| Time-ordered | Yes | No | Roughly (ms) | Roughly (ms) |
| Safe to show users | No (leaks volume) | Yes | Mostly (leaks time) | Mostly (leaks time) |
| Operational risk | Database is the bottleneck | Index growth on big tables | Low | Clock and worker ID bugs |
Takeaways
- Inside one database, a sequence is still a great primary key. Just don't show it to users.
- UUIDv4 scatters inserts across the index; it's fine for tokens and keys, poor for big tables.
- UUIDv7 gives coordination-free, time-ordered IDs. It's a sensible default for new systems.
- Use Snowflake-style IDs when you need 64 bits, and budget for worker IDs and clock handling.
- Separate the internal key from the public ID, and most of the trade-offs disappear.
Originally published at ayushwing.com.