I don't know how to navigate commitfest (nor would I probably understand the source code to begin with), but the reason I'm confused is that you can already use all the proposed draft UUID implementations in Postgres (as long as you generate the ID application-side). In fact, PG will happily accept any 128 bit ID to be inserted into a UUID column, as long as it's hex encoded – even the dashes are optional.
If you want to do something smart like encoding your node ID within the value, or prefixing a timestamp for sortability, then sure, do that in your application. No one else really needs to care how you produced your 16 bytes. Just do some napkin math to make sure you're keeping sufficient entropy
I'm not sure "UUID" even needed to be a column type, versus a "INT16" and some string formatting/parsing functions for the conventional representation (should you choose to use that in your application). You could also put IPv6 addresses in the same type. Though I guess this depends on how much you think the database should encode intention versus raw storage in types
UUID isn't about how it's done, it's about what it is.
Instead of everyone doing something differently, everyone can just comply with UUID.
Instead of having to repeat it across your docs that the IDs of this entity are sortable, you can just say they are UUIDv7. If someone wants to extract the timestamp from your ID, they don't need to figure out which (32, 48, 50?) bits are the timestamp nor what resolution the timestamp has because you can tell them UUIDv7.
You don't have to write your own validation functions because you can tell the database that this hex string is a UUID and it can do it for you.
You're probably making the case for Sqlite here which is very minimal, but something more full-featured like Postgres, I prefer these conveniences. I can tell because whenever I use Sqlite in a case where I could've used Postgres, I regret it!
Most functional things related to e.g. embedding the record creation time within the ID is one of those "that's cool, but I've never seen anyone do it" kind of things. If you need to sort records by when they were created, there are probably three or four happened_at fields on the record you'd use (created_at in this case). If you need the exact time; those are there for that.
Counter-argument: Well, you can save a few bytes on every record by getting rid of the created_at field and just using a UUIDv7. Maybe, but I've never seen anyone do it. What if you need to change the time the record was created? Are you planning to explain to all your integration providers the process of extracting a timestamp from a UUIDv7? What if you need to run complex SQL timestamp functions on created_at? Etc. Its cool, but it never actually happens.
Once we enter the domain of "using the node id or timestamp or something to reduce the probability of ID collision", that's a totally reasonable responsibility within an ID's set of concerns. But, that's a very different need.
> You don't have to write your own validation functions
Why are we validating IDs?
> but something more full-featured like Postgres, I prefer these conveniences.
Agreed. I am a vocal UUID hyper-hater. UUIDs should be destroyed, and humanity would be (oh so slightly) better off if they had never existed. But, they're still a thing, and I think its cool that databases have hyper-specific types like this.
My wish is Postgres would have other more sane automatic ID types and gen capability, in addition to uuid & autoincrement.
With which UUID ? UUID v1 ? UUID v2 ? UUID v3 ? ... UUID v7 ?
The practical necessity of mixing UUID versions, along with other 128-bit UUID-like values, means that the collision probabilities are far higher in many non-trivial systems than in the ideal case of having a single type of 128-bit identifier. There is a whole separate element of UUID-like type engineering that happens around trying to mitigate collision probabilities when using 128-bit identifiers from different sources, some of which you may not control.
Having 128-bits is the only common thread across these identifiers which everyone seems to agree on.
If you're building for a single application or data type, sure do your thing, have at it. If you're trying to coordinate UUID spaces and generation across thousands of different applications and data types, like large data pipelines, then this matters a lot.
Also, having native database support (like indexing, filtering, etc.) improves efficiency for these types of workloads.
It's really more about convenience, and maybe a bit of speed.
1: https://gist.github.com/fabiolimace/515a0440e3e40efeb234e126...
Conflating timestamps and uniqueness is a conflation. These concerns are best separate. If you put a timestamp in your UUID, your UUID now has a timestamp. You can't remove it if you don't want the timestamp to be a part of the uniqueness any more.
- sortable by insertion
- less vulnerable to sequence prediction attack
- allows partitioning of tables in the future
Sequence prediction attack is a problem when you want to use identifiers in a public API. For example, a user or competitor can iterate through your product catalogue by incrementing the key. Sorting by inserting is a common use case as well. You can achieve this with an auto-incrementing primary key, however, this will create issues when you need to partition the table. Of course, you may never need this functionality, but there is a reason UUID7 have been added, as they are very useful in certain scenarios.Which leaves partitioning, something that very few applications will ever need, even if plenty of developers hope they will. A slightly less weird use case, but perfectly doable up to a point using regular sequences.
I see a solution looking for problems.
Then select * from item where id=123 and vf='ixkdS1Xb'
I fully agree and support that auto-incrementing integers should be used whenever possible. My preference for UUIDv7 over UUIDv4 is solely that they’re less likely to wreak havoc on the DB, if devs insist on having a UUID PK.
|------------------------------|-----------------------------|------------|----
| primaryKey (bigInt-internal) | publicKey (uuidv4-external) | created_at | ...
|------------------------------|-----------------------------|------------|----
(2) |------------------------------|-----------------------------|------------|----
| primaryKey (uuidv4-internal) | publicKey (uuidv4-external) | created_at | ...
|------------------------------|-----------------------------|------------|----
(3) |------------------------------|-----------------------------|----
| primaryKey (uuidv7-internal) | publicKey (uuidv4-external) | ...
|------------------------------|-----------------------------|----
(4) (not recommended)
|---------------------|----
| primaryKey (uuidv7) | ...
|---------------------|----
---- (1) [X] sortable by insertion, [X] timestamp
(2) All of (1) and [X] transferable between databases
(3) Use UUIDv7 as a primary key for internal and UUIDv4 for external. App or SELECT statement will need to extract the timestamp from UUIDv7 if you need to use it. Also, if you're using a DB Client you can't just view the 'created_at' column to get an idea of when a row was created.
(4) Use UUIDv7 as a primary key for internal & external use.Over time conflicts between the id's primary job (uniquely identifying something) and the extra semantics can arise, and the solutions tend to get pretty messy.
Here we have a unique id that embeds a timestamp. The classic conflict here is with privacy/security. A UUIDv7 user id tells you when the user was created. A UUIDv7 of a medical record tells you when some medical event occurred.
There are things whose identity is inherently time-based and not private, so I'm not giving a blanket recommendation to not use these. Just understand what you are signing up for.
For a database, you can use bigints for primary ids but only internally. Then you also have an external random (v4) uuid... and a timestamp if you want, for that matter -- now that it's a separate column, you can expose/hide it on a case-by-case basis, depending on need. So this gets you the benefits of a uuidv7 but maintains flexibility, though at the cost of some complexity and extra bytes/record.
Other conflicts can arise too, and they can be hard to always foresee, so generally be careful about extra semantics in unique ids.
Our competitor was able to ascertain, based on that timestamp, when our customers contract was up and was (briefly) able to poach some customers by underbidding us until we corrected this.
I'm so naively the "take the high road" kind of guy, that I just assume everyone (or every company) should just do the right thing. Stealing customers in this way from a competitor, I have no ability to rationalize such an action.
And this kind of makes me scared, like if I were to ever own a business, I just know I'm swimming with sharks with no ability to defend.
I believe your story, but it's just crazy to me. Go earn a customer's business in a legit way, not be stealing data from a competitor.
If that's an issue for you, you can get around this in a variety of ways, as they mention: you could use an associative table that maps the externally-exposed random ID to an internal-only ID.
It tells you when the event was documented. If the event didn't contain a date time stamp itself, I would be highly surprised, because what other value is there in documenting it?
The security problem here is inherent in the practice and your choice of primary key isn't a material factor at all.
Do you imagine there's a public CRUD database with simple Rails style accessors that can drill all the way down to individual event records inside my health information? And that, somehow the leak of a primary key in a URL might give away the fact that _something_ happened to me, medically, 12 days ago?
Just as a side note: it may also leak the location, not just the time. An that is enough e.g. for disproving an alibi or leaking an important commercial secret (if you are in the same location as competitor HQ, for example).
I cannot rightly apprehend the scenario you are describing. A medical provider might generate a UUIDv1 and add it to a record of mine, and this will somehow destroy my ability to have an alibi in court with respect to corporate espionage?
I'm not in a bond movie, I just need to keep track of events and have them sort in chronological order
While it’s no longer on ranks on the top 10 web vulnerabilities, gaining internal insight to systems is one of first things you do when infiltrating.
But people are messy and lazy. Nowadays, you ask for GDPR data and people give you CSVs with all their real table and column names.
Sometimes when you are just a little inside, figuring out an id is like figuring out a password (particularly with uuid as opposed to a sequence). Real nice if it leaks easily.
IMHO, leaking an ID always impose a risk. It is always have negative impact if leaked, no matter how perfect your system is.
We must live in a different universe. I'd wager to say that over 90% of all backends leak their primary key when speaking to the front-facing client.
That sounds like a problem which should be solved by making database engines not assume keys have some sane ordering, not by putting timestamps in UUIDs.
It is quite possible to do cluster-style indexing on UUIDs through disk on a single server at rates of tens of millions per second, I do it every day, just not with your typical ordered-tree architectures. Many popular database engines are not designed to make this particular scenario perform well.
It would be quite unfortunate to end up with a UUID v7 in PostgreSQL that’s not quite the standardized one because the patch got merged too quickly.
EDIT: here is the IETF working group page https://datatracker.ietf.org/wg/uuidrev/about/
Their milestone seems to submit the final proposal by March.
The chances of that seem extremely low at this point. The contents of a version 7 UUID have not changed since work started on RFC 4122 bis in October 2022: https://author-tools.ietf.org/iddiff?url1=draft-ietf-uuidrev...
For me the main challenge was that it's still considered a draft (AFAIK). It may be unlikely to change, but if it does I'd rather not have to deal with persistent UUIDv7 data generated per some previous spec.
Also, if I really want/need UUIDv7, it's not that hard to create an extension that generates UUID in arbitrary ways, including the proposed v7.
Correct. The sortable nature of UUIDv7 improves database performance and index locality by helping the index be more efficient since rows are inserted in a predictable order instead of scattered randomly.
UUIDv7 spec: https://www.ietf.org/archive/id/draft-peabody-dispatch-new-u...
The current draft can be found here: https://datatracker.ietf.org/doc/draft-ietf-uuidrev-rfc4122b...
The optimization relevant to v6 also applies to v7. The difference is that v7 UUIDs are not directly compatible with v1 UUIDs.
It seems the algorithm is equivalent to:
function nanoid(alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") {
return Array.from(crypto.getRandomValues(new Uint8Array(21)), i => alphabet.charAt(i & 63)).join('');
}
(Maybe String.fromCharCode() is slightly faster than Array.join(), but I doubt it matters much.)On node.js it's even easier, since url-safe base-64 encoding is supported natively:
Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64url').substring(0, 21)
Do we really need an entire Github project dedicated to a 1-liner?* Using uncoordinated random generation in a large address space for IDs is often a very useful idea
* 128 bits is a good rule of thumb for "will never ever collide"
* Making this into a heavyweight "UUID" concept, with it's own bespoke string format, and 7 different standard ways to generate them, feels like a ridiculous waste of cognitive effort that makes such a simple concept appear opaque and magic. If you want to encode other data (timestamp, node ID) in 16 bytes you can still do that of course. There's no need for anyone else to even know. Just do some quick calculations to ensure you haven't eliminated too much entropy
It depends.
True random number are slow. Fast PRNG are prone to collision. That's why we have different specs and versions of UUIDs.
That would mean it's easy to update old apps, as we would only have to change the default value for the columns.
It’s a good thing to keep in mind though for sure.
Those two sucks for us right now (planning to move to UUIDs).
Wouldn't Snowflake IDs also solve that problem? A Snowflake ID will fit within a signed 64-bit int.
https://en.wikipedia.org/wiki/Snowflake_ID
The nice thing about a Snowflake ID is that you can encode it into 11 characters in base 62. If I have a UUID, I'm going to need 22 characters. Maybe that doesn't really matter given that 11 characters isn't something someone will want to be typing anyway and Snowflake IDs do require a bit of extra caution to make sure you don't get collisions (since the number you can make per second is limited to how big your sequence generation is).
Integers don't scale because you need a central server to keep track of the next integer in the sequence. UUIDs and other random IDs can be generated distributed. Many examples, but the first one that comes to mind is Twitter writing their own custom UUID implementation to scale tweets [0]
[0]: https://blog.twitter.com/engineering/en_us/a/2010/announcing...
- client-side generation (e.g. can reduce complexity when doing complex creation of data on the client side, and then some time later actually inserting it into to your db)
- sequential ids leak competitive information: https://en.wikipedia.org/wiki/German_tank_problem
- Global identification (being able to look up an unknown thing by just an id - very useful in log searching / admin dashboards / customer support tools)
If your system ever becomes distributed you will sing the praises of whoever choose UUID over an int ID, and if it never becomes distributed UUID won't hurt you.
Note: this is for web systems. If it's embedded systems then the overhead starts to matter and the usefulness of UUID is probably nil.
Less of an issue if you have total control of the operational environment and code base, but that is not always the case.
I’ll again point out (I said this elsewhere in a post today on UUIDs) that PlanetScale uses int PKs internally. [0] That is a MASSIVE distributed system, working flawlessly with integers as keys. They absolutely can scale, it just requires more thoughtful data modeling and queries.
[0]: https://github.com/planetscale/discussion/discussions/366
You cursor on timestamps, or serial numbers, or etc., not IDs.
Some comments: https://news.ycombinator.com/item?id=39261469
https://news.ycombinator.com/item?id=36433481
And have a look at this post from last year: https://news.ycombinator.com/item?id=36438367
EDIT:
For those who misunderstood: I'm very much pro-UUID, and against serial autoincrement server-generated IDs. With the exception when you need to heavily optimize for speed and/or index storage space. And even then there are hybrid solutions like using UUID externally, and serial IDs internally.
Generating IDs away from the database is mainly done due to design restrictions demanding it, not because it is beneficial.
2. the UUID by itself doesn't authenicate or authorize anything
3. there is a small chance of collision, and it can be handled on the backend/persistance/DB layer, i.e. return error to the client in case of collision and ask to generate a new UUID
4. many non-trivial and/or CQRS/ES apps work like this
5. if you are really paranoid, you can push down UUID generation logic to BFF (Backend-For-Frontend) layer
6. Lots of DistSys problems can be solved with client-generated IDs. But most people mistakenly think that DistSys applies to backend only, and exclude clients from the picture.
7. Scaling RDBMS (especially Postgres) is hard. UUID generation is slower than serial bigint, so it's best to keep it outside DB layer fo this reason also.
8. Client-generated UUIDs help to make client requests idempotent, and enable error handling with retries (although it's better to add an additional layer of request idempotency with IDEMPOTENCY_KEY HTTP header, or GraphQL Relay's clientMutationID).
Sure you are. You're trusting the client to send you valid data.
> 2. the UUID by itself doesn't authenicate or authorize anything
Okay, better hope no one ever considers the UUID to be a unique randomly generated token.
Besides that, users might be tempted to submit "vanity" UUIDs if they get to decide their own identifiers, breaking assumptions about the system.
> 4. many non-trivial and/or CQRS/ES apps work like this
Cool, if your friends jump off a bridge, you gonna follow them?
But client-generated IDs make idempotency easier and remove whole classes of errors. They're typically a huge win.
Reason: I'm not a machine, so I dislike generating UUIDs by myself ;)