How-To Guide

How to Choose a Primary Key Type

Pick between auto-increment, UUID and time-ordered identifiers by weighing index locality, predictability and uniqueness.

On this page

  1. Introduction
  2. What a Primary Key Does
  3. Auto-Increment Integers
  4. Random UUIDs
  5. Time-Ordered Identifiers
  6. Exposure and Authorization
  7. Practical Defaults
  8. Conclusion

Introduction

A primary key looks like a trivial choice and turns out to affect insertion performance, index size, sort order and security. An auto-increment integer is compact and inserts at the end of the index, but it is predictable and hard to generate in a distributed system. A random UUID is generated anywhere without coordination, but its randomness scatters inserts across the index and makes the key wide. A time-ordered UUID keeps the size and uniqueness of a UUID while restoring the insert locality of an integer. This article compares the families and shows how the choice interacts with replication and exposure.

What a Primary Key Does

A primary key identifies a row uniquely, backs the clustered index in a clustered database, and often appears in every secondary index as a pointer. Three properties matter: uniqueness (across the system, not just a table), insert locality (where new keys land in the index), and width (how many bytes the key adds). A predictable key is a fourth property, relevant when the key is exposed in URLs.

The trade-offs are in tension. The most compact, most local key is an ordered integer, which is also the most predictable. The most flexible, least predictable key is a random UUID, which is wide and scatters inserts. Choosing is deciding which property matters most for this table.

Auto-Increment Integers

A 64-bit integer is eight bytes, and a sequential value inserts at the rightmost leaf of the index, which is optimal for insertion: the new row’s page is already in cache, and the index does not fragment. It is the best default for a single-database table that does not expose its keys publicly.

Its weaknesses are predictability (an attacker can enumerate rows by trying consecutive ids, so the id should not be the only authorization check) and coordination in a distributed system: two databases both starting from one collide. For a sharded system, a block allocation or a composite key with a shard prefix is needed, which adds complexity.

Random UUIDs

A UUID version 4 is 128 bits, generated independently on any node without coordination, which makes it the natural choice for a distributed system or a client that generates ids offline. Its uniqueness is effectively global, so merging datasets or shards does not need a conflict-resolution step.

The cost is insert locality: a random 128-bit value lands at a random position in the index, so each insert touches a different page, causing cache misses and index fragmentation, and the key is twice the size of a bigint in every index. On a write-heavy table this can measurably reduce throughput.

-- Random UUID v4: globally unique, but inserts scatter across the index.
CREATE TABLE events_v4 (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  body jsonb NOT NULL
);

-- Time-ordered UUID v7: same width and uniqueness, but monotonic in time,
-- so inserts land at the right edge of the index like a sequence.
CREATE TABLE events_v7 (
  id uuid PRIMARY KEY DEFAULT uuidv7(),
  body jsonb NOT NULL
);

-- Compare index growth and insert throughput between the two tables.
INSERT INTO events_v4 (body) SELECT '{}'::jsonb FROM generate_series(1, 1000000);
INSERT INTO events_v7 (body) SELECT '{}'::jsonb FROM generate_series(1, 1000000);

Time-Ordered Identifiers

A UUID version 7, or a ULID, encodes a timestamp in the leading bits and random bits after, so values generated later sort after values generated earlier. This restores insert locality while keeping the 128-bit uniqueness and the offline generation of a UUID. It is the best of both for a table that needs globally unique ids and good insert performance.

When you use a time-ordered id, be aware that it reveals the creation time, which may be acceptable or may leak information you would rather not expose. If the timestamp must be hidden, use a random UUID and accept the insert cost, or keep a separate opaque public identifier and use the time-ordered one internally.

Exposure and Authorization

A sequential key exposed in a URL invites enumeration: an attacker tries neighbouring ids to find resources they should not see. If the key is also the authorization check, that is a broken access control. Never rely on the key being hard to guess for authorization; check the owner explicitly. Use an opaque identifier for the public URL if enumeration is a concern, while keeping an internal key for joins.

Some systems use a composite key, such as tenant plus a local sequence, which keeps the key compact and local within a tenant and makes cross-tenant enumeration impossible. This is a strong pattern for multi-tenant tables, because the tenant prefix also improves locality for tenant-scoped queries.

-- Composite key: tenant plus a per-tenant sequence. Compact, local, and
-- impossible to enumerate across tenants.
CREATE TABLE documents (
  tenant_id uuid NOT NULL,
  doc_no    bigint NOT NULL,
  body      jsonb NOT NULL,
  PRIMARY KEY (tenant_id, doc_no)
);

-- A per-tenant sequence (or a counter row) provides doc_no within each tenant,
-- so ids are small and ordered locally, and a query for one tenant reads
-- contiguous index ranges.
CREATE SEQUENCE documents_doc_no_seq;   -- one global sequence is fine too

-- A foreign key must carry both columns to remain tenant-scoped.
CREATE TABLE document_versions (
  tenant_id uuid NOT NULL,
  doc_no    bigint NOT NULL,
  version   int NOT NULL,
  PRIMARY KEY (tenant_id, doc_no, version),
  FOREIGN KEY (tenant_id, doc_no) REFERENCES documents (tenant_id, doc_no)
);

Practical Defaults

For a single-node table, an auto-increment bigint is a good default: compact, local, and fast. For a distributed or offline-generated key, use a time-ordered id (UUID v7 or ULID) rather than a random one, unless the creation time must be hidden. For a multi-tenant table, consider a composite key of tenant and a local sequence.

Whatever you choose, keep the type consistent across foreign keys; a mismatch forces implicit casts and can prevent the use of an index. Size the key once at the start, because changing the primary key of a large table later is expensive, and the choice is one of the harder ones to reverse.

Conclusion

A primary key type is a trade among uniqueness, insert locality, width and predictability. An auto-increment bigint is compact and local but predictable and hard to coordinate across nodes. A random UUID is globally unique and offline-generatable but wide and scatters inserts. A time-ordered UUID v7 keeps the 128-bit uniqueness while restoring locality, at the cost of revealing the creation time. Choose from the table’s needs, keep the key type consistent across references, and never use the key’s unpredictability as the authorization check.

Sources: RFC 9562: UUID (v7), SQL Server: GUID vs integer keys, ULID specification.

FAQ

Why do random UUIDs hurt insert performance?
A random value lands at a random position in the index, so each insert touches a different page, causing cache misses and index fragmentation. A time-ordered UUID encodes a timestamp in the leading bits, so inserts land at the right edge like a sequence.
Can I rely on an unguessable key for authorization?
No. Security through an opaque identifier is defence in depth, not authorization. Check ownership explicitly, because a key can leak through logs, URLs or a previous API response, and a sequential key invites enumeration outright.

Related Examples