Video in progress

How do you choose a primary key strategy for a new system: a `bigint` sequence, UUIDv4, UUIDv7, or a Snowflake ID?

For a single database and an internal ID, a bigint identity is the most compact and fast. For an ID that is exposed externally or generated in a distributed way, UUIDv7: it's ordered by time, so it doesn't hurt a B-tree the way UUIDv4 does. I avoid making UUIDv4 the PK on a big table.

📖 Answer

The main difference is where the write lands in the index. A sequence and UUIDv7 grow upward, so new rows land at the right edge of the index: hot pages stay in cache, with few page splits. UUIDv4 is random, so every insert lands anywhere in the index. When the index is bigger than memory, every insert reads a page from disk, full page writes in the WAL multiply, and the index bloats with half-empty pages.

bigint UUIDv4 UUIDv7 Snowflake
Size 8 bytes 16 16 8
Ordered yes no by time by time
Generated without the DB no yes yes yes (needs a worker ID)
Guessable yes no partly (the time shows) partly

Other factors:

  • Security. /orders/1001 with sequential IDs shows a competitor how many orders you get per day and makes IDOR bugs easier. An internal bigint PK + an external UUID column is a widespread compromise.
  • JPA. The IDENTITY strategy disables batch inserts in Hibernate; SEQUENCE + allocationSize=50 (and INCREMENT BY 50 in the database) is faster. Generating a UUID in the application doesn't get in the way of batching either.
  • Sharding/merging. If data created in several databases has to be merged later, sequences collide: UUIDv7 or Snowflake.

PostgreSQL 18 added a uuidv7() function; in earlier versions it's generated in the application (for example with the java-uuid-generator library). In a new distributed system I make UUIDv7 the default, and in purely internal, big tables, bigint.