Why I reach for a UUID v4 instead of an auto-increment ID
Auto-increment primary keys are fine until they aren't. The moment you have two services writing to the same logical dataset, a sharded table, an offline client that creates rows before it syncs, or a public URL you'd ra
Auto-increment primary keys are fine until they aren't. The moment you have two services writing to the same logical dataset, a sharded table, an offline client that creates rows before it syncs, or a public URL you'd rather not have /orders/1, /orders/2 leaking your volume — the sequential integer starts to hurt.
That's the case for UUID v4.
What a v4 actually is
A UUID v4 is 128 bits, of which 122 are random (the rest are fixed version/variant bits). You get a value like:
f47ac10b-58cc-4372-a567-0e02b2c3d479
The useful property: you can generate one anywhere — on the client, in a worker, in three services at once — without coordinating with a central sequence, and the chance of a collision is negligible for any realistic volume. No round-trip to the database to ask "what's the next number?"
Where it earns its keep
- Client-generated IDs: a mobile app can create a record offline, assign the UUID itself, and sync later with no renumbering.
- Distributed writes: merge data from several sources without PK clashes.
-
Opaque public identifiers:
/invoice/f47ac10b-…doesn't reveal how many invoices exist, unlike/invoice/4471. - Idempotency keys: send one with a request so a retry doesn't double-charge.
The honest trade-offs
I'm not going to pretend UUIDs are free:
- They're bigger (16 bytes vs 4–8 for an int), which matters at index scale.
- Random v4s scatter across a B-tree index, hurting insert locality — if that's your bottleneck, look at UUID v7 (time-ordered) or keep ints internally and expose UUIDs externally.
- They're not secrets — unguessable isn't the same as authenticated. Don't use a UUID as a bearer token.
Grabbing one quickly
When I just need a handful for seed data, a config, or a test fixture, I use Toolonium's UUID generator — it produces v4 UUIDs in the browser, nothing sent to a server, no install. For bulk generation at runtime you'd obviously use your language's native library (crypto.randomUUID() in modern JS, uuid in Python, etc.), but for a quick one-off it saves opening a REPL.
Takeaway
Reach for UUID v4 when IDs must be created without central coordination or must not leak counts. Know the index cost, and consider v7 if insert ordering matters. Need one right now? Generate it here.
Teams that went UUID-only on primary keys: did the index trade-off ever bite you in production?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.