Postgres 18: uuidv7() and the IDs I Stopped Generating in the App
Postgres 18 ships a built-in uuidv7(), asynchronous I/O, and virtual generated columns. Why time-ordered UUIDs fix the index bloat random ones cause, and the two lines I changed.
PostgreSQL 18 came out at the end of September. The headline is a new asynchronous I/O system that speeds up sequential scans and vacuum. The change I actually made on day one was smaller: a built-in uuidv7() function.
Why random UUIDs hurt
Most of our tables use UUID primary keys. They're safe to expose in URLs, you can generate them anywhere, and merging data from two environments never collides. Until now they were almost always version 4: completely random.
Random is the problem. A B-tree index keeps keys sorted. Every new random UUID lands somewhere in the middle of the index, so inserts touch pages all over it. Pages split, the index grows larger than it needs to be, and far less of it stays in memory.
UUIDv7 puts a millisecond timestamp in the first bits and randomness in the rest. New IDs sort after old ones, so inserts go to the end of the index, like a bigserial would. You keep everything that's good about UUIDs and lose the write penalty.
The change
Before 18, getting v7 meant generating it in the app or installing an extension. Now it's a default:
create table orders (
id uuid primary key default uuidv7(),
...
);In Drizzle, defaultRandom() maps to gen_random_uuid(), which is v4. For v7, use a SQL default:
import { sql } from "drizzle-orm";
import { pgTable, uuid } from "drizzle-orm/pg-core";
export const orders = pgTable("orders", {
id: uuid("id").primaryKey().default(sql`uuidv7()`),
});That let me delete the small helper that generated IDs in the app before every insert. The database owns the ID again, and every insert path gets the same kind of key.
The trade-off to know about
A v7 UUID carries its creation time. Anyone holding the ID can read roughly when the row was created. For orders and invoices that's harmless, since the date is on the page anyway. For something where creation time is sensitive, like when an account was opened, keep v4 for the public identifier.
The other two things worth knowing
- Asynchronous I/O. Postgres 18 can issue several reads at once instead of waiting for each one. Sequential scans, bitmap heap scans, and vacuum benefit most. It's on by default (
io_method = worker), so you get it by upgrading. - Virtual generated columns. Generated columns are now virtual by default: computed when you read them, not stored on disk. Handy for things like a full name or a total that you want queryable without paying to store it. Add
STOREDif you need to index it.
None of these change how you design an app. They make the defaults better, which is the best kind of database release: upgrade, change two lines, and stop maintaining a workaround.