Video in progress

Strong Middle 🌱 Spring

What do you consider when choosing between a Long sequence and a UUID as a table's primary key, and how does a random UUID affect the index?

A Long sequence is compact and lands at the end of the B-tree index. A random UUID (v4) lets you generate the id without going to the database and can't be guessed, but it lands all over the index: inserts get slower on a big table and the cache works badly. A time-based UUID v7 largely removes that problem.

📖 Answer

Two questions get mixed up here: "which id do we show to the outside" and "what do we join on in the database".

Long sequence:

  • 8 bytes, so FKs and indexes stay compact;
  • new values go to the end of the index, so inserts are cheap and pages are dense;
  • but if it is exposed to the outside, sequential numbers reveal your business volume and make it easy to enumerate ids.

UUID v4 (random):

  • 16 bytes, so every FK and index is bigger;
  • every insert lands at a random spot in the index: pages split and the buffer cache has no "hot" part left. With tens of millions of rows you clearly see it in insert speed and disk I/O;
  • the upside is that the application or client creates the id itself (idempotency, offline mode, merging data across services).

UUID v7 starts with a millisecond timestamp, so values grow roughly monotonically. The index behaves much like it does with a sequence, and you keep the benefits of a UUID.

@Entity
class Order {
    @Id
    private UUID id = UuidCreator.getTimeOrderedEpoch();   // uuid-creator library, v7
    // ...
}

In PostgreSQL use the uuid type, not varchar(36): the latter takes more than twice the space and compares slower.

For an entity whose id is assigned up front, Spring Data save() decides it is "not new" and does a merge, which costs an extra SELECT. Make the "is new" status explicit with a @Version field or Persistable.

A compromise you see a lot in practice: a bigint PK and FKs internally, and a separate unique public_id uuid column for the outside. Whichever you pick, the id type is no substitute for an ownership check.