UUID Generator (v4 / v7)
You need a unique identifier. Maybe for a database primary key, maybe for a log correlation ID, maybe for a session token. Generating unique IDs that do not collide is harder than it sounds -- pick the wrong strategy and you get duplicates or performance problems.
Pick a version, set the count, generate. Copy the result.
v4 vs v7
Version 4 (random): Every bit is random. You cannot tell anything about when or where it was generated just by looking at it. Use this when you just need uniqueness and do not care about ordering -- distributed workers generating IDs independently, anonymous tokens, that kind of thing.
Version 7 (time-ordered): The first 48 bits are a millisecond-precision timestamp, the rest are random. UUIDs sort roughly in creation order. Use this when the ID is a primary key or you want records ordered by creation time without a separate created_at column.
Why v7 wins for database keys
UUID v4 is random. When you insert random values into a B-tree index (which is what most databases use for primary keys), every insertion hits a random leaf page. The database cannot batch writes efficiently, pages split constantly, and fragmentation gets ugly fast.
UUID v7 is sequential. Inserts append to the end of the index. Pages fill up in order. Less fragmentation, better cache locality, fewer page splits. If you are building a new table and the primary key is a UUID, use v7 unless you have a reason not to.
Format options
- Lowercase with hyphens --
aee9a902-3c7e-4f6b-8c1a-3d2e1f0a9b8c. Canonical RFC format. What most systems expect. - Lowercase compact -- same without hyphens. Saves 36 bytes per ID in legacy systems that cannot handle hyphens.
- Uppercase with hyphens -- matches Microsoft GUID conventions.
Other details
- Custom prefix -- prepend a namespace like
customer-to each ID so you can tell what type of entity it is at a glance.customer-aee9a9...versusorder-3f7b1a.... - The all-zero UUID (
00000000-0000-0000-0000-000000000000) is reserved. It means "no value." Do not use it as a primary key. - Collision probability for v4 is effectively zero. With 2^122 possible values, generating a billion UUIDs per second for a century would not produce a meaningful collision chance. Do not build collision-checking logic around UUIDs.