Sub topic 15
When not to use sequential IDs
This chapter assumes you can create identity columns, know the difference between GENERATED ALWAYS and GENERATED BY DEFAULT, and know why sequence values can have gaps. It covers the cases where an identity column is the wrong choice, or only part of the answer, and what to use in those cases.
What sequential IDs do well
An identity column gives you a small, fast, ordered key. A bigint takes 8 bytes. New rows land at the right edge of the primary key index, so inserts stay cheap. Values are easy to read in logs and easy to type into a query.
Most tables never need anything else. The problems below show up in specific situations, so check whether you are in one before you change a working design.
Problem 1: the ID leaks information
If your API exposes /orders/10432, anyone can request /orders/10433. This causes two separate issues:
- Enumeration. An attacker can walk through every ID. If you forgot an authorization check on one endpoint, this makes the mistake easy to exploit.
- Volume disclosure. Two orders placed a week apart reveal how many orders you take per week. Competitors can use this.
Hiding the ID is not a substitute for authorization. Still, an unguessable identifier removes a whole class of cheap attacks and stops the volume leak.
Problem 2: IDs must exist before the insert
A sequence lives in one database. Several situations make that awkward:
- A client, such as a mobile app working offline, needs to create a record and refer to it before the server has seen it.
- A client retries a request after a timeout and must not create a duplicate.
- Several databases, for example one per region, produce rows that later get merged.
- You shard data across servers and no single sequence can serve them all.
In these cases the identifier must be created outside the database or independently on each node. A UUID (universally unique identifier, 128 bits) is designed for this. Collisions are practically impossible without any coordination.
The same property gives you idempotent inserts. The client generates the ID once and reuses it on each retry:
CREATE TABLE events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
payload jsonb NOT NULL
);
INSERT INTO events (id, payload)
VALUES ('0b0c7f3e-5a1d-4c53-9f0a-3f6a2b1d9e10', '{"type": "signup"}')
ON CONFLICT (id) DO NOTHING;Running that statement twice stores one row. With an identity column the server picks the ID, so a retried insert creates a second row unless you add another unique constraint.
gen_random_uuid() is built in from PostgreSQL 13. Earlier versions need the pgcrypto extension.
UUID trade-offs
UUIDs cost something. Know the costs before switching.
| Property | `bigint` identity | UUID version 4 (random) | UUID version 7 (time-ordered) |
|---|---|---|---|
| Size | 8 bytes | 16 bytes | 16 bytes |
| Insert locality in the index | Excellent | Poor | Good |
| Guessable | Yes | No | No, but the creation time is visible |
| Generated without the database | No | Yes | Yes |
| Human-friendly | Yes | No | No |
Size multiplies
The primary key is copied into every secondary index and into every foreign key column that references it. A 16-byte key instead of an 8-byte one makes each of those structures larger. Larger indexes mean fewer entries per page and a lower cache hit rate.
Random keys scatter writes
A version 4 UUID is random. Each insert lands on an arbitrary leaf page of the primary key B-tree. On a large table this causes more page splits, more cache misses, and more write-ahead log (WAL) volume, because the first change to each page after a checkpoint writes a full page image. On a table that fits in memory you may never notice. On a table of hundreds of millions of rows the difference can be measurable.
Time-ordered UUIDs
A version 7 UUID begins with a millisecond timestamp, followed by random bits. New values sort roughly in creation order, so inserts cluster at the right edge of the index again, much like a sequence. PostgreSQL 18 adds a built-in uuidv7() function. On older versions you generate version 7 values in the application or with an extension.
Two cautions apply. The timestamp is readable from the value, so you still disclose when a row was created. Also, ordering holds across nodes only as far as their clocks agree.
A common compromise: internal and public IDs
You do not have to pick one. Keep a compact identity primary key for joins and foreign keys, and add a UUID column for anything that leaves the database:
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,
name text NOT NULL
);
INSERT INTO customers (name) VALUES ('Ada') RETURNING id, public_id;Foreign keys point to id, so the small key is what gets copied around. APIs, URLs and exports use public_id. The cost is one extra unique index and one extra lookup when a request arrives with a public ID.
This does not help with the offline-creation or multi-node cases. There the primary key itself must be generated outside a single sequence.
Problem 3: you need a gapless counter
Identity values are not a counter. A rolled-back insert still consumes a value, a crash can skip cached values, and none of that is fixable by configuration. If a legal or business rule says invoice numbers must be consecutive with no holes, an identity column cannot satisfy it.
The usual fix is a separate counter row that you update inside the same transaction as the invoice insert:
CREATE TABLE invoice_counter (
year integer PRIMARY KEY,
last_number integer NOT NULL
);
INSERT INTO invoice_counter (year, last_number) VALUES (2026, 0);
BEGIN;
UPDATE invoice_counter
SET last_number = last_number + 1
WHERE year = 2026
RETURNING last_number;
-- use the returned number in the invoice INSERT, then:
COMMIT;If the transaction rolls back, the counter update rolls back too, so no number is lost. The price is serialization. The UPDATE locks the row until commit, so concurrent invoice transactions queue behind each other. That is acceptable for invoices and unacceptable for page views.
Keep the identity column as the primary key and store the invoice number in its own UNIQUE column. Then the technical key can have gaps and the business number cannot.
Problem 4: the data already has a good key
A surrogate key is not always needed. Some tables have a stable, short, unique identifier that people already use:
CREATE TABLE countries (
code char(2) PRIMARY KEY,
name text NOT NULL
);Here the ISO country code is readable in every row that references it, and it never changes in practice. A surrogate key would only force an extra join to find out what 7 means.
Natural keys go wrong when the value can change or is not truly unique. Email addresses, phone numbers, names and product titles all change, and updating a primary key means updating every referencing row. If the value might change, use a surrogate key for the primary key and put a UNIQUE constraint on the natural value.
Composite keys are another option. A link table such as (student_id, course_id) can use both columns as its primary key, with no separate ID at all.
Choosing
Use these criteria in order:
- Does a stable natural key already exist? Use it.
- Must IDs be created outside a single database? Use a UUID, preferably time-ordered on large tables.
- Is the ID visible to outsiders? Add a public UUID next to an identity key.
- Otherwise, use
bigint GENERATED ALWAYS AS IDENTITY.
Common mistakes
- Switching a whole schema to random UUIDs "for scalability" when a single database handles the load, then paying for larger indexes with no benefit.
- Using an identity column as a business counter and then finding gaps in the audit.
- Exposing the identity value and relying on obscurity instead of authorization checks.
- Storing UUIDs as
text. Theuuidtype takes 16 bytes. The text form takes 36 characters plus overhead and compares more slowly.
Exercise
An orders table uses id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY. The business now requires customer-facing order numbers that are consecutive within each year, and the public API must not let anyone guess other orders' addresses. What would you add, and what does each addition solve?
Show answer
Add a public_id uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE column and use it in the API, which prevents guessing other orders' addresses. Add a counter table keyed by year, updated in the same transaction as the order insert, and store its value in a separate UNIQUE order number column, which gives consecutive numbers because a rollback undoes the counter update. Keep the identity column as the primary key for joins and foreign keys.
Exercise
Why can a table with random version 4 UUID primary keys become slower to insert into than the same table with identity keys once it grows beyond memory, and which UUID type reduces the problem?
Show answer
Random values land on arbitrary leaf pages of the primary key index. That causes more page splits, more cache misses, and more WAL from full page writes. A time-ordered UUID (version 7) starts with a timestamp, so new values go to the right edge of the index like sequence values do.