# UUIDv7 vs bigint vs UUIDv4 primary keys in Postgres 17: we measured the difference

Index size, page splits, WAL volume and insert cost for bigint identity, random UUIDv4 and time-ordered UUIDv7 primary keys, measured on PostgreSQL 17.11 with 5 million rows. Includes a UUIDv7 function for Postgres 17 that builds an index as compact as Postgres 18's built-in, and why the simple millisecond version doesn't in bulk loads.

**"Should my primary key be a `bigint` or a UUID?" has been argued for as long as Postgres has had a `uuid` type, and Postgres 18's new `uuidv7()` restarted the argument. We stopped arguing and measured it. On PostgreSQL 17.11, the version Relyt One runs, we loaded 5 million rows into four otherwise identical tables keyed by a `bigint` identity column, a random version 4 UUID, and two version 7 UUID functions written for 17. Then we measured index size, page splits, WAL and the cost of inserting into a table that already holds the data. The short answer: a random UUIDv4 key made inserts into a large table write 8 to 9 times as much WAL as an ordered key, and a time-ordered UUIDv7 removes almost all of that. What's left is the size bill for a 16-byte key. One surprise: a simple millisecond-precision UUIDv7 function, including the one in our own earlier post, builds an index as bloated as UUIDv4's when you bulk-load. Everything below is reproducible with the SQL in this post.**

## The short version

| Primary key                  | Primary key index, 5M rows | Average leaf page fill | WAL to insert 100k rows into the full table | Full-page images in that insert | WAL per single-row insert transaction |
| ---------------------------- | -------------------------- | ---------------------- | ------------------------------------------- | ------------------------------- | ------------------------------------- |
| `bigint` identity            | 107 MB                     | 90%                    | 16.5 MB                                     | 5                               | 214 B                                 |
| UUIDv4 (`gen_random_uuid()`) | 195–198 MB                 | 68–70%                 | 152 MB                                      | about 24,500                    | 452–757 B                             |
| UUIDv7, millisecond only     | 190–197 MB                 | 69–71%                 | 18.1–18.4 MB                                | 5                               | 228 B                                 |
| UUIDv7, sub-millisecond      | 150 MB                     | 90%                    | 17.9 MB                                     | 5                               | 228 B                                 |

- **UUIDv4 is the expensive one.** Its inserts land on random index pages, so a big table touches far more pages per insert. After every checkpoint each touched page costs an image of the whole page (up to 8 KB) in the WAL.
- **UUIDv7 fixes the write pattern**, but how much depends on how it's generated. A millisecond-only function puts the IDs generated in the same millisecond in random order. Bulk loads generate a hundred or more per millisecond, so the index ends up with the same page splits and fill as UUIDv4. Filling the 12 spare bits with a sub-millisecond fraction, as Postgres 18 does, fixes that.
- **`bigint` is still the smallest and cheapest**: a 16-byte key makes each table row 8 bytes wider and each primary key index entry about 40% larger.

## How we tested

Everything ran in a throwaway Docker container (`postgres:17.11-alpine`) on an Apple M1 Pro laptop with 4 CPUs and 8 GB given to Docker. We didn't change any settings: `shared_buffers` is the default 128 MB and `max_wal_size` is 1 GB, so the tables and indexes are larger than the buffer cache. We ran the whole benchmark three times in fresh containers. Sizes, WAL and full-page image counts came out nearly identical every time (the one exception is UUIDv4's WAL in the single-row test, explained below), and the tables show the range. Elapsed times varied by up to about 4× between runs because the laptop was busy with other work, so we only quote them as ranges and ratios. Sizes are in the units Postgres reports (1 MB = 1,048,576 bytes).

The four tables differ only in the primary key:

```sql
CREATE EXTENSION IF NOT EXISTS pgstattuple;  -- for pgstatindex()

CREATE TABLE t_bigint (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  created_at timestamptz NOT NULL DEFAULT now(),
  payload    text NOT NULL
);
CREATE TABLE t_uuidv4 (
  id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  created_at timestamptz NOT NULL DEFAULT now(),
  payload    text NOT NULL
);
CREATE TABLE t_uuidv7 (
  id         uuid PRIMARY KEY DEFAULT public.uuidv7(),
  created_at timestamptz NOT NULL DEFAULT now(),
  payload    text NOT NULL
);
CREATE TABLE t_uuidv7_sub (
  id         uuid PRIMARY KEY DEFAULT public.uuidv7_sub(),
  created_at timestamptz NOT NULL DEFAULT now(),
  payload    text NOT NULL
);
```

`gen_random_uuid()` is built in and returns a random version 4 UUID. Postgres 17 has no `uuidv7()`, so `public.uuidv7()` is the millisecond-precision SQL function from our post on [running Postgres 18 schemas on Postgres 17](/blog/postgres-18-features-on-17). `public.uuidv7_sub()` is a sub-millisecond version; its code is in the section "A UUIDv7 function for Postgres 17 that keeps the index compact" below. Create the two functions before the tables that use them.

Each table got the same 5 million rows in one statement, starting from a fresh checkpoint so WAL is comparable:

```sql
CHECKPOINT;
SELECT pg_stat_reset_shared('wal');
SELECT pg_current_wal_lsn() AS lsn0 \gset
INSERT INTO t_uuidv4 (payload)
SELECT md5(g::text) FROM generate_series(1, 5000000) AS g;
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'lsn0')) AS wal,
       (SELECT wal_fpi FROM pg_stat_wal) AS full_page_images;
```

Then we vacuumed and read the sizes and the shape of each primary key index:

```sql
VACUUM ANALYZE t_bigint, t_uuidv4, t_uuidv7, t_uuidv7_sub;
SELECT c.relname AS tbl,
       pg_size_pretty(pg_table_size(c.oid))           AS table_size,
       pg_size_pretty(pg_relation_size(i.indexrelid)) AS pk_index_size,
       s.avg_leaf_density,
       s.leaf_fragmentation
FROM pg_class c
JOIN pg_index i ON i.indrelid = c.oid AND i.indisprimary
CROSS JOIN LATERAL pgstatindex(i.indexrelid::regclass) s
WHERE c.relname IN ('t_bigint', 't_uuidv4', 't_uuidv7', 't_uuidv7_sub')
ORDER BY c.relname;
```

## Result 1: a 16-byte key costs 8 bytes a row and 40% more index

```text
     tbl      | table_size | pk_index_size | avg_leaf_density | leaf_fragmentation
--------------+------------+---------------+------------------+--------------------
 t_bigint     | 403 MB     | 107 MB        |            90.08 |                  0
 t_uuidv4     | 444 MB     | 197 MB        |            68.91 |              49.79
 t_uuidv7     | 444 MB     | 196 MB        |            69.03 |              30.16
 t_uuidv7_sub | 444 MB     | 150 MB        |            90.03 |               0.01
```

A `uuid` is a 128-bit value, 16 bytes, and a `bigint` is 8. The tables differ by 41 MB, about 8.6 bytes per row, which is the extra 8 bytes of key plus rounding to whole pages.

The index grows by less than you might expect. Compare the two indexes that are both packed to 90%: 107 MB for `bigint` and 150 MB for the sub-millisecond UUIDv7, a ratio of 1.4, not 2. Each B-tree entry carries an 8-byte header (the pointer to the heap row plus a size field) and a 4-byte item pointer on the page, so an entry is about 20 bytes with a `bigint` key and 28 with a `uuid`.

The same arithmetic follows the key everywhere it's copied: every foreign key column that references it makes those rows 8 bytes wider too, and a single-column index on such a column grows by about the same 40%.

## Result 2: where inserts land decides how full the index is

The other two UUID indexes are another 30% bigger than the sub-millisecond one, at the same key size. The difference is where new keys go.

![Where new keys land in a B-tree index: ordered keys always go to the rightmost leaf page, random UUIDv4 keys go to any leaf, and millisecond-precision UUIDv7 keys go to random spots among the keys of the current millisecond](/blog/assets/d38ba9b646f8ba72.svg)

When a B-tree leaf page is full, Postgres splits it. The documentation for `fillfactor` describes the special case: leaf pages are filled to the fillfactor (90 by default for B-trees) "during initial index builds, and also when extending the index at the right (adding new largest key values)". If each new key is larger than every existing key, Postgres keeps splitting the rightmost page at the 90% mark and the pages behind it stay 90% full. That's what `bigint` gives you, and `leaf_fragmentation` stays at 0.

A random key lands in the middle of some page. When that page fills, it splits roughly in half, and the two halves fill up again slowly as more random keys arrive. Averaged over the whole index you get the 68–70% fill we measured for UUIDv4. Half of the leaf pages are also out of physical order (`leaf_fragmentation` near 50), which makes range scans read pages out of order.

The millisecond-only UUIDv7 surprised us. Its timestamp prefix is ordered, but the 74 bits after it are random. Our bulk load inserted roughly 100 to 150 rows per millisecond, so within each millisecond the keys arrived in random order, and the rightmost pages of the index got the same random splits. The leaf fill came out at 69–71%, no better than UUIDv4. The only things it saved were the physical order of most pages (fragmentation 27–30 instead of 50) and, as the next result shows, the write cost.

Postgres 18's built-in `uuidv7()` doesn't have this problem. We loaded the same 5 million rows on Postgres 18.1 with it and got a 150 MB index at 89.99% leaf fill, the same as our sub-millisecond function on 17.

## Result 3: inserting into a big table is where UUIDv4 hurts

A one-off bulk load is not your normal workload. Inserting into a table that already holds the data is. With each table at 5 million rows, we took a checkpoint and inserted another 100,000 rows:

```sql
CHECKPOINT;
EXPLAIN (ANALYZE, BUFFERS, WAL, COSTS OFF, TIMING OFF)
INSERT INTO t_uuidv4 (payload)
SELECT md5(g::text) FROM generate_series(1, 100000) AS g;
```

```text
 Insert on t_uuidv4 (actual rows=0 loops=1)
   Buffers: shared hit=356042 read=47411 dirtied=49144 written=32578, temp read=171 written=171
   WAL: records=200569 fpi=24726 bytes=159566807
```

| Primary key             | WAL          | Full-page images | Pages dirtied | Time (3 runs) |
| ----------------------- | ------------ | ---------------- | ------------- | ------------- |
| `bigint`                | 16.5 MB      | 5                | 1,314         | 0.34–1.44 s   |
| UUIDv4                  | 152 MB       | 24,283–24,726    | 49,144        | 2.5–9.9 s     |
| UUIDv7, millisecond     | 18.1–18.4 MB | 5                | 1,641         | 0.43–1.09 s   |
| UUIDv7, sub-millisecond | 17.9 MB      | 5                | 1,531         | 0.46–0.86 s   |

(Pages dirtied are from the first run.) The ordered keys touch the last few pages of the index over and over. The random keys are spread over the whole index: about 24,500 full-page images means about that many different pages were modified, close to every one of the roughly 25,000 leaf pages in a 197 MB index. The `read=47411` means many of them weren't in the buffer cache and had to be fetched. And because this is the first change to each page since the checkpoint, Postgres writes the whole page to WAL. The `full_page_writes` documentation explains why: the server "writes the entire content of each disk page to WAL during the first modification of that page after a checkpoint", so a page that is only half written during a crash can still be restored. Those page images, about 5.7 KB each on average here, make up most of the 152 MB.

UUIDv4 wrote 9.2 times the WAL of `bigint` for the same rows, and took 7 to 11 times as long in each of our runs. WAL is not just disk: every byte also goes to your replicas, your backups and your point-in-time recovery history.

The sub-millisecond UUIDv7 wrote 8% more WAL than `bigint`, which is the wider key, and the millisecond version wrote 10–11% more. For this kind of insert the two UUIDv7 functions are close: random order within a millisecond still only touches the last few pages of the index, so it costs page splits but not page images.

## Result 4: single-row inserts

Most applications insert one row per transaction. We ran `pgbench` for 60 seconds per table with 4 clients, each transaction inserting one row:

```sql
INSERT INTO :tbl (payload) VALUES (md5(random()::text));
```

Transactions per second were too noisy on a shared laptop to compare (the same table varied by more than 2× between runs), so here is WAL per transaction instead:

| Primary key             | Run 1 | Run 2 | Run 3 |
| ----------------------- | ----- | ----- | ----- |
| `bigint`                | 214 B | 214 B | 214 B |
| UUIDv4                  | 542 B | 757 B | 452 B |
| UUIDv7, millisecond     | 228 B | 228 B | 228 B |
| UUIDv7, sub-millisecond | 228 B | 228 B | 228 B |

The ordered keys write the same amount every time; the extra 14 bytes over `bigint` are the wider key in the row and in the index entry. UUIDv4 writes 2 to 3.5 times as much, and the amount changes from run to run because it depends on how many index pages are touched for the first time since the last checkpoint. At this rate (roughly 5,000 to 17,000 inserts per second across four sessions, depending on the run) the millisecond-only UUIDv7 writes exactly as much WAL per transaction as the sub-millisecond one.

## The bulk load itself

For completeness, loading the 5 million rows took 18–21 s for `bigint`, 42–71 s for UUIDv4, 35–47 s for the millisecond UUIDv7 and 39–52 s for the sub-millisecond one. Part of the UUID cost is the generators themselves. In one measurement, producing 5 million values with nothing else took 5.1 s with `gen_random_uuid()`, 13.8 s with the SQL `uuidv7()` and 18.7 s with the PL/pgSQL `uuidv7_sub()`, against 0.9 s for `generate_series` alone. A few microseconds per row doesn't matter for single-row inserts, but in a bulk load it's a large part of the gap. If you load data in bulk, consider generating the IDs in your application.

The bulk load WAL followed the same pattern as Result 3: 829 MB for `bigint`, 1,043–1,046 MB for UUIDv4 with about 14,000 full-page images, and 896–923 MB for the two UUIDv7 versions.

## A UUIDv7 function for Postgres 17 that keeps the index compact

RFC 9562 lays out UUIDv7 as a 48-bit Unix timestamp in milliseconds, 4 version bits, 12 bits called `rand_a`, 2 variant bits and 62 random bits. Its section 6.2 allows "additional clock precision available on the system to substitute for up to 12 random bits" right after the timestamp. Postgres 18's `uuidv7()` does exactly that: its source stores 1/4096 fractions of a millisecond in `rand_a`. This function does the same on 17:

```sql
-- UUIDv7 with a 12-bit sub-millisecond fraction in rand_a (RFC 9562 section 6.2, method 3),
-- the same layout Postgres 18's built-in uuidv7() uses
CREATE FUNCTION public.uuidv7_sub() RETURNS uuid
LANGUAGE plpgsql VOLATILE
AS $$
DECLARE
  us bigint := (extract(epoch FROM clock_timestamp()) * 1000000)::bigint;
BEGIN
  RETURN encode(
    overlay(uuid_send(gen_random_uuid())
            PLACING int8send(
                      ((us / 1000) << 16)             -- 48-bit Unix time in ms
                      | (7 << 12)                     -- version 7
                      | ((us % 1000) * 4096 / 1000))  -- 12-bit fraction of the ms
            FROM 1 FOR 8),
    'hex')::uuid;
END
$$;
```

It takes a random v4 UUID, which already has random bits and the RFC variant, and overwrites the first 8 bytes with the timestamp, the version and the fraction. We checked 10,000 values generated in one statement: all had version 7 and the RFC 9562 variant, and none was smaller than the one before it.

Two things it does not do:

- **It isn't strictly monotonic.** `clock_timestamp()` has microsecond resolution, so two IDs generated in the same microsecond in one session compare in random order. Postgres 18's built-in guarantees increasing values within a session by stepping the timestamp forward when the clock hasn't moved. For index fill this doesn't matter, as the 90% above shows. If you need strict order, use a sequence or 18.
- **IDs from different sessions aren't ordered either.** That's true of every UUIDv7 generator, and of `bigint` identity across sessions too: values are handed out in order but committed in any order.

We wrote it in PL/pgSQL because the timestamp has to be read once and used three times, which needs a variable.

## So which one should you use?

| Situation                                                                                                          | Use                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| IDs are created by the database and only used inside your system                                                   | `bigint GENERATED ALWAYS AS IDENTITY`: smallest, cheapest, and you can read it                                                                                                                                                 |
| IDs are created outside the database (clients, offline devices, several services) or merged from several databases | UUIDv7, sub-millisecond: `uuidv7()` on 18, the function above on 17, or a UUIDv7 library in your application that orders IDs within a millisecond (a sub-millisecond fraction or a counter, as RFC 9562 section 6.2 describes) |
| IDs appear in URLs and must not reveal how many rows you have                                                      | UUIDv7, or `bigint` inside plus a separate public ID                                                                                                                                                                           |
| IDs must not reveal when a row was created                                                                         | UUIDv4, and accept the write cost; or keep a `bigint` key plus a UUIDv4 column for lookups (its unique index still has the random-insert cost, but foreign keys and joins use the small key)                                   |

UUIDv7 puts the creation time in the ID, readable by anyone with the ID. RFC 9562 calls that "a very small attack surface" and recommends UUIDv4 for any UUID used in a security operation. Treat a v7 ID as public metadata about the row.

If you already have UUIDv4 keys, think twice before converting them. Both are the `uuid` type, so there's no type change, but replacing existing IDs means updating every row and every foreign key that points at it. Changing only the default is much cheaper: it doesn't touch existing rows.

```sql
SET lock_timeout = '2s';  -- SET DEFAULT still takes a brief ACCESS EXCLUSIVE lock
ALTER TABLE t_uuidv4 ALTER COLUMN id SET DEFAULT public.uuidv7_sub();
RESET lock_timeout;
REINDEX INDEX CONCURRENTLY t_uuidv4_pkey;  -- optional: repack the old half-full pages
```

Don't expect a compact index afterwards, though. New UUIDv7 values start with the current timestamp, which in our test was smaller than 99.4% of the existing random keys. So the new keys don't go to the right edge of the index. They go into a narrow band inside it, onto pages that also hold larger v4 keys. Those aren't the rightmost page, so Postgres splits them in half, and the left halves never get another key. We tried it with 1 million UUIDv4 rows, reindexed to 30 MB at 90% fill, then added 1 million rows with the new default. The index grew to 84 MB at 64% fill, while the same 1 million UUIDv7 rows in a table of their own take 30 MB. The write savings do carry over: inserting another 100,000 rows wrote 19.2 MB of WAL with 7 full-page images, against 47.4 MB and 3,856 with explicit `gen_random_uuid()` values.

The `REINDEX` repacks what's there: on our UUIDv4 table (5.1 million rows by then) it took the primary key from 196 MB at 69% leaf fill to 153 MB at 90%. It's a one-off; new keys keep landing inside the index afterwards. `REINDEX ... CONCURRENTLY` builds a new copy of the index without blocking writes, at the cost of a longer run and room on disk for the new copy while it runs. If it fails partway, it leaves an invalid index behind that you need to drop.

## Try it on a branch

Relyt One runs PostgreSQL 17, so `uuidv7()` isn't built in and the choice above is yours to make. A branch starts from its parent at a point in time and shares its pages copy-on-write, so you can create one, switch a table's default to `public.uuidv7_sub()`, replay a day of inserts and compare WAL and index size against the parent before you change anything in production. Leaf fill and fragmentation come from the `pgstattuple` extension; where it isn't installed, `pg_relation_size()` on the index and the WAL numbers tell most of the story. The `\gset` line is a `psql` command, and `pgbench` ships with Postgres.

[Start for free](/auth/signin?ref=blog-postgres-uuidv7-vs-bigint-primary-key)
