Full answer
Considerations:
- Size: bigint is 8 bytes; a UUID is 16 bytes in a native type (36 if stored as text, which should be avoided). Every foreign key and secondary index carries the key.
- Insert pattern: sequential keys append to the right edge of the B-tree. Random UUIDv4 values land anywhere, causing more page splits and cache misses on large tables.
- Generation: UUIDs can be created by clients, offline devices or several services without coordination, which helps merges and idempotent inserts.
- Exposure: sequential ids in URLs reveal growth and invite enumeration; a UUID or a separate public id avoids that.
A common compromise is a bigint primary key internally plus a unique random public id for URLs, or UUIDv7 as the single key. PostgreSQL 18 adds a built-in uuidv7() function; on older versions it comes from an extension or the application (stated from documentation, not run here).
Key points
- bigint keys are compact and sequential
- UUIDs allow decentralised generation
- Random UUIDs hurt index locality
- UUIDv7 is time ordered
- Store UUIDs in a native type, not text
Common mistakes
- Storing UUIDs as 36-character text
- Exposing sequential ids where enumeration matters
Follow-ups
- How would you add a public id to an existing table?
- Do UUID keys prevent all enumeration attacks?
Tips
- Weigh size, locality and generation