← Back to PostgreSQL, page 5

postgresql-0093 · Hard senior

Should primary keys be bigint identities or UUIDs? Weigh index locality, exposure and distributed generation.

bigint identities are compact (8 bytes), sequential so inserts append to the right of the B-tree, and cheap to join, but they reveal row counts and need the database to generate them. Random UUIDv4 values (16 bytes) can be generated anywhere and leak nothing, but scatter inserts across the index, causing more page splits, cache misses and WAL. Time-ordered UUIDs (UUIDv7) keep most of the locality while staying globally unique.

Full answer

Trade-offs in detail:

  • Size: uuid is 16 bytes against 8 for bigint; every index containing the key, including foreign-key indexes in child tables, grows accordingly.
  • Locality: sequential keys keep the hot part of the index small and in memory. Random UUIDs touch random leaf pages, so on large tables inserts read pages from disk and full-page writes after checkpoints add WAL volume.
  • Generation: UUIDs can be created by clients or services before inserting, which helps offline-first apps, merging data from several databases, and idempotent APIs where the client chooses the id.
  • Exposure: sequential ids in URLs let outsiders guess other records and estimate volume; a separate public UUID or slug avoids this while keeping a bigint internal key.

PostgreSQL 17 provides gen_random_uuid() (version 4) natively; UUIDv7 needs an extension or application-side generation on 17, and PostgreSQL 18 adds uuidv7(). (Not run here, since generated values are random.)

A common compromise: bigint identity as the primary key used in joins, plus a unique UUID column exposed in APIs. When ids must be generated outside the database, prefer UUIDv7 over v4 for new tables.

Key points

  • bigint is compact and sequential
  • Random UUIDs hurt index locality
  • UUIDs can be generated anywhere
  • Sequential ids leak counts
  • UUIDv7 or bigint plus public UUID are common compromises

Common mistakes

  • Random UUIDv4 keys on very large insert-heavy tables without considering locality
  • Exposing sequential ids where enumeration matters

Follow-ups

  • How would you migrate a table from bigint to UUID keys?
  • What is the storage cost of uuid in child tables?

Tips

  • Mention UUIDv7