News for hackers. Stuff that matters.
Re:PostgreSQL and UUID as Primary Key by whynotmaybe on Friday July 05, 2024 @07:55PM (#40887113)
As uuid v7 hold time information, they can help bad actors for timing attacks or pattern recognition because they contain a time information linked to the record.

You can guess the time the system took between 2 uuid v7 id's.

They can only be used if they're not shown to the user. (so not in the form mysite.com/mypage? id=0190854d-7f9f-78fc-b9bc-598867ebf39a)

A big serial starting at a high number can't provide the time information.

Re:PostgreSQL and UUID as Primary Key by TeeWEE on Friday July 05, 2024 @11:24PM (#40887971)
Big serial is sequential and it’s very easy to guess the next number. So you got the problem of sequential key attack…

If you use only uuid in your outwards facing api then you still have the problem of slow queries. Since you need them to find the object (as mentioned below)

UUIDv7 has a random part, can be created distributedly, and indexes well.

It’s the best choice for modern application that support distributed data creation.

Re:PostgreSQL and UUID as Primary Key by badestrand on Saturday July 06, 2024 @03:08AM (#40888678)
You never expose the bigserial, you generate a ID (like UUID) for external use/identification and simply have an index over that column for fast selects.
Re:PostgreSQL and UUID as Primary Key by stoperaticless on Saturday July 06, 2024 @05:30AM (#40889251)
Amen (or similar)
Re:PostgreSQL and UUID as Primary Key by kroolik on Saturday July 06, 2024 @06:05AM (#40889375)
Having an index over the uuid is equivalent to it being a PK, so why would you bother having both?
Re:PostgreSQL and UUID as Primary Key by blackenedgem on Saturday July 06, 2024 @06:15AM (#40889429)
Because it's much better for range queries and joins. When you inevitably need to take a snapshot of the table or migrate the schema somehow you'll be wishing you had something else other than a UUID as the PK.
Re:PostgreSQL and UUID as Primary Key by rezonant on Saturday July 06, 2024 @07:47AM (#40889831)
This. Highly recommend using a numeric primary key + UUID. Using UUID relations internally can have some strategic advantages, but when UUIDv4 is used as the only primary key, you completely lose the ability to reliably iterate all records across multiple independent queries.

Also, the external thing isn't just for exposing it out to your own apps via APIs, but way more importantly for providing an unmistakable ID to store within external related systems. For example, in your Stripe metadata.

Doing this ensures that ID either exists in your own database or does not, regardless of database rollbacks, database inconsistencies etc. In those situations a numeric ID is a big question mark: Does this record correspond with the external system or was there a reuse of that ID?

I've been burnt taking over poorly managed systems that saved numeric IDs externally, and in trying to heal and migrate that data, ran into tons of problems because of ill-considered rollbacks of the database. At least after I leave the systems I build won't be subtly broken by such bad practices in the future.

Re:PostgreSQL and UUID as Primary Key by groestl on Saturday July 06, 2024 @07:11AM (#40889678)
Ha? Please elaborate.
Re:PostgreSQL and UUID as Primary Key by kroolik on Saturday July 06, 2024 @07:28AM (#40889751)
When running a batched migration it is important to batch using a strictly monotonic field so that new rows wont get inserted in already processed range
Re:PostgreSQL and UUID as Primary Key by asah on Saturday July 06, 2024 @08:46AM (#40890114)
would creation/lastmod timestamps cover this requirement?
Re:PostgreSQL and UUID as Primary Key by kroolik on Saturday July 06, 2024 @11:09AM (#40890861)
Yes, although timestamps may have collisions depending on resolution and traffic, no? Bigserials (at least in PG), are strictly monotonic (with holes).
Re:PostgreSQL and UUID as Primary Key by blackenedgem on Saturday July 06, 2024 @09:44AM (#40890428)
It's not even necessarily it being strictly monotonic. That part does help though as you don't need to skip rows.

For me the bigger thing is the randomness. A uid being random for a given row means the opposite is true; any given index entry points to a completely random heap entry.

When backfilling this leads to massive write amplification. Consider a table with rows taking up 40 bytes, so roughly 200 entries per page. If I backfill 1k rows sorted by the id then under normal circumstances I'd expect to update 6-7 pages which is ~50kiB of heap writes.

Whereas if I do that sort of backfill with a uid then I'd expect to encounter each page on a separate row. That means 1k rows backfilled is going to be around 8MB of writes to the heap.

Re:PostgreSQL and UUID as Primary Key by valenterry on Saturday July 06, 2024 @09:55AM (#40890493)
Isn't that solved because UUIDv7 can be ordered by time?
Re:PostgreSQL and UUID as Primary Key by blackenedgem on Saturday July 06, 2024 @10:42AM (#40890732)
Yeah pretty much, although ids can still be a little better. The big problem for us is that we need the security of UUIDs not leaking information and so v7 isn't appropriate.

We do use a custom uuid generator that uses the timestamp as a prefix that rotates on a medium term scale. That ensures we get some degree of clustering for records based on insertion time, but you can't go backwards to figure out the actual time. It's still a problem when backfilling and is more about helping with live reads.

Re:PostgreSQL and UUID as Primary Key by kroolik on Saturday July 06, 2024 @11:10AM (#40890868)
Are page misses still a thing in the age of SSDs?
Re:PostgreSQL and UUID as Primary Key by groestl on Saturday July 06, 2024 @09:48AM (#40890450)
Okay, but in a live DB, typically you won't have only inserts while migrating, won't you?
Re:PostgreSQL and UUID as Primary Key by kroolik on Saturday July 06, 2024 @11:06AM (#40890843)
Yes, but updates are covered by updated app code
Re:PostgreSQL and UUID as Primary Key by x3al on Saturday July 06, 2024 @10:20AM (#40890625)
Strictly monotonic fields are quite expensive and the bigserial PK alone won't give you that.
Re:PostgreSQL and UUID as Primary Key by kroolik on Saturday July 06, 2024 @11:06AM (#40890841)
PG bigserial is already strictly monotonic
Re:PostgreSQL and UUID as Primary Key by blackenedgem on Saturday July 06, 2024 @01:05PM (#40891683)
No they're not, even with a `cache` value of 1. Sequence values are issued at insert rather than commit. A transaction that commits later (which makes all updates visible) can have an earlier value than a previous transaction.

This is problematic if you try to depend on the ordering. Nothing is stopping some batch process that started an hour ago from committing a value 100k lower than where you thought the sequence was at. That's an extreme example but the consideration is the same when dealing with millisecond timeframes.

Re:PostgreSQL and UUID as Primary Key by iterateoften on Saturday July 06, 2024 @06:07AM (#40889388)
If you have an index on the uuid anyways having a separate big serial field for PK doesn’t help that much.
Re:PostgreSQL and UUID as Primary Key by rezonant on Saturday July 06, 2024 @07:55AM (#40889864)
As mentioned elsewhere, it ensures the ability to perform resumable and consistent batching queries across the data set without missing records.

Ordering over an insertion timestamp is not enough if two records may have the same timestamp: You may miss a record (or visit a record twice) across multiple queries.

Re:PostgreSQL and UUID as Primary Key by disneycember on Saturday July 06, 2024 @09:21AM (#40890307)
This is solved sorting by timestamp first then by random PK UUID. Don't think a little simpler batch queries justify leaking time and quantity information or complexity of handling two types of IDs.
Re:PostgreSQL and UUID as Primary Key by j45 on Saturday July 06, 2024 @02:46PM (#40892307)
I agree with not baking more intelligence into a piece of data than needed, especially an index.
Re:PostgreSQL and UUID as Primary Key by rezonant on Saturday July 06, 2024 @04:50PM (#40893171)
You wouldn't expose the numeric IDs publically, and ideally you'd use your database's automatic ID selection to avoid any complexity.

The UUID sorting works in the common case, but if you happen to end your batch near the current time, you still run the risk of losing a few records if the insert frequency is sufficiently high. Admittedly this is only a problem when you are batching through all the way to current insertions.

Re:PostgreSQL and UUID as Primary Key by j45 on Saturday July 06, 2024 @02:45PM (#40892302)
Sequential numbers can not be used publicly.

Also, security can be built around not allowing querying records which are not yours.

I'm all for a little security through obscurity including UUIDs but it shouldn't be the sole thing. Easier to generate a UUID for the sequential and let the database do what it does best (relate many serials among each other).

The other part is being able to use what's built into the database out of the box without a lot more configuration.

Selfishly, I always appreciate learning more about Postgres though :)

Re:PostgreSQL and UUID as Primary Key by arp242 on Friday July 05, 2024 @11:40PM (#40888011)
For almost all use cases just showing a UUIDv7 or sequential ID is fine. There are a few exceptions, but it's not the common case.
Re:PostgreSQL and UUID as Primary Key by mewpmewp2 on Friday July 05, 2024 @11:59PM (#40888083)
How would it be fine, e.g. for e commerce which is arguably very large portion of the use cases?

You would be immediately leaking how many orders a day your business is getting with sequential id.

Re:PostgreSQL and UUID as Primary Key by arp242 on Saturday July 06, 2024 @12:54AM (#40888243)
> You would be immediately leaking how many orders a day your business is getting with sequential id.

Which is fine for almost all of them. All brick and mortar stores "leak" this too; it's really not that hard to guess number of orders for most businesses, and it's not really a problem for the overwhelming majority.

And "Hi, this is Martin, I'd like to ask a question about order 2bf8aa01-6f4e-42ae-8635-9648f70a9a05" doesn't really work. Neither does "John, did you already pay order 2bf8aa01-6f4e-42ae-8635-9648f70a9a05" or "Alice, isn't 2bf8aa01-6f4e-42ae-8635-9648f70a9a05 the same as what we ordered with 7bb027c3-83ea-481a-bb1e-861be18d21ea?"

Especially for order IDs UUIDs are huge PITA because unlike user IDs and other more "internal" IDs, people can and do want to talk about them. You will need some secondary human-friendly unique ID regardless (possibly obfuscated, if you really want to), and if you have that, then why bother giving UUIDs to people?

Re:PostgreSQL and UUID as Primary Key by badestrand on Saturday July 06, 2024 @03:10AM (#40888689)
Best solution is to have a serial identifier internally and a generated ID for external. And yes it shouldn't be a UUID as they are user-hostile, it should be something like 6-10 letters+digits.
Re:PostgreSQL and UUID as Primary Key by inopinatus on Saturday July 06, 2024 @01:05AM (#40888274)
There are jurisdictions e.g. Germany in which a consecutive sequence for invoice numbers is a mandatory, legislated requirement (mercifully, gaps are generally permitted, with caveats)

For extra spice, in some places this is legislated as a per-seller sequence, and in others as a per-customer sequence, so there’s no policy you can apply globally, and this once again highlights the separation of concerns between a primary key and a record locator/identifier.

Re:PostgreSQL and UUID as Primary Key by wodenokoto on Saturday July 06, 2024 @01:45AM (#40888397)
> consecutive sequence for invoice numbers is a mandatory, legislated requirement (mercifully, gaps are generally permitted, with caveats)

That’s surprising. In Denmark gaps are not allowed. You have to account for all invoices and if you have an invoice numbered 50, then you have at least 50 invoices to account for.

Re:PostgreSQL and UUID as Primary Key by withinboredom on Saturday July 06, 2024 @08:56AM (#40890172)
It's nice when you change invoicing software, to be able to have gaps. For example, before Stripe is invoice <500 and Stripe invoices have >500. This makes it simple for humans to determine where an invoice may be located during the transition year. Further, it means we can plan the entire switch-over in advance, vs. only knowing the invoice number AFTER the switch-over. This makes a huge difference in internal communications to customer support, because you can let them know how things will operate once the switch is done. If you can't have gaps, you won't know how to tell customer support where to find new/old invoices until after the switch.
Re:PostgreSQL and UUID as Primary Key by tinodb on Sunday July 07, 2024 @03:12AM (#40895814)
In the Netherlands gaps aren’t allowed either, and I’m surprised that it is elsewhere, as that allows to you get rid of unwanted invoices whenever you want.

However you are allowed to have multiple sequences, differentiated through a prefix, but all starting at 0. That’s what we recently did to switch invoice generation tools (we actually still run both of them alongside each other atm).

Of course you could still drop some invoices from the end when you do this, but I guess tax authorities accept that risk.

Re:PostgreSQL and UUID as Primary Key by withinboredom on Sunday July 07, 2024 @10:06AM (#40897846)
The prefixes have to be in order though. You cannot start a prefix with A after already using prefix starting with B.
Re:PostgreSQL and UUID as Primary Key by JodieBenitez on Saturday July 06, 2024 @01:43AM (#40888390)
> There are jurisdictions e.g. Germany in which a consecutive sequence for invoice numbers is a mandatory

Same in France. I thought it was a pretty common requirement.

Re:PostgreSQL and UUID as Primary Key by sebazzz on Saturday July 06, 2024 @02:39AM (#40888560)
> As uuid v7 hold time information, they can help bad actors for timing attacks or pattern recognition because they contain a time information linked to the record.

Are you then not doing security by randomness if that is the thing that worries you?

Re:PostgreSQL and UUID as Primary Key by OskarS on Saturday July 06, 2024 @02:56AM (#40888623)
Can I ask (as a humble application developer, not a backend/database person), if the two requirements are:

1. The UUIDs should be ordered internally, for B-tree performance

2. The UUIDs should not be ordered externally, for security reasons

Why not use encryption? The unencrypted ID is a sequential id, but as soon as it leaves the database, it's always encrypted. Like, when getting it out:

    SELECT encrypt(id) FROM table WHERE something = whatever;
and when putting stuff in:

    UPDATE table SET something = whatever WHERE id = decrypt(<encrypted-key>)
Seems like the best of both worlds, and you don't need to store separate things.
Re:PostgreSQL and UUID as Primary Key by spencerap on Saturday July 06, 2024 @03:36AM (#40888795)
If the key and encryption mechanism are ever leaked, those opaque external IDs can be converted easily back to sequence numbers, and vice versa, which might pose a risk for you or your users. You won't be able to rotate the encryption key without breaking anything external that tracks those encrypted IDs... third party services, SEO, user bookmarks, etc.
Re:PostgreSQL and UUID as Primary Key by OskarS on Saturday July 06, 2024 @03:45AM (#40888834)
You store the key in the database, right? Like, if the database leaks, it doesn’t matter if your ids are sequeneced or unsequenced, because all data has leaked anyway. The key leaking doesn’t seem like a realistic security issue.
Re:PostgreSQL and UUID as Primary Key by zxexz on Saturday July 06, 2024 @04:37AM (#40889034)
Ideally if you do this, you store the key in a separate schema with proper roles so that you can call encrypt() with the database role, which can't select the key. Even then, the decrypted metadata should not be particularly sensitive - and should immutably reference a point in time so you can validate against some known key revocation retroactively.

My take is it's rarely necessary to have a token, that you give to an external entity, that has any embedded metadata all - 99.9% of apps aren't operating at a scale where even a million-key hashmap sitting in ram and syncing changes to disk on update would cause any performance difference.

Re:PostgreSQL and UUID as Primary Key by OskarS on Saturday July 06, 2024 @07:09AM (#40889669)
This is a very weird thread: half the people are arguing that having these timestamps is not a realistic security problem at all, and the other half is arguing that any fix to it has to have Fort Knox level security policies.

It seems to me: the actual value of knowing these ids/timestamps to a hacker is tiny, but it's not nothing (German tank problem and all that). Like, if a hacker was able to decode the timestamps, it's not ideal, but it's not like a catastrophe either (especially given that half the people in this thread thinks it has no security value at all). Given that threat model, a simple scheme like I suggested seems fine to me.

Re:PostgreSQL and UUID as Primary Key by stoperaticless on Saturday July 06, 2024 @05:34AM (#40889268)
> The key leaking doesn’t seem like a realistic security issue.

But it is.

If you have a password in a system, you want to rotate it regularly or at least have that ability (for example, when angry colleague leaves).

Re:PostgreSQL and UUID as Primary Key by fauigerzigerk on Saturday July 06, 2024 @03:46AM (#40888836)
>Why not use encryption?

Because then you have a key management problem, which adds complexity.

Re:PostgreSQL and UUID as Primary Key by thiht on Saturday July 06, 2024 @03:55AM (#40888872)
I don’t understand how that’s an issue. Do you have an example of a possible attack using UUIDv7 timestamp? Is there evidence of this being a real security flaw?
Re:PostgreSQL and UUID as Primary Key by cqqxo4zV46cp on Saturday July 06, 2024 @08:53AM (#40890153)
I don’t understand this thinking. If you understand what’s at play, you can infer the potential security implications. What you’re advocating for is being entirely reactive instead of also being proactive.
Re:PostgreSQL and UUID as Primary Key by thiht on Saturday July 06, 2024 @10:44AM (#40890737)
No, I don’t. Even with a timestamp uuids are not enumerable, and honestly I don’t care that the timestamp they were created at is public. Is the version of uuid used being a part of the uuid considered a leak too?
Re:PostgreSQL and UUID as Primary Key by whynotmaybe on Saturday July 06, 2024 @09:17AM (#40890280)
The draft spec for uuid v7 has details about the security considerations : https://www.ietf.org/archive/id/draft-peabody-dispatch-new-u...

The way I see it is that uuid v7 in itself is great for some use but not for all uses.

You always have to remember that a v7 always carries the id's creation time as metadata with it, whether you want it or not. And if you let external users get the v7, they can get that metadata.

I'm not a security expert but I know enough to know that you should only give the minimal data to a user.

My only guess is that v7 being so new, attacks aren't widespread for now, and I know why the author decided not to focus on "if UUID is the right format for a key", because the answer is no 99% of the time.

Re:PostgreSQL and UUID as Primary Key by thiht on Saturday July 06, 2024 @10:51AM (#40890775)
That just seems overly cautious. I’d rather use UUIDv7 unless I have a reason not to. The convenience of sortable ids and increased index locality are very much worth the security issues associated with UUIDv7. Maybe I wouldn’t use UUIDv7 for tokens or stuff like that, but DB IDs seem pretty safe.
Re:PostgreSQL and UUID as Primary Key by timmytokyo on Saturday July 06, 2024 @12:55PM (#40891613)
I don't get it either. If UUIDv7 lacks security due to its revelation of a timestamp, why don't bigserials also lack security? After all, given a bigserial ID, you can tell whether it was generated before or after some other bigserial ID and thereby infer something about the time it was generated.
Re:PostgreSQL and UUID as Primary Key by j45 on Saturday July 06, 2024 @03:10PM (#40892491)
BigSerials come from a relational database world for me.

The use of UUIDs for documents may come from a no-sql background.

I use bigserials for relational data in relational databases, and if there is a unique document value needed, a UUID is good.