16 ms·
Avoid UUID Version 4 Primary Keys in Postgres
- Xorakios 10mo agoI was born in the Vancouver Social Security office #538 area in 1962. Guess how much I have to defend against attackers trying 538-62-xxxx
- oldpersonintx2 10mo ago[dead]
- jwr 10mo ago"if you use PostgreSQL" (in the scientific reporting world this would be the perennial "in mice")
- hyperpape 10mo agoThe thing is, none of us are mice, but many of us use Postgres. It would be the equivalent of "if you're a middle-aged man" or "you're an American". P.S. I think some of the considerations may be true for any system that uses B-Tree indexes, but several will be Postgres specific.
- orthoxerox 10mo agoIt's not just Postgres or even OLTP. For example, if you have an Iceberg table with SCD2 records, you need to regularly locate and update existing records. The more recent a record is, the more likely it is to be updated. If you use UUIDv7, you can partition your table by the key prefix. Then the bulk of your data can be efficiently skipped when applying updates.
- andatki 10mo agoGood addition!
- kijin 10mo agoThe space requirement and index fragmentation issue is nearly the same no matter what kind of relational database you use. Math is math. Just the other day I delivered significant performance gains to a client by converting ~150 million UUIDv4 PKs to good old BIGINT. They were using a fairly recent version of MariaDB.
- zelphirkalt 10mo agoIf they can live with making keys only in one place, then sure, this can work. If however they need something that is very highly likely unique, across machines, without the need to sync, then using a big integer is no good. if they can live with MariaDB, OK, but I wouldn't choose that in the first place these days. Likely Postgres will also perform better in most scenarios.
- kijin 10mo agoYeah, they had relatively simple requirements so BIGINT was a quick optimization. MariaDB can guarantee uniqueness of auto-incrementing integers across a cluster of several servers, but that's about the limit. Had the requirements been different, UUIDv7 would have worked well, too, because fragmentation is the biggest problem here.
- splix 10mo agoI think the author means all dbs that fit a single server. Because in distributed dbs you often want to spread the load evenly over multiple servers.
- esafak 10mo agoTo spell it out: it improves performance by avoiding hot spots.
- benterix 10mo agoThe article sums up some valid arguments against UUIDv4 as PKs but the solution the author provides on how to obfuscate integers is probably not something I'd use in production. UUIDv7 still seems like a reasonable compromise for small-to-medium databases.
- mort96 10mo agoI tend to avoid UUIDv7 and use UUIDv4 because I don't want to leak the creation times of everything. Now this doesn't work if you actually have enough data that the randomness of the UUIDv4 keys is a practical database performance issue, but I think you really have to think long and hard about every single use of identifiers in your application before concluding that v7 is the solution. Maybe v7 works well for some things (e.g identifiers for resources where creation times are visible to all with access to the resource) but not others (such as users or orgs which are publicly visible but without publicly visible creation times).
- cdmckay 10mo agoOut of curiosity, why is it an issue if you leak creation time?
- robertlagrant 10mo agoDepends on the data. If you use a primary key in data about a person that shouldn't include their age (e.g. to remove age-based discrimination) then you are leaking an imperfect proxy to their age.
- xandrius 10mo agoTo summarise the article: in PG, prefer using UUIDv7 over UUIDv4 as they have slightly better performance. If you're using latest version of PG, there is a plugin for it. That's it.
- sbuttgereit 10mo agoYou might have missed the big H2 section in the article: "Recommendation: Stick with sequences, integers, and big integers" After that then, yes, UUIDv7 over UUIDv4. This article is a little older. PostgreSQL didn't have native support so, yeah, you needed an extension. Today, PostgreSQL 18 is released with UUIDv7 support... so the extension isn't necessary, though the extension does make the claim: "[!NOTE] As of Postgres 18, there is a built in uuidv7() function, however it does not include all of the functionality below." What those features are and if this extension adds more cruft in PostgreSQL 18 than value, I can't tell. But I expect that the vast majority of users just won't need it any more.
- tmountain 10mo agoSticking with sequences and other integer types will cause problems if you need to shard later.
- zwnow 10mo agoEspecially in larger systems, how does one solve the issue of reaching the max value of an integer in their database? Sure for unsigned bigint thats hard to achieve but regular ints? Apps quickly outgrow that.
- sbuttgereit 10mo agoOK... but that concern seems a bit artificial.. if bigints are appropriate: use them. If the table won't get to bigint sizes: don't. I've even used smallint for some tables I knew were going to be very limited in size. But I wouldn't worry about smallint's very limited number of values for those tables that required a larger size for more records: I'd just use int or bigint for those other tables as appropriate. The reality is that, unless I'm doing something very specific where being worried about the number of bytes will matter... I just use bigint. Yes, I'm probably being wasteful, but in the cases where those several extra bytes per record are going to really add up.... I probably need bigint anyway and in cases where bigint isn't going to matter the extra bytes are relatively small in aggregate. The consistency of simply using one type itself has value. And for those using ints as keys... you'd be surprised how many databases in the wild won't come close to consuming that many IDs or are for workloads where that sort of volume isn't even aspirational. Now, to be fair, I'm usually in the UUID camp and am using UUIDv7 in my current designs. I think the parent article makes good points, but I'm after a different set of trade-offs where UUIDs are worth their overhead. Your mileage and use-cases may vary.
- dotancohen 10mo agoFrom the fine article: > Random values don’t have natural sorting like integers or lexicographic (dictionary) sorting like character strings. UUID v4s do have "byte ordering," but this has no useful meaning for how they’re accessed. Might the author mean that random values are not sequential, so ordering them is inefficient? Of course random values can be ordered - and ordering by what he calls "byte ordering" is exactly how all integer ordering is done. And naive string ordering too, like we would do in the days before Unicode.
- kreetx 10mo agoUsing an UUIDv4 as primary key is a trade-off: you use it when you need to generate unique keys in a distributed manner. Yes, these are not datetime ordered and yes, they take 128 bits of space. If you can't live with this, then sure, you need to consider alternatives. I wonder if "Avoid UUIDv4 Primary Keys" is a rule of thumb though.
- dotancohen 10mo agoIf one needs timestamp ordering, then UUIDv7 is a good alternative. But the author does not say timestamp ordering, he says ordering. I think he actually means and believes that there is some problem ordering UUIDv4.
- kreetx 10mo agoYup. There are alternatives depending on what the situation is: with non-distributed, you could just use a sufficiently sized int (which can be rather small when the table is for e.g humans). You could add a separate timestamp column if that is important. But if you need UUID-based lookup, then you might as well have it as a primary key, as that will save you an extra index on the actual primary key. If you also need a date and the remaining bits in UUIDv7 suffice for randomness, then that is a good option too (though this does essentially amount to having a composite column made up of datetime and randomness).
- torginus 10mo agoI do not understand why 128 bits is considered too big - you clearly can't have less, as on 64 bits the collision probability on real world workloads is just too high, for all but the smallest databases. Auto-incrementing keys can work, but what happens when you run out of integers? Also, distributed dbs probably make this hard, and they can't generate a key on client. There must be something in Postgres that wants to store the records in PK order, which while could be an okay default, I'm pretty sure you can this behavior, as this isn't great for write-heavy workloads.
- waynenilsen 10mo agoWhat kills me is I can’t double click the thing to select it.
- mrits 10mo agoThis application specific. iTerm2 doesn't break up by - why firefox does.
- mcny 10mo agoPostgresql 18 released in September and has uuidv7 https://www.postgresql.org/docs/current/functions-uuid.html https://www.postgresql.org/docs/current/functions-uuid.html
- dimitrisnl 10mo agoNoob question, but why no use ints for PK, and UUIDs for a public_id field?
- edding4500 10mo ago*edit: sorry, misread that. My answer is not valid to your question. original answer: because if you dont come up with these ints randomly they are sequential which can cause many unwanted situations where people can guess valid IDs and deduce things from that data. See https://en.wikipedia.org/wiki/German_tank_problem https://en.wikipedia.org/wiki/German_tank_problem
- javawizard 10mo agoHence the presumed implication behind the public_id field in GP's comment: anywhere identifiers are exposed, you use the public_id field, thereby preventing ID guessing while still retaining the benefits of ordered IDs where internal lookups are concerned. Edit: just saw your edit, sounds like we're on the same page!
- javaunsafe2019 10mo agoSo We make things hard in the backend because of leaky abstractions? Doesn't make sense imo.
- jcims 10mo agoDecades of security vulnerabilities and compromises because of sequential/guessable PKs is (only!) part of the reason we're here. Miss an authorization check anywhere in the application and you're spoon-feeding entire tables to anyone with the inclination to ask for it.
- grim_io 10mo agoThe article mentions microservices, which can increase the likelihood of collisions in sequential incremental keys. One more reason to stay away from microservices, if possible.
- Lucasoato 10mo agoHi, a question for you folks. What if I don’t like to embed timestamp in uuid as v7 do? This could expose to timing attacks in specific scenarios. Also is it necessary to show uuid at all to customers of an API? Or could it be a valid pattern to hide all the querying complexity behind named identifiers, even if it could cost a bit in terms of joining and indexing? The context is the classic B2B SaaS, but feel free to share your experiences even if it comes from other scenarios!
- scary-size 10mo agoThis reminds me about this old gist for generating Firebase-like "push IDs" [1]. Those have some nicer properties. [1] https://gist.github.com/mikelehen/3596a30bd69384624c11 https://gist.github.com/mikelehen/3596a30bd69384624c11
- socketcluster 10mo agoMy advice is: Avoid Blanket Statements About Any Technology. I'm tired of midwit arguments like "Tech X is N% faster than tech Y at performing operation Z. Since your system (sometimes) performs operation Z, it implies that Tech X is the only logical choice in all situations!" It's an infuriatingly silly argument because operation Z may only represent about 10% of the total CPU usage of the whole system (averaged out)... So what is promoted as a 50% gain may in fact be a 5% gain when you consider it in the grand scheme of things... Negligible. If everyone was looking at this performance 'advantage' rationally; nobody would think it's worth sacrificing important security or operational properties. I don't know what happened to our industry; we're supposed to be intelligent people but I see developers falling for these obvious logical fallacies over and over. I remember back in my day, one of the senior engineers was discussing upgrading a python system and stated openly that the new version of the engine was something like 40% slower than the old version but he didn't even have to explain himself why upgrading was still a good decision; everybody in the company knew he was only talking about the code execution speed and everybody knew that this was a small fraction of the total. Not saying UUIDv7 was a bad choice for Postgres. I'm sure it's fine for a lot of situations but you don't have to start a cult preaching the gospel of The One True UUID to justify your favorite project's decisions. I do find it kind of sly though how the community decided to make this UUIDv7 instead of creating a new standard for it. The whole point of UUID was to leverage the properties of randomness to generate unique IDs without requiring coordination. UUIDv7 seems to take things in a philosophically different path. People chose UUID for scalability and simplicity (both of which you get as a result of doing away with the coordination overhead), not for raw performance... That's the other thing which drives me nuts; people who don't understand the difference between performance and scalability. People foolishly equate scalability with parallelism or concurrency; whereas that's just one aspect of it; scalability is a much broader topic. It's the difference between a theoretical system which is fast given a certain artificially small input size and one which actually performs better as the input size grows. Lastly; no mention is made about the complex logic which has to take place behind the scenes to generate UUIDv7 IDs... People take it for granted that all computers have a clock which can produce accurate timestamps where all computers in the world are magically in-sync... UUIDv7 is not simple; it's very complicated. It has a lot of additional complexity and dependencies compared to UUIDv4. Just because that complexity is very well hidden from most developers, doesn't mean it's not there and that it's not a dependency... This may become especially obvious as we move to a world of robotics and embedded systems where cheap microchips may not have enough Flash memory to hold the code for the kinds of programs required to compute such elaborate IDs.
- dfox 10mo ago> Creating obfuscated values using integers While that is often neat solution, do not do that by simply XORing the numbers with constant. Use a block cipher in ECB mode (If you want the ID to be short then something like NSA's Speck comes handy here as it can be instantiated with 32 or 48 bit block). And do not even think about using RC4 for that (I've seen that multiple times), because that is completely equivalent to XORing with constant.
- bux93 10mo agoLong article about why not to use UUIDv4 as Primary Keys, but.. Who is doing so? And why are they doing that? How would you solve their requirements? Just throwing out "you can use UUIDv7" doesn't help with, e.g., the size they take up. Aren't people using (big)ints are primary keys, and using UUIDs as logical keys for import/export, solving portability across different machines?
- Sayrus 10mo agoUUIDs are usually the go-to solution to enumeration problems. The space is large enough that an attacker cannot guess how many X you have (invoices, users, accounts, organizations, ...). When people replace the ints by UUIDv4, they keep them as primary keys.
- bruce511 10mo agoI'd add that it's also used when data is created in multiple places. Consider say weather hardware. 5 stations all feeding into a central database. They're all creating rows and uploading them. Using sequential integers for that is unnecessarily complex (if even possible.) Given the amount of data created on phones and tablets, this affects more situations than first assumed. It's also very helpful in export / edit / update situations. If I export a subset of the data (let's say to Excel), the user can edit all the other columns and I can safely import the result. With integer they might change the ID field (which would be bad). With uuid they can change it, but I can ignore that row (or the whole file) because what they changed it to will be invalid.
- nrhrjrjrjtntbt 10mo agoYes and the DB might be columnular or a distributed KV, sidestepping the index problem.
- andatki 10mo agoThis was written based on working on several Postgres databases at different companies of “medium” size as a consultant, that had excessive IO and latency and used UUID v4 PKs/FKs. They’re definitely out there. We could transform the schema for some key tables as a demonstration with big int equivalents and show the IO latency reduction. With that said, the real world PK data type migration is costly but becomes a business decision of whether to do or not.
- cebert 10mo agoUsing UUIDs as primary keys in non-relational databases like DynamoDB is valid and doesn’t raise the concerns mentioned in the article.
- andatki 10mo agoGood point that the post should be made clear it’s referring only to my experience with Postgres.
- reactordev 10mo agoI fun trick I did was generate UUID-like ids. We all can identify a UUIDv4 most of the time by looking at one. "Ah, a uuid" we say to ourselves. A little over a decade ago I was working on a massive cloud platform and rather than generate string keys like the author above suggested (int -> binary -> base62 str) we opted for a more "clever" approach. The UUID is 128bits. The first 64bits are a java long. The last 64bits are a java long. Let's just combine the Tenant ID long with a Resource ID long to generate a unique id for this on our platform. (worked until it didn't).
- nrhrjrjrjtntbt 10mo agoAtlassian settles for longer "ARIs" for this (e.g.https://developer.atlassian.com/cloud/guard-detect/developer/build-your-ari/ https://developer.atlassian.com/cloud/guard-detect/developer...) composed of guids which allow a scheme like the Amazon ARN to pass around.
- reactordev 10mo agoyeah, the problem for us was the resource id. What id was it? Was it a post? an upload? a workspace? it wasn't nearly as descriptive as we needed it to be.
- K0nserv 10mo agoAn additional thing I learned when I worked on a ulid alternative over the weekend[0] is: Postgres's internal Datum type is at most 64 bits which means every uuid requires heap allocation[1] (at least until we get 128 bit machines). 0: https://bsky.app/profile/hugotunius.se/post/3m7wvfokrus2g https://bsky.app/profile/hugotunius.se/post/3m7wvfokrus2g 1: https://github.com/postgres/postgres/blob/master/src/backend/utils/adt/uuid.c#L180-L189 https://github.com/postgres/postgres/blob/master/src/backend...
- qntmfred 10mo agoyou may be interested in this postgres extension as well https://github.com/blitss/typeid-postgres https://github.com/blitss/typeid-postgres
- K0nserv 10mo agoThat is indeed interesting. I have slightly different goals for my version. I want everything to fit in 128 bits so I'm sacrificing some of the random bits, I'm also making sure the representation inside Postgres is also exactly 128 bits. My initial version ended up using CBOR encoding and being 160 bits. Mine dedicates 16 bits for the prefix allowing up to 3 characters (a-z alphabet).
- K0nserv 10mo agoFinished an initial version of mine https://github.com/k0nserv/plid https://github.com/k0nserv/plid
- raxxorraxor 10mo ago> Do not assume that UUIDs are hard to guess; they should not be used as security capabilities The issue is that is true for more or less all capability URLs. I wouldn't recommend UUIDs per se here, probably better to just use a random number. I have seen UUIDs for this in practice though and these systems weren't compromised because of that. I hate the tendency that password recovery flows for example leave the URL valid for 5 minutes. Of course these URLs need to have a limited life time, but mail isn't a real time communication medium. There is very little security benefit from reducing it from 30 minutes to 5 minutes for example. You are not getting "securer" this way.
- vintermann 10mo agoA prime example of premature optimization. Permanent identifiers should not carry data. This is like the cardinal sin of data management. You always run into situations where the thing you thought, "surely this never changes, so it's safe to squeeze into the ID to save a lookup". Then people suddenly find out they have a new gender identity, and they need a last final digit in their ID numbers too. Even if nothing changes, you can run into trouble. Norwegian PNs have your birth date (in DDMMYY format) as the first six digits. Surely that doesn't change, right? Well, wrong, since although the date doesn't change, your knowledge of it might. Immigrants who didn't know their exact date of birth got assigned 1. Jan by default... And then people with actual birthdays on 1 Jan got told, "sorry, you can't have that as birth date, we've run out of numbers in that series!" Librarians in the analog age can be forgiven for cramming data into their identifiers, to save a lookup. When the lookup is in a physical card catalog, that's somewhat understandable (although you bet they could run into trouble over it too). But when you have a powerful database at your fingertips, use it! Don't make decisions you will regret just to shave off a couple of milliseconds!
- oncallthrow 10mo agoIt sounds to me like you’re just arguing for premature optimization of another kind (specifically, prematurely changing your entire architecture for edge cases that probably won’t ever happen to you).
- vintermann 10mo agoIf you have an architecture already, obviously it's hard to change and you may want to postpone it until those edge cases which probably won't ever happen to you, happen. But for new architectures, value your own grey hairs over small performance improvements.
- tacone 10mo agoFantastic real life example. Italian PNs carry also the gender, which something you can change surgically, and you'll eventually run into the issue when operating at scale. I don't agree with the absolute statement, though. Permanent identifiers should not generally carry data. There are situations where you want to have a way to reconciliate, you have space or speed constraints, so you may accept the trade off, md5 your data and store it in a primary index as a UUID. Your index will fragment and thus you will vacuum, but life will still be good overall.
- sobakistodor 10mo ago[dead]
- ivan_gammel 10mo agoThe is article is about a solution in search of a problem, a classic premature optimization issue. UUIDv4 is perfectly fine for many use cases, including small databases. Performance argument must be considered when there’s a problem with performance on the horizon. Other considerations may be and very often superior to that.
- sagarm 10mo agoIt's not really feasible to rekey your UUIDv4 keyed database to int64s after the fact, imo. Sure your new tables could be integer-keyed, but the bulk of your storage will be UUID (and UUIDv4, if that's what you started with) for a very long time
- ivan_gammel 10mo agoYes, sure. My point is, it may never be necessary.
- sagarm 10mo agoI think you're right that it won't matter for most companies. But having been at a company with persistent DB performance issues with UUIDv4 keys as a contributing factor, it sucks.
- mrkeen 10mo agoIf you have too many UUIDs, throw more DBs at the problem. Hopefully you haven't tied yourself to any architectural decisions that would limit you to only using a single database.
- sgarland 10mo agoIME, when performance issues become obvious, the devs are in growth mode and have no desire / time to revisit PK choice. Integer PKs were seen as fine for years - decades, even - before the rise of UUIDs.
- BartjeD 10mo agoPersonally my approach has been to start with big-ints and add a GUID code field if it becomes necessary. And then provide imports where you can match objects based on their code, if you ever need to import/export between tenants, with complex object relationships. But that also adds complexity.
- parpfish 10mo agoTwo things I don’t like about big-int indexes: - If you use uuids as foreign keys to another table, it’s obvious when you screw up a join condition by specifying the wrong indices. With int indices you can easily get plausible looking results because your join will still return a bunch of data - if you’re debugging and need to search logs, having a simple uuid string is nice for searching
- hk1337 10mo agoMy biggest thing for UUIDs is don’t UUID everything. Most things should be okay with just regular integers as PKs.
- grugdev42 10mo agoA much simpler solution is to keep your tables as they are (with an integer primary key), but add a non sequential public identifier too. id => 123, public_id => 202cb962ac59075b964b07152d234b70 There are many ways to generate the public_id. A simple MD5 with a salt works quite well for extremely low effort. Add a unique constraint on that column (which also indexes it), and you'll be safe and performant for hundreds of millions of rows! Why do we developers like to overcomplicate things? ;)
- Denvercoder9 10mo agoThis misses the point. The reason not to use UUIDv4 is that having an index on random values is slow(er), because sequential inserts into the underlying B-tree are faster than random inserts. You're hitting the same problem with your `public_id` column, that it's not the primary key doesn't change that.
- hnfong 10mo agoInts as pk would be quicker for joins etc though.
- grugdev42 10mo agoExactly
- sgarland 10mo agoFor InnoDB-based DBs that are not Aurora, and if the secondary index isn’t UNIQUE, it solves the problem, because secondary non-unique index changes are buffered and written in batches to amortize the random cost. If you’re hashing a guaranteed unique entity, I’d argue you can skip the unique constraint on this index. For Aurora MySQL, it just makes it worse either way, since there’s no change buffer.
- Retr0id 10mo agoPer https://news.ycombinator.com/item?id=46273325 https://news.ycombinator.com/item?id=46273325, if you use a block cipher rather than a hash then you don't even need to store it anywhere.
- kaladin_1 10mo agoI really hoped the author would discuss alternatives for distributed databases that writes in parallel. Sequential key would be atrocious in such circumstance this could kill the whole gain of distributed database as hotspots would inevitably appear. I would like to hear from others using, for example, Google Spanner, do you have issues with UUID. I don't for now, most optimizations happen at the Controller level, data transformation can be slow due to validations. Try to keep service logic as straightforward as possible.
- old8man 10mo agoVery useful article, thank you! Many people suggest CUID2, but it is less efficient and is better used for frontend/url encoding. For backend/db, only UUID v7 should be used.
- mexicocitinluez 10mo agoYou'll have to rip the ability to generate unique numbers from quite literally anywhere in my app and save them without conflict from my cold, dead hands. The ability to know ahead of time what a primary key will be (in lieu of persisting it first, then returning) opened up a whole new world of architecting work in my app. It made a lot of previous awkward things feel natural.
- sgarland 10mo agoSounds like a lot of referential integrity violations.
- mexicocitinluez 10mo agoWhy would generating a PK ahead of time cause referential integrity violations? Super curious to find out.
- sgarland 10mo agoThe implication is that you need to know the PK ahead of time so that you can insert it into other tables which reference it as an FK without waiting for it to be returned, which further implies that you don’t have FK constraints, because the DB would disallow this. Tbf in Postgres, you can declare FKs to be deferrable, so their existence is checked at transaction commit, rather than at insertion time. If you don’t have the DB enforcing referential integrity, you need to be extremely careful in your application logic; IME, this inevitably fails. At some point, someone writes bad code, and you get data anomalies.
- mexicocitinluez 10mo ago> Tbf in Postgres, you can declare FKs to be deferrable, so their existence is checked at transaction commit, rather than at insertion time.h further implies that you don’t have FK constraints, because the DB would disallow this. I'm using EF core which hooks up these relationships and allows me to persist them in a single transaction using MSSQL server. > If you don’t have the DB enforcing referential integrity I'm building an electronic medical system. I'm well aware of the benefits of referential integrity.
- mkleczek 10mo agoThat's really an important deficiency of Postgres. Hash index is ideally suited for UUIDs but for some reason Postgres hash indexes cannot be unique.
- p2detar 10mo agoAnother interesting article from Feb-2024 [0] where the cost of inserting a uuid7() and a bigint is basically the same. To me it wasn't quite clear what the problem with the buffer cache is but the author makes it much more clear than OP's article: > We need to read blocks from the disk when they are not in the PostgreSQL buffer cache. Conveniently, PostgreSQL makes it very easy to inspect the contents of the buffer cache. This is where the big difference between uuidv4 and uuidv7 becomes clear. Because of the lack of data locality in uuidv4 data, the primary key index is consuming a huge amount of the buffer cache in order to support new data being inserted – and this cache space is no longer available for other indexes and tables, and this significantly slows down the entire workload. 0 - https://ardentperf.com/2024/02/03/uuid-benchmark-war https://ardentperf.com/2024/02/03/uuid-benchmark-war
- stevefan1999 10mo agoTry Snowflake ID then: https://en.wikipedia.org/wiki/Snowflake_ID https://en.wikipedia.org/wiki/Snowflake_ID
- gwbas1c 10mo agoI work on an application where we encrypt the integer primary key and then use the bytes to generate something that looks like a UUID. In our case, we don't want database IDs in an API and in URLs. When IDs are sequential, it enables things like dictionary attacks and provides estimates about how many customers we have. Encrypting a database ID makes it very obvious when someone is trying to scan, because the UUID won't decrypt. We don't even need a database round trip.
- puilp0502 10mo agoFew questions: * How do you manage the key for encrypting IDs? Injected to app environment via envvar? Just embedded in source code? I ask this because I'm curious as to how much "care" I should be putting in into managing the secret material if I were to adopt this scheme. * Is the ID encrypted using AEAD scheme (e.g. AES-GCM)? Or does the plain AES suffice? I assume that the size of IDs would never exceed the block size of AES, but again, I'm not a cryptographer so not sure if it's safe to do so.
- gwbas1c 10mo ago> How do you manage the key for encrypting IDs? The same way we manage all other secrets in the application. (Summarized below) > Is the ID encrypted using AEAD scheme (e.g. AES-GCM)? Or does the plain AES suffice? I assume that the size of IDs would never exceed the block size of AES, but again, I'm not a cryptographer so not sure if it's safe to do so. I don't have the source handy at the moment. It's one of the easier to use symmetric algorithms available in .Net. We aren't talking military-grade security here. In general: a 32-bit int encrypts to 64-bits, so we pad it with a few unicode characters so it's 64-bits encrypted to 128 bits. --- As far as managing secrets in the application: We have a homegrown configuration file generator that's adapted to our needs. It generates both the configuration files, and strongly-typed classes to read the files. All configuration values are loaded at startup, so we don't have to worry about runtime errors from missing configuration values. Secrets (connection strings, encryption keys, ect,) are encrypted in the configuration file as base64 strings. The certificate to read/write secrets are stored in Azure Keyvault. The startup logic in all applications is something like: 1: Determine the environment (production, qa, dev) 2: Get the appropriate certificate 3: Read the configuration files, including decrypting secrets (such as the primary key encryption keys) from the configuration files 4: Populate the strongly-typed objects that hold the configuration values 5: These objects are dependency-injected to runtime objects
- mgoetzke 10mo agoThat depends a lot on many factors and thus I dont like generic statements like that which tend to be more focused on a specific database pattern. That said everyone should indeed be aware of the potential tradeoffs. And of course we could come up with many ways to generate our own ids and make them unique, but we have the following requirements. - It needs to be a string (because we allow composing them to 'derive' keys) - A client must be able to create them (not just a server) without risk for collisions - The time order of keys must not be guessable easily (as the id is often leaked via references which could 'betray' not just the existence of a document, but also its relative creation time wrt others). - It should be easy to document how any client can safely generate document ids. The lookup performance is not really such a big deal for us. Where it is we can do a projection into a more simple format where applicable.
- aynyc 10mo agoI've seen this type of advice a few times now. Now I'm not a database expert by any stretch of imagination, but I have yet to see UUID as primary key in any of the systems I've touched. Are there valid reasons to use UUID (assuming correctly) for primary key? I know systems have incorrectly expose primary key to the public, but assuming that's not the concern. Why use UUID over big-int?
- reffaelwallen 10mo agoAt my company we only use UUIDs as PKs. Main reason I use it is the German Tank problem: https://en.wikipedia.org/wiki/German_tank_problem https://en.wikipedia.org/wiki/German_tank_problem (tl;dr; prevent someone from counting how many records you have in that table)
- littlestymaar 10mo agoWhat stops you from having another uuid field as publicly visible identifier (which is only a concern for a minority of your tables). This way you avoid most of the issues highlighted in this article, without compromising your confidential data.
- jakeydus 10mo agoI'm new to the security side of things; I can understand that leaking any information about the backend is no bueno, but why specifically is table size an issue?
- boruto 10mo agoIn my old company new joiners are assigned an monotonic number as id in tech. GitHub profile url reflected that. Someone may or may not have used the pattern to get to know the attrition rate through running a simple script every month))
- infragreen 10mo agoThis was a great read, thank you for sharing!
- nesarkvechnep 10mo agoIf we embraced REST, as Roy Fielding envisioned it, we wouldn't have this, and all similar, conversations. REST doesn't expose identifier, it only exposes relationships. Identifiers are an implementation details.
- cruffle_duffle 10mo agoI never understood the arguments against using using globally unique ids. For example how it somehow messes up indexes. I’m not a CS major but those are typically b-trees are they not? If you have a primary key whose generation is truly random such that each number is equally likely, then that b-tree is always going to be balanced. Yes there are different flavors of generating them with their own pros and cons, but at the end of the day it’s just so much more elegant than some auto incrementing crap your database creates. But that is just semantic, you can always change the uuid algorithm for future keys. And honestly if you treat the uuid as some opaque entity (which you should), why not just pick the random one? And I just thought of the argument that “but what if you want to sort the uuid…” say it’s used for a list of stories or something? Well, again… if you treat the uuid as opaque why would you sort it? You should be sorting on some other field like the date field or title or something. UUIDs are opaque, damn it. You don’t sort opaque data. “Well they get clustered weird” say people. Why are you clustering on a random opaque key? If you need certain data to be clustered, then do it on the right key (user_id field did your data was to be clustered by user, say) Letting the client generate the primary keys is really liberating. Not having to care about PK collisions or leaking information via auto incrementing numbers is great! In my opinion uuid isn’t used enough!
- chuckadams 10mo ago> If you have a primary key whose generation is truly random such that each number is equally likely, then that b-tree is always going to be balanced. Balanced and uniformly scattered. A random index means fetching a random page for every item. Fine if your access patterns are truly random, but that's rarely the case. > Why are you clustering on a random opaque key? InnoDB clusters by the PK if there is one, and that can't be changed (if you don't have a PK, you have some options, but let's assume you have one). MSSQL behaves similarly, but you can override it. If your PK is random, your clustering will be too. In Postgres, you'll just get fragmented indexes, which isn't quite as bad, but still slows down vacuum. Whether that actually becomes a problem is also going to depend on access patterns. One shouldn't immediately freak out over having a random PK, but should definitely at least be aware of the potential degradation they might cause.
- stickfigure 10mo agoThis is incredibly database-specific. In Postgres random PKs are bad. But in distributed databases like Cockroach, Google Cloud Datastore, and Spanner it is the opposite - monotonic PKs are bad. You want to distribute load across the keyspace so you avoid hot shards.
- jakeydus 10mo agoI think they address this in the article when they say that this advice is specific to monolithic applications, but I may be misremembering (I skimmed).
- andy_ppp 10mo agoAre you saying a monolith cannot use a distributed database?
- jakeydus 10mo agoI'm not making any claims at all, I was just adding context from my recollection of the article that appeared to be missing from the conversation. Edit: What the article said: > The kinds of web applications I’m thinking of with this post are monolithic web apps, with Postgres as their primary OLTP database. So you are correct that this does not disqualify distributed databases.
- dap 10mo agoIt is, although you can have sharded PostgreSQL, in which case I agree with your assessment that you want random PKs to distribute them. It's workload-specific, too. If you want to list ranges of them by PK, then of course random isn't going to work. But then you've got competing tensions: listing a range wants the things you list to be on the same shard, but focusing a workload on one shard undermines horizontal scale. So you've got to decide what you care about (or do something more elaborate).
- nutjob2 10mo ago> You want to distribute load across the keyspace so you avoid hot shards. This is just another case of keys containing information and is not smart. The obvious solution is to have a field that drives distribution, allowing rebalancing or whatever.
- deathanatos 10mo ago> Are UUIDs secure? > Misconceptions: UUIDs are secure > One misconception about UUIDs is that they’re secure. However, the RFC describes that they shouldn’t be considered secure “capabilities.” > From RFC 41221 Section 6 Security Considerations: > Do not assume that UUIDs are hard to guess; they should not be used as security capabilities This is just wrong, and the citation doesn't support it. You're not guessing a 122-bit long random identifier. What's crazy is that the article, immediately prior to this, even cites the very math involved in showing exactly how unguessable that is. … the linked citation (to §4.4, which is different from the in-prose citation) is just about how to generate a v4, and completely unrelated to the claim. The prose citation to §6 is about UUIDs generally: the statement "Do not assume that [all] UUIDs are hard to guess" is not logically inconsistent with properly-generated UUIDv4s being hard to guess. A subset of UUIDs have security properties, if the system generating & using them implements those properties, but we should not assume all UUIDs have that property. Moreover, replacing an unguessable UUID with an (effectively random) 32-bit integer does make it guessable, and the scheme laid out seems completely insecure if it is to be used in the contexts one finds UUIDv4s being an unguessable identifier. The additional size argument is pretty weak too; at "millions of rows", a UUID column is consuming an additional ~24 MiB.
- hippo22 10mo agoThe author should include benchmarks otherwise, saying that UUIDs “increase latency” is meaningless. For instance, how much longer does it take to insert a UUID vs. an integer? How much longer does scanning an index take?
- jakeydus 10mo agoThe author doesn't reference any tests that they themselves ran, but they did link a cybertec article [0] with some benchmarks. [0] https://www.cybertec-postgresql.com/en/unexpected-downsides-of-uuid-keys-in-postgresql/ https://www.cybertec-postgresql.com/en/unexpected-downsides-...
- henning 10mo agoUUIDs make enumeration attacks harder and also prevent situations where seeing a high valid ID value lets you estimate how much money a private company is earning if they charge based on the object the ID is associated with. If you can sample enough object ID values and see when the IDs were created, you could reverse engineer their ARR chart and see whether they're growing or not which many companies want to avoid.
- sneak 10mo agoThis is why ULID exists and why I use them in my ext_id columns. For the actual relational IDs internal to the db I use smaller/faster data types.
- FancyFane 10mo agoEven MySQL benefits from these changes as well. What we're really discussing is random primary key inserts (UUIDv4) vs incrementing primary key inserts (UUIDv6 or v7). PlanetScale wrote up a really good article on why incrementing primary keys are better for performance when compared to randomly inserted primary keys; when it comes to b-tree performance. https://planetscale.com/blog/btrees-and-database-indexes https://planetscale.com/blog/btrees-and-database-indexes
- iainctduncan 10mo agoCounterargument... I do technical diligence so I talk to a lot of companies at points of inflection, and I also talk to lots who are stuck. The ability to rapidly shard everything can be extremely valuable. The difference between "we can shard on a dime" and "sharding will take a bunch of careful work" can be expensive If the company has poor margins, this can be the difference between "can scale easily" and "we're not getting this investment". I would argue that if your folks have the technical chops to be able to shard while avoiding surrogate guaranteed unique keys, great. But if they don't.... a UUID on every table can be a massive get-out-of-jail free card and for many companies this is much, much important than some minor space and time optimizations on the DB. Worth thinking about.
- jessep 10mo agoSort of related, but we had to shard as usage grew and didn’t have uuids and it was annoying. Wasn’t the most annoying bit though. Whole thing is pretty complex regardless of uuid, if you have a highly interconnected data model that needs to stay online while migrating.
- iainctduncan 10mo agoRight, but if you start off with uuids and the expectation that you might use them to shard, you'll wind up factoring that into the data model. Retrofitting, as you rightly say, can be much harder.
- mrinterweb 10mo agoI can see how sharding could be difficult with a bigint FK, but UUIDv7 would still play nice, if I understand your point correctly. Monotonically increasing foreign keys have performance benefits over random UUIDv4 FKs in postgresql is the point of the article.
- jryio 10mo agoI also do technical diligence, often times the blocker to sharding is the target company's tenancy model and schema. PK data type is certainly a blocker. Definitely an issue, rarely the main one. You can work around integer PKs with composite keys or offset-based sharding schemes. What you can't easily fix is a schema with cross-tenant foreign keys, shared lookup tables, or a tenancy model that wasn't designed for data isolation from day one. Those are architectural decisions that require months of migration work. UUIDs buy you flexibility, sure. But if your data model assumes everything lives in one database, the PK type is a sub-probem of your problems.
- Waterluvian 10mo agoAny decent resources with benchmark data on Postgres insertion, indexing, retrieve, etc. for UUID vs. integer based PKs?
- whateveracct 10mo agoSometimes its nice for your PK to be uniformly distributed. As a reader, even if it hurts as a writer. For instance, you can easily shard queries and workloads. > the impact to inserts and retrieval of individual items or ranges of values from the index. Classic OLTP vs OLAP.
- can3p 10mo ago> For many business apps, they will never reach 2 billion unique values per table, so this will be adequate for their entire life. I’ve also recommended always using bigint/int8 in other contexts. I'm sure every dba has a war story that starts with similar decision in the past
- phendrenad2 10mo agoYou probably don't want integer primary keys, and you probably don't want UUID primary keys. You probably want something in-between, depending on your use case. UUID is one extreme on this spectrum, which tries to solve all of the problems, including ones you might not have.
- pil0u 10mo agoWhat's in-between? I posted the article because I'm in the middle of that choice and wanted to generate discussion/contradiction. So far, people have talked a lot about UUIDs, so I'm genuinely curious about what's in-between.
- phendrenad2 10mo agoAn example would be YouTube's video IDs. It's custom-fit for a purpose (security: no, avoiding the problem where people fish for auspicious YouTube video numbers or something: yes). Another example would be a function that sorts the numbers 0 through 999 in a seemingly random order (but's actually deterministic), and then repeat that for each block of 1000 with a slight shift. Discourages casual numeric iteration but isn't as complex or cryptographically secure as UUID.
- maxnoe 10mo agoWould this argument still apply if I need to store a uuidv4 anyway in the table? And I'd likely want a unique constraint on that?
- miiiiiike 10mo agoThe article is muddled, I wish he'd split it into two. One for UUID4 and another for UUID7. I was using 64-bit snowflake pks (timestamp+sequence+random+datacenter+node) previously and made the switch to UUID7 for sortable, user-facing, pks. I'm more than fine letting the DB handle a 128-bit int vs over a 64-bit int if it means not having make sure that the latest version of my snowflake function has made it to every db or that my snowflake server never hiccups, ever. Most of the data that's going to be keyed with a uuid7 is getting served straight out of Redis anyway.
- p1necone 10mo agoBeing able to create something and know the id of it before waiting for an http round trip simplifies enough code that I think UUIDs are worth it for me. I hadn't really considered the potential perf optimization from orderable ids before though - I will consider UUID v7 in future.
- andatki 10mo agoGreat!
- impoppy 10mo agoThis is such a mediocre article. It provides plenty of valid reasons to consider avoiding UUID in databases, however, it doesn’t say what should be used should one want primary keys that are not easy to predict. The XOR alternative is too primitive and, well, whereas I get why should I consider avoiding UUID, then what should I use instead?
- kortex 10mo agoI've been using ULIDs [0] in prod for many years now, and I love them. I just use string encoding, though if I really wanted to squeeze out every last MB, I could do some conversion so it is stored as 16 bytes instead of 26 chars. In practice it's never mattered, and the simplicity of just string IDs everywhere is nice. Sometimes I have to talk to legacy systems, all my APIs have str IDs, and I encode int IDs as just decimal left padded with leading zeros up to 26 chars. Technically not a compliant ULID but practically speaking, if I see leading `00` I know it's not an actual ULID, since that would be before Nov-2004, and ULID was invented in 2017. The ORM automatically strips the zeros and the query just works. I'm just kind of over using sequential int IDs for anything bigger than hobby level stuff. Testing/fixturing/QA are just so much easier when you do not have to care about whether an ID happens to already exist. [0] https://github.com/ulid/spec https://github.com/ulid/spec
- sedatk 10mo agoSee https://news.ycombinator.com/item?id=46211578 https://news.ycombinator.com/item?id=46211578
- kortex 10mo agoThe python implementation I use doesn't do this quirk. It's just timestamp + randomness in Crockford Base32. That's all I need. Sure it doesn't fully "comply with the spec" but frankly the sequence sub-millis quirk was a complete mistake.
- m000 10mo agoWhy not just use UUIDs as a unique column next to a bigint PK? The power and main purpose of UUIDs is to act as easy to produce, non-conflicting references in distributed settings. Since the scope of TFA is explicitly set to be "monolithic web apps", nothing stops you from having everything work with bigint PKs internally, and just add the UUIDs where you need to provide external references to rows/objects.
- mrkeen 10mo agoYes, if you're in the group of developers who are passionate about db performance, but have ruled out the idea of spreading work out to multiple DBs, then continuing to use sequential IDs is fine.
- AtNightWeCode 10mo agoThe counter argument I would say is that having all these integer ids comes with many problems. You can't make em public cause they leak info. They are not unique across environments. Meaning you have to spin up a lot of bs envs to just run it. But retros are for complaining about test envs, right? Uuid4 are only 224bits is a bs argument. Such a made up problem. But a fair point is that one should use a sequential uuid to avoid fragmentation. One that has a time part.
- kgeist 10mo agoSome additional cases we encounter quite often where UUIDs help: - A client used to run our app on-premises and now wants to migrate to the cloud. - Support engineers want to clone a client’s account into the dev environment to debug issues without corrupting client data. - A client wants to migrate their account to a different region (from US to EU). Merging data using UUIDs is very easy because ID collisions are practically impossible. With integer IDs, we'd need complex and error-prone ID-rewriting scripts. UUIDs are extremely useful even when the tables are small, contrary to what the article suggests.
- andatki 10mo agoIf merging or moving data between environments is a regular occurrence, I agree it would be best to have non-colliding primary keys. I have done an environment move (new DB in different AWS region) with integers and sequences for maybe a 100 table DB and it’s do-able but a high cost task. At that company we also had the demo/customer preview environment concept where we needed to keep the data but move it.
- p0w3n3d 10mo agoWhat about newest postgresql support for uuidv7? Anybody did tests? This is what we're heading towards at the moment of writing so I'd like to ask to eventually roll back the decision
- ath3nd 10mo ago[dead]
- burnt-resistor 10mo agoUUID PKs are trying to solve the wrong problem. Integer/serial primary keys are not the problem so long as they're never exposed or usable externally. A critical failure of nearly every RESTful framework is exposing internal database identifiers rather than using encrypted ones preserving relative performance, creation order-preservation, and eliminating unowned key probing.
- mcsoft 10mo agoSnowflake or sonyflake ids work: https://en.wikipedia.org/wiki/Snowflake_ID https://en.wikipedia.org/wiki/Snowflake_ID https://github.com/sony/sonyflake?tab=readme-ov-file https://github.com/sony/sonyflake?tab=readme-ov-file
- dizlexic 10mo agoMeh, uuid go brrrrrrrrrrrrrrrrrrrrrrrrr
- moomoo11 10mo agoI’ll do it regardless because any time I’ve tried to chase optimization early like this, hardware has always evolved faster. We have all faced issues where we don’t know where the data will ultimate live that’s optimal for our access patterns. Or we have devices and services doing async operations that need to sync. I’m not working on mission critical “if this fails there’s a catastrophic event” type shit. It’s just rent seeking SaaS type shit. Oh no it cost $0.35 extra to make $100. Next year will make more money relative to cost increase.
- dspillett 10mo ago> Do not assume that UUIDs are hard to guess; they should not be used as security capabilities It is not just about being hard to guess a valid individual identifier in vacuum. Random (or at least random-ish) values, be they UUIDs or undecorated integers, in this context are also about it being hard to guess one from another, or a selection of others. Wrt: "it isn't x it is y" form: I'm not an LLM, 'onest guv!
- deepsun 10mo agoI still don't understand why people don't remove the hyphens from UUIDs. Hyphens makes it harder to copy-paste IDs. The only reason to keep them is to make it explicit "hey this is an UUID", otherwise it's a completely internal affair. Even worse, some tools generate random strings and then ADD hyphens in them to look like UUID (even thought it's not, as the UUID version byte is filled randomly as well), cannot wrap my head why, e.g: https://github.com/VictoriaMetrics/VictoriaLogs/blob/v1.41.0/app/vlogsgenerator/main.go#L232 https://github.com/VictoriaMetrics/VictoriaLogs/blob/v1.41.0...
- Jeff_Brown 10mo agoIf you're really ambitious you'll use two UUIDs for the ID, because for an app in which at least a billion people have at least 327 million random v4 UUIDs, the probability of a collision will be greater than 1%.
- marcus_holmes 10mo agoI didn't see my primary use case for UUID's covered: sharing identifiers across entities is dangerous. I wrote a CRUD app for document storage. It had user id's and document id's. I wrote a method GetDocumentForUser(docID, userID) that checked permissions for that user and document and returned the document if permitted. I then, stupidly, called that method with GetDocumentForUser(userID, docID), and it took me a good half hour to work out why this never returned anything. It never returned anything because a valid userID will never be a valid docID. If I had used integers it would have returned documents, and I probably wouldn't have spotted it while testing, and I would have shipped a change that cheerfully handed people other people's documents. I will put up with a fairly considerable amount of performance hit to avoid having this footgun lurking. And yes, I know there are other ways around this (e.g. types) but those come with their own trade-offs too.
- tom_m 10mo agoIt depends. What a narrow minded article, sigh. Bring on the vibe coding! Let's just be mindless.
- deepsun 10mo ago> For UUID v4s, primary key values in B-Tree indexes are problematic. Wrong. Don't use B-Tree for random indexes, there's HASH index exactly for this: CREATE INDEX [index_name] ON [table_name] USING HASH ([column_name]);