Articles

UUID vs Auto-Increment Primary Keys: Which to Use

UUIDs vs auto-increment primary keys: sequential integers are compact and index-friendly, UUIDs are globally unique and unguessable. How to choose.

The Lycoris Team The Lycoris Team · · 5 min read
A library card catalog drawer, representing indexed lookup

The choice between a UUID and an auto-increment primary key comes down to who generates the ID and where. An auto-increment key is a sequential integer the database hands out on insert: small, fast, and naturally ordered. A UUID is a 128-bit identifier any machine can generate on its own with a negligible chance of collision: bigger and harder to index well, but globally unique and impossible to guess. Neither is universally better. Most of the trade-offs follow from that single difference.

How auto-increment keys work

An auto-increment column (SERIAL or GENERATED ... AS IDENTITY in PostgreSQL, AUTO_INCREMENT in MySQL) is backed by a counter. Each insert takes the next value: 1, 2, 3, and so on. The database guarantees the values are unique within that table, though not gap-free. A rolled-back transaction still consumes its number, so gaps are normal and harmless.

The appeal is obvious. A 64-bit integer is 8 bytes. It compares quickly, it fits neatly into a B-tree index, and because every new row gets a larger value than the last, inserts always land at the right-hand edge of the index. Pages fill up in order, and the index stays compact.

How UUIDs work

A UUID is a 128-bit value usually written as 36 characters of hex and hyphens, such as 3f2b8c1e-7a4d-4e9b-9c2a-5d6e7f8a9b0c. There are several versions, and the version matters a lot for databases:

  • UUIDv4 is almost entirely random. Two machines generating IDs at the same moment will not collide in any practical sense, but consecutive IDs have no relationship to each other.
  • UUIDv7 puts a millisecond timestamp in the most significant bits and fills the rest with random data. IDs generated later sort after IDs generated earlier, so they behave much more like a sequence while staying globally unique.

Older time-based versions exist too, but v4 and v7 are the two you will meet most in modern application code. Store UUIDs in a native uuid type (16 bytes) rather than as text (36 bytes plus overhead) whenever your database offers one.

UUID vs auto-increment at a glance

Auto-increment integerUUIDv4UUIDv7
Size4 or 8 bytes16 bytes16 bytes
Who generates itThe database, on insertAnyone, anywhereAnyone, anywhere
OrderingStrictly increasingRandomRoughly time-ordered
Index insert patternAppend at the endScattered across the indexMostly append
GuessableYes, triviallyNoPartly (timestamp is visible)
Safe to merge across databasesNo, values collideYesYes
Human readabilityEasy to read and sayLong and opaqueLong and opaque

Why random UUIDs hurt index performance

The cost of UUIDv4 is mostly about locality, not raw size. With an increasing key, the database writes new entries to the last leaf page of the index, which is almost always already in memory. With random keys, each insert lands on an arbitrary page. Over time that means more pages pulled from disk, more page splits, half-empty pages, and a larger index overall.

This hits hardest when the primary key also determines the physical row order, as in a clustered index like InnoDB’s. Every secondary index in that design also stores the primary key, so a 16-byte random key inflates every index on the table. In PostgreSQL, where tables are heaps and the primary key is a separate index, the effect is smaller but still real.

UUIDv7 largely fixes this. Because the leading bits are a timestamp, new IDs cluster at the end of the index the way integers do. If you want UUIDs and care about write performance, v7 is usually the version to reach for. The general mechanics of why ordering matters are covered in our guide to database indexing.

Where auto-increment keys fall short

Sequential integers have three practical weaknesses.

They leak information. If your order URL is /orders/10482, anyone can guess that /orders/10483 exists, and anyone who signs up twice a month apart can estimate how many customers you added in between. Exposed sequential IDs make enumeration attacks easy whenever authorization checks are missing. Proper access control is the real fix, but unguessable IDs are a useful second layer.

They need a central authority. Only the database can hand out the next number, so the client cannot know a record’s ID until the insert returns. That complicates offline-first apps, batch imports, and any flow where the client wants to create related records in one go.

They collide across systems. Merging two databases, or splitting one through sharding, turns “user 42” into an ambiguous reference. Workarounds exist, such as per-shard offsets or a dedicated ID service, but they add moving parts.

Where UUIDs earn their keep

UUIDs shine whenever IDs are created in more than one place. A mobile client can generate an ID before it ever talks to the server, which makes retries safe: sending the same create request twice with the same ID is naturally idempotent. Distributed services can mint IDs without coordinating. Data from multiple regions or tenants can be merged without rewriting keys.

They are also a better default for anything exposed in URLs or APIs, because knowing one ID tells an attacker nothing about the next.

A common hybrid

Many teams use both. The table keeps a compact bigint identity column as its internal primary key, which every foreign key and join uses. A separate UUID column, with a unique constraint, is what the outside world sees in URLs and API responses. You get small, fast joins internally and opaque identifiers externally. The cost is an extra column and an extra index, plus the discipline to never leak the internal ID. If you are unsure how unique constraints differ from primary keys, see primary keys vs foreign keys vs unique constraints.

How to choose

  • Single database, internal IDs, write-heavy tables: a bigint identity column is hard to beat.
  • IDs created on clients or across services: UUIDs, preferably v7.
  • IDs visible to users or in public URLs: UUIDs, or the hybrid approach.
  • Existing UUIDv4 keys causing index bloat: consider v7 for new tables rather than migrating old ones.

Avoid 32-bit integer keys on tables that might grow large. Running out of int range on a busy table is a painful migration that a bigint would have avoided at almost no cost.

The takeaway

Auto-increment keys are small, ordered, and fast, but they depend on one database to issue them and they reveal more than you might want. UUIDs can be generated anywhere and reveal nothing, at the cost of size and, for random v4, index locality. Time-ordered UUIDv7 closes most of that gap, and the hybrid pattern of an internal integer plus a public UUID gives you the strengths of both.