UUID as Primary Key

Difficulty: Intermediate

Question

What are the drawbacks of using UUIDs as primary keys compared to auto-increment integers, and how can you reduce them?

Answer

UUIDs are 16 bytes instead of 4 or 8, and the common random version (UUIDv4) inserts at random positions in the primary key index, which causes page splits, poor cache use and extra write I/O, especially in databases that cluster rows by primary key such as MySQL InnoDB. They are also harder for humans to read and debug. Using time-ordered UUIDv7, storing them in a native 16-byte type, and keeping a compact internal key where it matters removes most of the pain.

Why random UUIDs hurt index performance

A B-tree primary key with auto-increment ids always appends to the rightmost leaf page. The hot page stays in memory and pages fill completely.

With UUIDv4, each new key lands at a random point in the tree:

  • The target leaf page is often not in memory, so inserts cause random disk reads.
  • Full pages split in half, leaving pages around half to two-thirds full and growing the index.
  • More dirty pages per insert means more write I/O. In PostgreSQL, touching many different pages after each checkpoint also means more full-page images in the WAL.

In InnoDB the table itself is the clustered primary key index, so random keys scatter the actual row data, not just an index. PostgreSQL stores rows in an unordered heap, so the effect is limited to the indexes, but it is still measurable on large, write-heavy tables.

Size costs

Key typeSizeNotes
INT4 bytesMax about 2.1 billion; risky for big tables
BIGINT8 bytesPractical default for auto-increment
UUID native / BINARY(16)16 bytesTwice a BIGINT
UUID as CHAR(36)36 bytes plus overheadCommon mistake, avoid

The primary key is repeated in every foreign key column and, in InnoDB, in every secondary index entry. A wide key multiplies across the schema.

Other drawbacks

  • Readability: "order 48213" is easy to say on a support call; 0192f5c4-... is not.
  • No natural ordering with UUIDv4, so ORDER BY id is not creation order.
  • Storage format bugs: storing as text in some services and binary in others, or mixing upper and lower case.

Why people use them anyway

  • Ids can be generated anywhere (client, multiple services, offline mobile apps) without a central sequence.
  • Merging data from multiple databases or shards never collides.
  • Ids in URLs are not guessable or enumerable, unlike /orders/1001, /orders/1002.

How to reduce the downsides

  • Use UUIDv7. Standardised in RFC 9562 (2024), it puts a millisecond Unix timestamp in the high bits, so new ids are roughly sequential and insert near the right edge of the index like an auto-increment. PostgreSQL 18 includes a built-in uuidv7() function; on older versions generate it in the application or with an extension.
  • Use the native type. PostgreSQL UUID (16 bytes); in MySQL use BINARY(16) with UUID_TO_BIN(), whose swap flag reorders time fields for UUIDv1.
  • Hybrid keys. Keep a BIGINT identity as the internal primary key for joins, and add a unique public_id UUID column for APIs and URLs.
  • Alternatives: ULID or Snowflake-style 64-bit ids, which are also time-ordered.
Primary key options. Time-ordered UUIDs keep most benefits of both worlds.
BIGINT identityUUIDv4UUIDv7
Size8 bytes16 bytes16 bytes
Insert patternSequentialRandomRoughly sequential
Generate without the DBNoYesYes
Guessable in URLsYesNoHard, but leaks creation time

Code examples

UUID options in PostgreSQL

-- Random UUIDv4 (built in since PostgreSQL 13)
CREATE TABLE sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid()
);

-- Time-ordered UUIDv7 (built in since PostgreSQL 18)
CREATE TABLE events (
  id UUID PRIMARY KEY DEFAULT uuidv7(),
  payload JSONB
);

-- Hybrid: compact internal key, opaque public id
CREATE TABLE orders (
  id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  public_id UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
  amount_paise BIGINT NOT NULL
);

The hybrid design joins on an 8-byte key internally while exposing a non-guessable UUID in URLs and APIs.

Storing UUIDs compactly in MySQL 8

CREATE TABLE payments (
  id BINARY(16) PRIMARY KEY,         -- 16 bytes, not CHAR(36)
  amount_paise BIGINT NOT NULL
);

-- Swap flag 1 reorders UUIDv1 time fields so inserts are sequential
INSERT INTO payments (id, amount_paise)
VALUES (UUID_TO_BIN(UUID(), 1), 49900);

SELECT BIN_TO_UUID(id, 1) AS id, amount_paise FROM payments;

MySQL's UUID() returns version 1. Storing it as BINARY(16) with the swap flag keeps the clustered index append-friendly.

Key points

  • UUIDs are 16 bytes vs 8 for BIGINT, and the key is repeated in foreign keys and InnoDB secondary indexes
  • Random UUIDv4 inserts cause page splits, cache misses and extra write I/O
  • UUIDv7 (RFC 9562) is time-ordered and fixes most insert performance problems
  • Store UUIDs as native UUID or BINARY(16), never CHAR(36)
  • A common pattern is a BIGINT internal key plus a UUID public id

Common follow-up questions

  • How is UUIDv7 structured and why does it insert sequentially?
  • What is the difference between UUID, ULID and Snowflake ids?
  • Why is the impact of random keys larger in InnoDB than in PostgreSQL?
  • Is exposing auto-increment ids in URLs a security problem?

Interview tips

  • Explain the random insert problem in terms of B-tree pages; that is the core of the answer
  • Mention UUIDv7 and PostgreSQL 18's uuidv7() to show you are current
  • Also state why teams choose UUIDs, so the answer is balanced rather than anti-UUID

Concepts covered

UUID, UUIDv7, Clustered Index, Page Splits, Auto-increment Keys

More Database Design questions