Unexpected downsides of UUID keys in PostgreSQL
cybertec-postgresql.com
cybertec-postgresql.com
UUID actually performs much better than I thought based on the author's example with a COUNT query. COUNT queries aren't very efficient because typically, all records are traversed; here we're talking about a 50% slowdown on 10 million records... How often do you need to access 10 million contiguous records? Most of the time, for user-facing apps, you'll be accessing 100 contiguous records at most and, in fact, most queries will access a single record... I suspect that the average per-query performance loss for a typical app is probably less than 5%. Also, you could simply index by a separate date/timestamp field if you need records to be ordered by time and probably won't incur any performance cost.
IMO, unless you're building an app for high-frequency trading, auto-incrementing IDs aren't worth the pain and lack of flexibility.
The loss of locality for reads is bad, especially for data sets that don't fit into cache / RAM (while the active set would).
Where it really bites you is writes, because it can trigger pretty massive write amplification.
Imagine you have 128 GB index on UUID column, that's ~16M pages (8kB) and insert 1M random values. Congrats! You've probably just wrote 8GB to the WAL, because of FPW and stuff like that. With serial IDs we'd write a fraction of that. It doesn't take much to hit max_wal_size and trigger a checkpoint, starting a new cycle with FPWs. Got a replica? Well, now you need to send the WAL over network. Is the bandwidth limited (another DC?), sorry to hear that. Is the replica sync and you have to wait. Well, that's unfortunate.
In other words, the lack of locality seems like a detail but at scale it's actually a damn huge deal.
UUIDs belong where you can't afford that simplicity. Where you e.g. cannot coordinate the creation of your primary keys. Or where you cannot allow them to be predictable. There you pay the price.
In practice I noticed that the size of PKs and their poor locality start to play a role only after a huge basket of lower-hanging fruit has been collected. There are relatively few places where their role is dramatic.
You often don't realize you you have non-simple needs until your application is reasonably mature, and in production. If you already picked integer keys, you now either forever deal with the issues caused by not using UUIDs, or you deal with the unknown-but-non-zero pain of converting to UUIDs.
You are writing your data into a DBMS. Coordinating the creation of primary keys is one of the cheapest tasks around, if you can't do that, how is your database still online?
> Or where you cannot allow them to be predictable.
You don't need to export your PKs for the rest of the world. You can have non-predictable data outside of your PK. Yes, a different column will still have some of the problems with index maintenance, but it becomes a much smaller problem if only one table cares about the value.
But sometimes you have to make these keys public, e.g. as user or other resource IDs. You want to make them UUIDs so they won't be predictable. Not having to join everywhere with the UUID-to-artificial-PK table may be a bigger performance win than the losses from larger size of UUIDs.
Sometimes you have a distributed / sharded system, and don't want the keys to clash, and also avoid assigning ranges. Sometimes you have to accept someone else's ID, not originating in your system. In cases like that, large random numbers, e.g. UUID v4, work reasonably well.
Of course when you just have one DB, and a relative slow stream of new rows, it's easy to fully control PK creation. And this covers the majority of practical cases.
https://github.com/estuary/flow/blob/master/supabase/migrati...
we use macaddr8 instead of bigint, because it has a postgres serialization / JSON encoding which lossless-ly round-trips with browsers and it works well with PostgREST. The same CANNOT be said for bigint, which is a huge footgun.
Is there some value to UUIDs over ULIDs that make these discussions largely revolve around Autoincrement vs UUIDs rather than Autoincrement vs ULIDs(and friends)?
[1]: Again, totally out of my wheel house.
edit: Apparently UUIDv7 exists, which is similar to ULID, so my question pertains to UUIDv5 and below, i think.
edit2: I think Nanoids do suffer the same problem. They're just small... i think.
One place we're avoiding ULIDs (and other counters) is in publicly-facing IDs. Preferring random to help keep them unguessable. (say what you will about security-through-obscurity).
So we do ULIDs for private IDs. Random UUIDs for public IDs. Seems to work well.
You don't have such issues with randomly generated ids, unless someone obtains a full dump of your database (in which case you will have to think about bigger problems anyway).
And the reason for that was to have lexicographically sortable IDs (even if not monotonic, which would require an extra server) so we didn’t have to index a timestamp column for chronological ordering. The alternative was to have a traditional integer sequence but it’s not always ideal to expose those on your API.
That also applied to our test suite so the choice was to use KSUID but still index a timestamp for accuracy, or just use an alternative with more precision.
Native DB support is irrelevant to me for randomized bits unless it affects storage, sorting, paging, etc. Does it?
You can also write a plpgsql function to generate these ULIDs in the database.
I ran into this last year - storing them as UUIDs works great, unless all of the drivers for the language you're using (Go, in my case) try to cast/validate those bytes as a UUID before you can access them.
So with high enough concurrent load it's effectively all random IO and that's the primary thing worth optimizing for.
Auto-incrementing IDs simply don't scale beyond a single host so I don't see how they can be good for scalability. Too many devs conflate raw performance with scalability. They are not the same at all - In fact, high scalability often incurs a performance overhead.
Not hyper scale, but good enough for failover or a 3-5 node setup.
If you wanted to (practically speaking anyway) overcome the requirement that K is known, you could borrow prefix based counting from the p-adics.
mysql> CREATE TABLE animals (
-> id MEDIUMINT NOT NULL AUTO_INCREMENT,
-> name CHAR(30) NOT NULL,
-> PRIMARY KEY (id)
-> );
Query OK, 0 rows affected (0.34 sec)
mysql> INSERT INTO animals (name) VALUES
-> ('dog'),('cat'),('penguin'),
-> ('lax'),('whale'),('ostrich');
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM animals;
+----+---------+
| id | name |
+----+---------+
| 3 | dog |
| 6 | cat |
| 9 | penguin |
| 12 | lax |
| 15 | whale |
| 18 | ostrich |
+----+---------+
6 rows in set (0.00 sec)Also, I don't think the blog (or me) suggested going back to using autoincrement IDs. There are other (better) options.
I mentioned only WAL for simplicity, but it also has to modify and write out the index pages themselves, and write them out eventually. And that's going to be mostly random I/O. Flash storage is good at handling that, ofc, but if things are adding up like this ...
Not to mention you still have to copy the WAL over network to replica, or perhaps to multiple replicas. And if you have physical backups with PITR, you gotta keep all the WAL somewhere too.
The GP was talking about the first graph here: https://www.2ndquadrant.com/en/blog/on-the-impact-of-full-pa...
If you care about the insert location, why not just add a brin index on a timestamp field and use that instead of assuming that the index is sequential.
The main source of write amplification comes from updating random pages of the btree index. Imagine inserting 10 random UUID values into a large index - it's pretty likely those will go into 10 different leaf pages. And every first update of a page after a checkpoint (which typically happens every 30 minutes or so), we have to write a FPI (i.e. the whole 8kB page) to WAL. So because btrees are based on ordering, random values end up on random leaf pages, causing write amplification.
If you have BRIN index on UUID column, this does not happen, because the index is not based on ordering but location in the table. If the 10 rows get appended to the same table page, that'll be just 1 write, with one FPI.
This is why BRIN does not have the write amplification issue. But it's also a bit pointless, because BRIN on random data is pretty useless for querying (Well, at least the minmax indexes, are. Let's ignore BRIN bloom indexes here.)
If you create BRIN on timestamp, that's not going to have write amplification problem, and it'll be good for querying. The thing is - BTREE would not have write amplification problem either, because the timestamps are going to be sequential (hence no updates to random leaf pages).
What this means in practice, of course, is that you shouldn't expect to do application driven pagination with UUID keys either. You would need to expose some other boundary marker with a total order that works well with btrees. And this could bring you back to "leaking" predictable key material that you were trying to hide by adopting UUIDs...
Your solution just doesn't really make any sense. The time ordered UUID suggested in the blog post makes way more sense.
One of the best things about UUIDs is that if your front end tries to create a resource and fails due to a bad connection, you can simply resend that exact same resource for creation again (with the same UUID) and you don't need to worry about duplicate records being inserted into the database since you would get an ID collision; it results in much simpler/cleaner code which is idempotent and deterministic by default.
With auto-incrementing IDs, if there is a connection issue or other failure, it's not possible to cleanly figure out if a resource was already created or not since only the database knows what the ID of that resource was until that ID is sent back and reaches the client across the network.
Just because the client did not receive a successful response from the server, it does not mean that the resource was not created; and if it was, you cannot know since the client has no way of referencing that resource in a reliable way. It just seems completely wrong that the client (which created the resource) cannot reference it until the database has inserted it.
It's a hack to pretend that resource creation starts in the database, when in fact, it starts on the front end.
Even in a single-host setup, it can be a problem because what happens if your process crashes and restarts just after a resource was created in the database but before the ID was sent to the client (with success message)? You would end up with a duplicate record in your DB after the retry since your newly restarted server would not have the UUID in its memory (even though the resource was in fact already created on the server a few milliseconds before the last crash).
With the Redis (or similar) solution, you need to make sure that the request UUIDs expire after some time and are cleaned up to avoid memory bloat which is a pain... I mean that complex solution probably uses up a lot more resources than just using UUIDs in the database as IDs.
If you add a column to store params as well then you can also do better validation:
> Responding when a customer changes request parameters on a subsequent call where the client request ID stays the same
> We design our APIs to allow our customers to explicitly state their intent. Take the situation where we receive a unique client request token that we have seen before, but there is a parameter combination that is different from the earlier request. We find that it is safest to assume that the customer intended a different outcome, and that this might not be the same request. In response to this situation, we return a validation error indicating a parameter mismatch between idempotent requests. To support this deep validation, we also store the parameters used to make the initial request along with the client request identifier.
https://aws.amazon.com/builders-library/making-retries-safe-...
The author isn't suggesting abandoning UUIDs, he is suggesting using something like UUIDv7 which preserves locality. For most use-cases, this seems like a very reasonable recommendation with no significant downsides I can think of.
You can also do that to get opaque identifiers from an auto-increment primary key.
Whether that tradeoff makes sense probably depends.
I find auto-incrementing IDs far more elegant in many ways. They are much easier to make sense of for users, they give you some loose metadata (ordering, sometimes a rough time range) which can be handy in debugging stuff.
At my previous workplace most things were auto-incrementing IDs, and while we got bitten by them a few times, there was significant debugging value in seeing a user ID as an integer. Internally, order IDs and customer support ticket IDs were also auto-incrementing, but we offset them so that even numbers were orders and odd numbers were support tickets, and this helped quite a bit with debugging or even just non-technical users sending each other references. Not that this can't be done with prefixes on UUIDs with a bit of extra work.
I wouldn't necessarily recommend auto-incrementing IDs or UUIDs over the other, but I don't think one is more elegant at all.
> to optimize access times by a millisecond or two. UUID is totally worth the cost.
2ms * 20 queries is 40ms, which could take a typical page load for a web app from 150ms to 190ms, which is quite a regression.
Not to mention the distributed database situation.
In fact I like that enough that I sometimes use ULIDs for secondary unique keys just so I have something to log, even if the primary key is numeric.
It's nice that you can store ULIDs in Postgres natively as UUIDs, and it's really nice to have a timestamp embedded in the ULID if you ever need it... but it's also really tempting to use it in public-facing stuff and thus leak your creation timestamp.
Out of curiosity, what makes UUIDs more elegant or beautiful than just plain old integers?
In a lot of cases that can be a pain due to overlapping integer primary keys and large parent-child table sets.
> To be able to generate keys independently of the database
> To move sets of related records between different databases without having to deal with renumbering everything
For most applications you are better off using a sensible structured key, like incrementing an integer or similar, and encrypting it if you want to obscure it. Encrypting a 128-bit value is approximately free on modern CPUs.
This is a must if you don't want to couple your domain logic and DB. I want to generate a record with an ID inside my domain layer without depending on the DB and doing awkward DB save - DB read.
If this isn’t a concern, then using a timestamp based approach as recommended in this article is a good approach. That is the default in MongoDB.
If it is a concern, one approach is to use random UUIDs to give to end users but then internally to have something like auto increment ids.
I found this approach to be more trouble than it's worth and plan on switching to a UUID PK key and doing away with the integer sequence.
Here are the complications I ran into:
The libraries I'm using for the ORM and API are designed to work with a primary key for single record get access. For example they want you to do `resource.get(ID)` where ID is the primary key, however, I now have to do `resource.find({ where: { uuid: 'myuuid' }})`. This is for all resources on all pages.
In Postgres, the integer PK sequence has a state that keeps track of what number it's at. In certain circumstances it can get out of sequence and this can trip up migrations.
We already have created_at and updated_at fields and these are probably better for ordering than the sequencing.
Had I to do it again, I would just use UUIDv4 until it runs into issues and either date fields or a sequence where necessary. If anyone has better ideas I would be most grateful as this is something I go back and forth on.
If you do not have two separate forms of identifier AND you have a "public" API (including basically any client apps, frontend JS, or anything found in query params) then you are making compliance with European regulators a massive headache when it comes to erasure of PII, since shared identifiers must be destroyed one way or another. Trying to merely delete the records is complicated by the fact that you need legal holds to comply with various federal laws.
Between the work involved in using two identifiers, one for joins and one for external lookups, versus the work involved in manually coding up all sorts of erasure work arounds, something I was in charge of in the past, I would strongly consider just using two IDs.
If your ORM gets in the way, just modify the ORM. This is easier than you'd think. For example, in Django just make a helpers module with something like this:
class OurModel(Model):
def get(...):
And have some sort of programatic way (lint, etc) of ensuring that your models.py doesn't use the stock class. It's simpler. It ruffles some feathers at first, but if your framework is getting in the way of a real use case just change the framework and don't worry about it.I don't quite follow on the European regulation issues raised by using as a UUID in a route and that being the PK of the record.
I know you should not expose PII or any information that can be used to identify a person, however, in our case any route is behind an authed login on an SSL connection which encrypts the path (we don't use query params).
The only place that contains data that ties a UUID to a person is in the database. This would be the case whether we used a PK as an integer or not.
Could you elaborate or share any resources around dual IDs DB design for PII compliance? That would be super helpful.
Regarding framework hacking or workarounds, I have a principle to not go against the grain of a framework. The reason for this is that modifying/hacking adds complexity when building on top of it or onboarding other software engineers. If necessary I'll do it as a last resort.
If your application only services a single user with their own resources then you have nothing to fear. But few applications meet this definition. If, for example, you're running an invoicing application, then at some point you'll want to share some resource, say an invoice or an expense or a time sheet, with another party. If your API exposes the identifiers from one resource to another, or even a user's id when potentially adding them to a team, then these identifiers are considered PII according to European regulators.
I understand that this is frustrating, but it comes from a posture that prioritizes right-to-be-forgotten over programmer ergonomics. Imagine, for example, API crawlers that hit your /search endpoint with email=[some predetermined list of emails] and harvest user ids to match with future data.
In the end, the best thing you can do is keep join keys internal and API keys separated. There are other workarounds, but they're so much trouble that they aren't really viable alternatives. Now, whether you use UUIDs for both identifiers or UUID for external and integer ids for join keys is up to you and your performance and scaling requirements. Personally, I prefer integer keys for internal unless I really expect the database to grow to more than 200m rows before the company hits 1000 people, since int ids mean you do not need secondary indexes on things like the created_at fields, but even there, it's not such a big deal to have an extra index on every table.
> I have a principle to not go against the grain of a framework. > hacking adds complexity
Here we essentially agree, but with the right integration tests, upgrading and onboarding is a lot easier than feared. That said, do not add to the framework unless the benefit is worth it.
I'm still having a little trouble grokking when an ID becomes exposed or shared so I guess I'll just have to read up on this as it's certainly important.
In our system I realized user IDs are not shared nor linked to (at least not yet) so in actuality the case where there's a URL with a UUID representing a person does not occur. Content generated does not reference UUIDs for persons either. There are URLs with UUIDs representing other types of resources.
By API key I take it to mean an access key for an external reference. That's a good idea for replacing the PK integer with a PK UUID but keeping an external UUID field. That would satisfy the concern with maintaining integer sequences and migrating data.
Anyway this has been helpful so thank you for sharing your thoughts and I have some things to look go on to stay in the good graces of European regulators.
I've used the int keys and UUID public keys on multiple projects - it wasn't an issue for EF core or RoR
On the efficiency side, joining and querying by id is generally more efficient on CPU usage for querying, but you do have to pay the cost of having the additional column and index.
For all my tables I have a base schema that looks something like this.
id: integer sequence PK uuid: uuidV4 created_at: datetime updated_at: datetime
The concern I have is when I have to distribute my system when scaling. Those numeric IDs will have to be replaced with the UUIDs so I figure I might as well do it now.
Lets say I have a <CAR>-[1:N]-<TRIP> in two tables in a relational DB. This works fine at first even for millions of rows as you say.
At some point in the future it makes sense to have these two entities managed by different team/services/db. Let's say TRIP becomes a whole feature laden thing with fares, hotels, itinerary, dates. So I need to take this local relation and move it to different services and different DB.
If I had been using an integer PK/FK this would be a more complicated migration than if I used UUIDs.
My assumption is that we would not want to have a sequenced integer key used in a distributed system.
In other words it seems safer bet if there's a possibility of needing to move to a distributed system to use a UUID for the key from the beginning.
What specific issues are you worried about with the integer key? Usually the issue is dupming data into something like a staging or development environment rather than a production concern. If you attempt to dump 2 datasets into one db you will have a conflict. Or if you write to an environment and then dump into you will have a conflict.
How soon is soon? And how would you handle it if you already had all PKs as UUIDs
I would use a date field to do ordering or a sequenced field when needed.
1. Size: If a client receives a record with id=10004578, they can guess that 4578 orders have been made.
2. Rate of growth: Receiving two different orders means they can track the growth rate of record insertion.
And also
Iteration attack: If your API endpoints do not have authorization, an attacker can try to access with GET /api/users/1, GET /api/users/2, GET /api/users/3, etc. UUID makes this next to impossible.
And so the company that did that data science realised they too were susceptible to exactly the same 'attack'. So they created a system to obscure the ids they were themselves exposing to their customers, using some cheap cut-down tea64 encryption iirc. My memory is it never went live, though.
You could also use a 32 or 64 bit block cipher like skip32 if you want to prevent reversal. Or at least, it makes reversing non-trivial.
> Do not encode sensitive data. This includes sensitive integers, like numeric passwords or PIN numbers. This is not a true encryption algorithm. There are people that dedicate their lives to cryptography and there are plenty of more appropriate algorithms: bcrypt, md5, aes, sha1, blowfish.
Use hashids to avoid the leak, and as a bonus your client-facing keys will be short and easily copy-pastable.
Every other issue with random UUIDs etc, which are ignored here, are solved by encrypting your identifier. Random UUIDs (i.e. UUIDv4) are banned in many places for good reasons.
To clarify this a bit, UUID v7 (or the existing ULID) are timestamps with random bytes at the end. You can learn when a UUID v7 was created. How do you infer the total size of the database from this information?
That said, the number of times those records are accessed is low, so there are no performance considerations.
On the topic of how important it is for B-trees to be "orderly": https://news.ycombinator.com/item?id=34404641
PostgreSQL can do (among other types) 32-bit hash indices which work out better for certain use cases. Personally I would avoid B-trees for any UUID unless I really had to do partial or ranged scans on them.
I don't think this is the same phenomenon at all, if anything that looks like an implementation problem rather than something that's somehow inherent in B-trees.
Depending on how you construct the tree, it's however still possible to end up with something that's very fragmented and inefficient, but you can always construct a dense b-tree with a space complexity of O(N/(B-1)). To see why you can just lay out the data in a list and manually create the index layers. Each layer will be bounded by N/B, N/B², N/B³, ... (and the sum of 1/B^n over all n is 1/(B-1) )
Considering an actual tree, for N=10, B=3
1 2 3 4 5 6 7 8 9 10 data
<3 | <6| <9 | <10 index 1
<6 |<10 | index 2
<10 root
Looking at this, I think it should be apparent that if you change this ordered sequence 1-10 to ten UUIDs ordered in the same way, there would be no change in the structure of the tree.It would be a bit bigger on disk because UUIDs are bigger than integers, and you may end up with an additional data layer because of that (because you want to align with the disk block size).
One reason you might see a difference even when the implementation makes the appropriate assumptions is that B-trees can do very clever things with somewhat sequential data when it comes to joins, where you can get linear nearly runtimes for the operation. But as mentioned, this only works with relatively ordered data.
That + Losing locality can be, for some workloads, a significant loss. Where UUIDs reign supreme for performance is in terms of generation - if you have a super high write load and really high latency requirements it may not be viable to have a single integer counter.
Although, in my own testing, I've found Postgres is more than capable of hundreds of thousands of increments per second and if you're willing to allow for gaps/ interleaving in your counter (slight hit to locality) you're really unlikely to hit a bottleneck.
Sequentual uuids help and are desirable but they still can't compete on storage :)
Are there any cases in Postgres where this actually plays a role and sequential ints get compressed?
The other data stores where I used this were a combination of Parquet on S3 (where you get compression) and ScyllaDB (where you also get compression).
I want this as a vscode extension.
Or maybe as a terminal plugin or something? Is that possible? Could tmux do it maybe?
Also I wish these sort of things would get encoded in base-36 (0-9 a-z) instead of base-16; that would help too.
If one doesn't truly need distributed creation of globally unique identifiers, it is so much nicer with base35-encoded integer sequences. Preferably loosely based on a timestamp.
> Impact of UUID choices: the choice of UUID has a significant impact on the layout of the B-tree, prior to compaction.
> For example, using a sequential UUID algorithm while uploading a large batch of documents will avoid the need to rewrite many intermediate B-tree nodes. A random UUID algorithm may require rewriting intermediate nodes on a regular basis, resulting in significantly decreased throughput and wasted disk space space due to the append-only B-tree design.
> It is generally recommended to set your own UUIDs, or use the sequential algorithm unless you have a specific need and take into account the likely need for compaction to re-balance the B-tree and reclaim wasted space.
And usually it is still worth it.
The knowledge is definitely out there, but almost all articles will be reaching for UUIDs, so this is understandably what most people end up with :/
select count(uuid) from records;
Makes absolutely no sense. You know the uuid is unique so you are deliberately selecting a value and then throwing it away just to count it. select count(1) from records;
Would give the same value and could be answered from the index without requiring a scan of the table.This is true of any unique column in the table no matter what type (it doesn’t have to be a uuid). The fact that uuids are a bit slower than other types of keys when you scan the entire table unnecessarily seems beside the point.
select
u.username as good_user
from
users u
where
not exists (
select 1 from naughty_users n where n.id = u.id
)
…is generally going to be much much faster than what a lot of people instinctively do which is to select the username or user id from the inner query. Since you’re just checking for (non)existence it doesn’t matter what the inner query returns so select 1 will answer the query from the index (assuming the id is indexed which if it isn’t you have bigger problems).If you spend a while looking at explain plans for your queries you will spot common patterns like this where you can avoid a table scan often.
The actual case came to my attention because an ORM insisted on generating the count(uuid) variant and I thought it peculiar that the performance difference was so large. But silly ORMs aside, the same problem will happen on any index only range scan over an index that has uuid in it. For a more realistic case, a `count(*) where somecol = 'value'` with a `(somecol, uuid)` index will hit the same problem. I thought the rather hidden single entry visibility map buffer reference cache was an interesting example where random ordering can cause performance problems.
1. They're ordered by a timestamp, so they preserve DB locality
2. They include a total of 74 bits of random data. This isn't enough to be used as unguessable keys, but it does offer some good protection if you have other bugs that could otherwise lead to IDOR vulnerabilities.
3. They're still 16 bytes, but IMO any minor hit to storage/time is completely worth it for the benefits they provide, especially since the other option is usually to have an integer primary key AND another "public ID" column that stores a UUID.
And then Andrey proposed a patch in the pgsql-hackers mailing list: https://www.postgresql.org/message-id/flat/CAAhFRxitJv%3DyoG..., https://commitfest.postgresql.org/43/4388/
Everyone who can help (test, discuss, etc.) – please participate in that discussion.
The standard is not finalized yet, but there some expectations that it will be, if it happens, it would be great to have this in future Postgres 17.
I have built a postgres extension for adding ULID support which does what I described. https://github.com/pksunkara/pgx_ulid
The three parts are:
- time-based leading bits.
- sequential counter, so that multiple UUID 7s generated very rapidly within the same process will be monotonic even if the time counter does not increment.
- enough random bits to ensure no collisions and UUIDs cannot be guessed.
Note that multiple rounds of cryptographic hashing is not considered sufficient anymore; PBKDF2 and Argon2 are Key Derivation Functions, and those are used instead of hash functions.
"New UUID Formats – IETF Draft" https://news.ycombinator.com/item?id=28088213
draft-peabody-dispatch-new-uuid-format-04 Internet-Draft "New UUID Formats" https://datatracker.ietf.org/doc/html/draft-peabody-dispatch... ; UUID6, UUID7, UUID8
And TBH I'm concerned that UUIDv1 had a timestamp, then it was removed completely in UUIDv4 and now the timestamp concept is being added back to UUIDv7... There are legitimate use cases where you simply don't want to have timestamps in your IDs.
Security consultants can be quite blunt in their approach and companies will often yield to their every demand for the sake of easy compliance and to avoid having to explain stuff.
[0]: https://youtu.be/mAyW-4LeXZo (Clock Synchronization in Distributed Systems by Martin Kleppmann)
If you want temporal locality, use ULIDs instead.
Yeap, UUIDv7 directly addresses the issues in the article. Warmly recommended.
(There is the issue that exposing ULIDs to users may 'leak' information about when things were created etc, but that is usually not a problem.)
So we've started making UUIDs that encode the current ISO8601 date+time in a human-readable format:
YYYYMMDD-HHMM-VRRR-RRRR-RRRRRRRRR
This is especially useful for things you have few of (no more than a couple per minute), that you regularly need to cross-reference with other systems (e.g. files on S3).If there was an index, the "old" part will be 99% empty. For regular UUIDs this would be fine, because new entries would get routed to this part of the index and the space would be reused. Not so for sequential UUIDs (v7/v8).
This is mostly why year ago I wrote "sequential-uuids" extension, doing roughly what v7/v8 do, but wrapping the timestamp once in a while.
Of course, if you don't delete data, this is not an issue and v7/v8 will work fine.
Long story short: you should probably use a bigint unless you have a pretty good reason not to. Good reasons exist! If you do use a UUID, make sure you use a version that is time-sorted.
1: https://planetscale.com/courses/mysql-for-developers/indexes...
Or am I missing something?
If you routinely work with junior developers this will come up because UUID4 seems miraculous at first. There's always a bit of surprise when the question gets asked about why we have so many sequential keys when we could just use UUID4...
I think a root cause is that there’s almost never a case for preferring UUIDv4 over ULID/UUIDv7, but we still see almost all learning material reach for the former. So people only find out once they have a table that exhibits weird/low performance and suddenly need to google for specific performance problems they’ve never encountered before.
Similarly, efficiently using indexes is also a very common thing I see people not know much about, since with SQL “everything performs well until it doesn’t” (i.e. you reach scale) :)
So your id's of top level entities should be something random.
At jetpack.io we've been doing exactly that via TypeIDs: https://github.com/jetpack-io/typeid and there's a PostgresSQL implementation available. TypeIDs are UUIDv7 with additional type information, so you also get type-safety in your IDs.
Example Ulid vs UUID:
000360TJXZDDMSKJSQGBQHA5YA
fb87f306-b613-4948-be24-00609cf9ccc8
https://github.com/ulid/spec
https://tsid.com/deYou’d typically see this as either lower performance of a table than you expect, or higher IOPS usage of your database (which gets expensive at scale).
Also another approach I've seen, which personally I find it a bit complicated, is to use auto-increment primary keys for the internal system and UUIDs for the public facing interactions.
They mess with table statistics. If you do a query like "SELECT * from users where creation_date > NOW-1h", the query analyzer doesn't know that there might be thousands of users created in the last hour. It is probably working from day-old statistics that say all users have a creation_date between 2008 and 2023-06-21.
That makes it sometimes pick an exceptionally poor query plan. Ie. instead of your query taking 50 milliseconds, it might take 50 hours and involve an n^2 scan of all data in your database.
eg. DeterministicGuid.Create(tenantNamespace, "my-tenant-name");
Note: https://github.com/Informatievlaanderen/deterministic-guid-g... for dotnet.
Additionally, know that there are different versions of UUID's. If you want to create chronologic UUID's so that queries are more easily ordered, use the correct type.
My instinct is to not use sequential-ish indices/primary keys, because I don't want to hotspot one part of the storage with all my writes for today in the same tablet.
I ran into this exact issue when building out a graph like database in Postgres many moons ago.
It’s probably less of an issue with fast nvme sad drives now, but on mechanical drives ordering and locality are massive.