# How do you generate unique IDs across many servers?

By Vishal Kumar · Published 2026-11-07 · Updated 2026-11-13
Source: https://fungyaan.com/p/unique-ids-at-scale
Tags: system-design, ids, uuid, postgres, interview

**Short answer:** the verdict, which the measurements below will earn:
- **One database:** a **sequence** (`bigint GENERATED ALWAYS AS IDENTITY`). Smallest, fastest, ordered. Use it unless you have a reason not to.
- **IDs created outside the database**, merged from many sources, or that mustn't reveal how many orders you have: **UUIDv7**. Time-ordered, so indexes stay compact, and no coordination needed.
- **Avoid random UUIDv4 as a primary key in B-tree databases** at scale: inserts land on random index pages. In my measurement, v4 inserts took about 60% longer than v7 (33.7 s against 21.2 s) once the index outgrew memory.
- **Snowflake-style 64-bit IDs** (timestamp + machine ID + counter) when you need sortable IDs in 8 bytes and can assign machine IDs reliably.

Here's the case. A table that inserted happily for months starts to slow down, its primary-key index has swollen far beyond what the data seems to need, and nothing about the queries has changed. The suspect nobody looks at is the ID. An ID looks like the most boring column in the table, and yet it shapes how your index grows, what your URLs leak and whether two servers can ever collide. It's a small decision with more depth than it looks, so let's measure it.

> **Case file**
>
> | | |
> |---|---|
> | **The case** | Inserts slow down and the primary-key index swells, with no change to the queries |
> | **Suspects** | Database sequence, UUIDv4, UUIDv7, Snowflake-style IDs |
> | **Culprit** | Random UUIDv4 keys: every insert lands on a random index page |
> | **The fix** | bigint identity in one database, UUIDv7 when IDs are made elsewhere |
> | **Evidence** | 5 million inserts on PostgreSQL 17, database-tradeoffs-lab/16-id-generation |

## The suspects

| | Database sequence | UUIDv4 | UUIDv7 | Snowflake-style |
|---|---|---|---|---|
| **Size** | 8 bytes | 16 bytes | 16 bytes | 8 bytes |
| **Ordered by time** | Roughly (by when the value was allocated; commits can land out of order) | No | Yes (milliseconds) | Yes |
| **Needs coordination** | The database | None | None | Unique machine IDs |
| **Generated by clients/offline** | No | Yes | Yes | Yes, with a machine ID |
| **Reveals volume** | Yes (order #10,482 tells competitors your volume) | No | Reveals creation time | Reveals creation time and machine |
| **Index behaviour** | Appends to the right edge | Random page per insert | Appends near the right edge | Appends near the right edge |
| **Standard** | - | RFC 9562 | RFC 9562 (built in from PostgreSQL 18) | Twitter's design, many variants |

The layouts below are worth a moment. Both UUIDv7 and Twitter's Snowflake design share the same clever move: put the time at the front, so that sorting the number almost sorts by when it was made. Hold on to that, because it's the key to the whole case.

```mermaid
flowchart LR
  subgraph UUIDv7 128 bits
    T[48 bits: Unix ms] --> V[4: version 7] --> F[12: sub-ms fraction or counter] --> VA[2: variant] --> R[62: random]
  end
  subgraph Snowflake 64 bits
    S0[1: sign] --> ST[41: ms since custom epoch] --> SM[10: machine ID] --> SC[12: per-ms counter]
  end
```

## The evidence: 5 million inserts on PostgreSQL

PostgreSQL 17, a small buffer cache (128 MB) so the index outgrows memory as it would in production. Keys generated first, then inserted in batches of 50,000:

| Key | Insert time | Rows/s | WAL written | Primary key index | Leaf density |
|---|---:|---:|---:|---:|---:|
| bigint | 24.4 s | 204,918 | 1,081 MB | **107 MB** | 90.1% |
| UUIDv4 | **33.7 s** | 148,368 | 1,235 MB | **196 MB** | **69.3%** |
| UUIDv7 | 21.2 s | 235,849 | 1,166 MB | 150 MB | 90.0% |

```mermaid
xychart-beta
  title "Primary key index size after 5 million inserts (MB)"
  x-axis ["bigint", "UUIDv4", "UUIDv7"]
  y-axis "MB"
  bar [107 , 196 , 150]
```

What the clues say:
- **UUIDv4:** every insert goes to a random leaf page. Pages split in the middle and end up about two-thirds full, so the index is 30% bigger than v7's. Once it no longer fits in memory, inserts must read random pages back from disk, which is where the extra time goes; the gap grows with the table. There's our culprit.
- **UUIDv7:** new keys are always near the end, like a sequence, so pages fill to 90% and stay in cache. It was as fast as bigint (the difference between them is within run-to-run noise); the index is bigger only because each key is 16 bytes instead of 8.
- **A false lead I followed myself:** my first UUIDv7 function used random bits after the millisecond. Thousands of rows inserted in the same millisecond then arrived in random order, and the index fragmented exactly like v4. Real implementations (PostgreSQL 18's `uuidv7()`, most libraries) put a sub-millisecond fraction or counter there for that reason. Check yours. The mistake was a useful one, because it settles the case: the ordering, not the format, keeps the index healthy.

Reproduce: [database-tradeoffs-lab/16-id-generation](https://github.com/the-vishal-kumar/database-tradeoffs-lab/tree/main/16-id-generation).

## Matching the solution to the situation

| Situation | What I'd use |
|---|---|
| **A typical SaaS on one PostgreSQL** | `bigint` identity internally; expose a UUIDv7 or an opaque code in URLs if volumes are sensitive |
| **Mobile or offline clients creating records** | UUIDv7 generated on the device, so records have IDs before they sync |
| **Event IDs across many services** | UUIDv7: unique without coordination and sortable by time in logs |
| **Order numbers customers read aloud** | A separate human-friendly code (short, no ambiguous characters, check digit), not the primary key |
| **Very high-volume, 8-byte IDs** (sharded stores) | Snowflake-style, with machine IDs from configuration or a lease, and a plan for clock skew |
| **DynamoDB / Cassandra partition keys** | Random-looking keys spread load; time-ordered keys can create hot partitions there, the opposite of B-trees ([B-tree vs LSM post](/p/btree-vs-lsm)) |

## Loose ends that can trip you

- **Clocks go backwards** (NTP corrections): Snowflake generators must wait or refuse; UUIDv7 generators should keep a monotonic counter.
- **IDs as secrets:** neither v4 nor v7 is an access control. Anyone with a link still needs a permission check.
- **Sorting by v7 ≠ sorting by event time** across machines with skewed clocks; it's close, not exact.
- **Migrating key types** on a big table is a [live migration](/p/zero-downtime-migrations): plan it, don't do it on a whim.

> **Remember this**
> - Put the time at the front so new keys append near the end of the index.
> - Random UUIDv4 keys fragment a B-tree once it outgrows memory.
> - Check that your UUIDv7 keeps order within a millisecond.

## Case closed: what I'd do by default

1. **bigint identity** inside a single database.
2. **UUIDv7** when IDs are created outside the database or must not reveal volume.
3. **Never UUIDv4 as a clustered or B-tree primary key** on large, write-heavy tables.
4. **Separate public, human-friendly codes** from primary keys.

It's a satisfying thing to see 48 bits of timestamp and a little care about ordering turn into a smaller, faster index. The best IDs are the ones nobody ever has to think about again, and a bit of thought up front is what earns that.

*Measured Nov 2026 on PostgreSQL 17.11 in Docker on a laptop (Intel i7-8550U), one run; sizes and densities repeat, timings vary by a few seconds. Code and full results: [database-tradeoffs-lab](https://github.com/the-vishal-kumar/database-tradeoffs-lab/tree/main/16-id-generation).*
