Video in progress
You plan to use UUIDs as primary keys. How do you choose between UUIDv4 and UUIDv7, and how do you set it up in Hibernate?
UUIDv4 is random, so it writes to the B-tree index all over the place and slows down on large tables. Time-ordered UUIDv7 almost eliminates that problem. Hibernate 6 has @UuidGenerator(style = TIME), but it is not v7, so for v7 you often need your own generator.
📖 Answer
The reasons for choosing a UUID are usually clear: you can create the ID without going to the database, merge across services without collisions, and avoid exposing sequential IDs in URLs. The price is the index.
UUIDv4 is random. Every new row lands on a random page of the B-tree: pages split, they don't stay in cache, WAL volume grows. On a table with a hundred million rows, INSERT speed can drop several times compared to bigint. Also a UUID is 16 bytes and a bigint is 8, so every foreign key and index is twice as big.
UUIDv7 starts with a millisecond timestamp, so new values land at the end of the index, just like a sequence.
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME)
private UUID id;
One catch: Style.TIME in Hibernate 6 produces a v1-style time-based UUID. It is not v7, and it is not guaranteed to be ordered for the B-tree the way v7 is. Newer Hibernate versions (7.x) added separate support for v7. If I need real v7, I write my own BeforeExecutionGenerator using a small library (for example uuid-creator), or assign the ID in the constructor.
On PostgreSQL the column type should be uuid, not varchar(36). On MySQL, BINARY(16).
My default recommendation: bigint + sequence for internal tables, UUIDv7 for IDs that go outside or are created in a distributed way. You can also use both together: a bigint PK internally and a unique public_id outside.
Sign up to mark studied questions and save your progress.