medium.com 4 min read Original Source

After 3 Years and 200M Rows, I Finally Stopped Using UUIDs as Primary Keys

It was not that. Same query, same table, same code we had shipped three years earlier, except that it had quietly stopped being fast.

I opened the query plan expecting a fluke and instead got a wall of numbers that make any backend engineer go still.

Index Scan using orders_pkey on orders
  Buffers: shared hit=812 read=94331
  Execution Time: 3841.226 ms
Index Scan using orders_pkey on orders
  Buffers: shared hit=812 read=94331
  Execution Time: 3841.226 ms

Ninety four thousand block reads, for one row, by its primary key. I read that line three times, half convinced I had pasted the wrong output into my own terminal.

That same query used to come back in under 20 milliseconds. Now, sitting on top of 200 million rows, it took almost 4 seconds, and the only reason anyone even noticed was that a client’s dashboard froze mid demo.

My lead asked me to explain it in the next standup, and the honest answer I gave was, the primary key is a UUID, and I do not think anyone realized what that would cost us later.

If you have ever used a UUID as a primary key in Postgres or MySQL, you already sense where this is going.

If you have not yet, keep reading, because the version of your app that exists three years from now is quietly taking notes.

Why It Felt Fine For Years

When our app was small, UUIDs felt like the responsible, grown up choice. No coordination needed between services, no risk of collisions, no leaking the fact that we only had 40 users by looking at the number in the URL.

Every senior engineer I asked told me the exact same sentence, use UUIDs, they scale better.

Nobody ever told me what three years of random inserts does to an index. I am not sure most of them had actually looked.

Most Engineers Have Never Opened Their Own Index

Here is the part that might sting a little. Most people who reach for a UUID as a primary key are not doing it because they measured anything. They are doing it because a blog post, a bootcamp instructor, or a confident colleague told them it was the modern way to do things. I did the exact same thing, and I paid for it in a standup, in front of my lead, with a client’s frozen dashboard as the evidence.

A primary key is not just an identifier. It decides the physical order your rows get stored in, and that order decides how kind or cruel your database is to itself over time.

What Actually Breaks at Scale

A primary key index is a B-tree. Rows get sorted by that key inside the tree, and the database keeps them in tidy pages on disk.

When you insert with an auto increment integer, every new row lands at the end of the tree, right next to the last one. Clean, predictable, cache friendly.

A UUID v4 is random by design. Every single insert lands in a completely different spot in the tree.

Not at the end, but somewhere in the middle, scattered across pages that are not even loaded in memory. The database has to pull a random page from disk, split it if there is no room, and write it back.

Multiply that by millions of rows and your index turns into a patchwork of half empty pages.

Here is roughly what that looks like on the inside.

[501..1000] -> [1001..1500] -> [1501..2000]
full full full filling
Random UUID inserts, tree gets shredded:
[a1, f8, 22, c9] [90, b3, 1e, d4] [f0, 33, a7, 6c]
half full half full half full
^ ^ ^
new row lands here, then there, then back here” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

Sequential integer inserts, tree stays tight:

[1..500] -> [501..1000] -> [1001..1500] -> [1501..2000]
   full         full            full          filling
Random UUID inserts, tree gets shredded:
[a1, f8, 22, c9] [90, b3, 1e, d4] [f0, 33, a7, 6c]
   half full         half full        half full
        ^                 ^                ^
   new row lands here, then there, then back here
Sequential integer inserts, tree stays tight:

[1..500] -> [501..1000] -> [1001..1500] -> [1501..2000]
   full         full            full          filling
Random UUID inserts, tree gets shredded:
[a1, f8, 22, c9] [90, b3, 1e, d4] [f0, 33, a7, 6c]
   half full         half full        half full
        ^                 ^                ^
   new row lands here, then there, then back here

The left side is one continuous street. The right side is a city with no street plan, and every new building goes wherever there happens to be an empty lot.

The Table That Started It

-- what we shipped three years ago
CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    total NUMERIC(10,2),
    created_at TIMESTAMPTZ DEFAULT now()
);
-- what we shipped three years ago
CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL,
    total NUMERIC(10,2),
    created_at TIMESTAMPTZ DEFAULT now()
);

It looked fine in every code review. It passed every load test we ran, because our load tests never went past a few million rows. Nobody tests for the version of the app that exists three years from now.

The Fix We Actually Shipped

We did not throw away UUIDs, we just stopped using them as the primary key. The database now inserts sequentially using a bigint, and the UUID becomes a public facing column with its own index, used only when a client actually needs it.

-- what runs today
CREATE TABLE orders (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    public_id UUID NOT NULL DEFAULT gen_random_uuid(),
    user_id BIGINT NOT NULL,
    total NUMERIC(10,2),
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE UNIQUE INDEX orders_public_id_idx ON orders (public_id);
-- what runs today
CREATE TABLE orders (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    public_id UUID NOT NULL DEFAULT gen_random_uuid(),
    user_id BIGINT NOT NULL,
    total NUMERIC(10,2),
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE UNIQUE INDEX orders_public_id_idx ON orders (public_id);

Foreign keys everywhere in the schema shrank from 16 bytes to 8. Joins got lighter. The primary key index went back to looking like a straight line instead of a scatter plot.

For a middle ground, look into UUID v7. It keeps the random uniqueness everyone loves but sorts by timestamp first, so inserts behave almost like a normal auto increment key while still being globally unique. If I was starting a new project today, that is where I would begin.

What The Numbers Looked Like After

On a clone of the same 200 million row table, the identical query that once needed almost 4 seconds now looked like this.

Index Scan using orders_pkey on orders
  Buffers: shared hit=4 read=3
  Execution Time: 0.041 ms
Index Scan using orders_pkey on orders
  Buffers: shared hit=4 read=3
  Execution Time: 0.041 ms

Four shared buffer hits instead of ninety four thousand block reads. Index size on that table dropped by close to 40 percent, and the weekend reindex job that used to eat several hours now finishes while I am still reading my first email.

What I Would Tell Myself Three Years Ago

Random keys are not free, they are a loan against your future write performance, and the interest rate shows up the exact moment your table stops being small. UUIDs are still useful, just not as the thing your database sorts millions of rows by every single second of every single day.

If your table is under a million rows, none of this will bite you yet, and I understand why it is tempting to close this tab and move on.