r/ruby • • 3d ago

Blog post UUIDv7 primary keys in Rails and PostgreSQL

https://www.randomerrata.com/articles/2026/uuidv7/
35 Upvotes

5 comments sorted by

6

u/harun_91 3d ago

This is a great article the only thing that kinda feels of (at least for me) is:

The trade-off is that the ID reveals when the record was created. If that information is sensitive for a given table, UUIDv7 isn't the right choice.

Why would the timestamp of a record would be sensitive? TBF I can't come up with a valid reason in my head.

4

u/k33l0r 3d ago edited 3d ago

It’s something that commonly gets brought up about v7 UUIDs. Personally I’ve never worked on a project where I’d care… 

3

u/bhaak 3d ago

Leaking timestamps will allow to estimate how many records are generated in a specific time period. This may or may not be sensitive information.

It's basically the German tank problem.

1

u/Equivalent-Bad-268 3d ago

The company I work for now doesn't allow users of our product to know the exact date of an object for possible deanonymization of PHI.

13

u/dkam 3d ago

I enjoyed your post!

> but once your code relies on IDs being in creation order, a stray v4 ID is a correctness bug, not a style problem.

There's a performance problem with mixing v4 and v7 in the same index too. Until ~2039 every v7 starts with 0x01, so ~99% of v4 values sort after all of your v7s.

When Postgres splits B-tree pages, the page being split is the rightmost leaf, it fills the left page to the fillfactor (90% by default). That's the normal case for v7, since new IDs always go to the right end. Any other page splits roughly 50/50. Once there are more v4s than fit on about one leaf page, new v7s land just before the v4 block instead of on the rightmost page. Every split then leaves behind a half-empty page that will never be filled, so you get a larger, sparser index that needs REINDEX CONCURRENTLY or pg_repack from time to time.

I discovered this by switching from v4 to v7 and expecting a nicer packed index. Sadly we need to periodically `REINDEX CONCURRENTLY` to keep the index neat.