Video in progress

Strong Junior 🧩 Microservices

How do you generate record IDs in microservices: auto-increment, UUID or something else?

Auto-increment works inside a service, but if the ID leaves the service or is needed before the DB write, I choose a UUID, preferably the time-ordered UUIDv7. It's generated without the DB and doesn't wreck the index the way a random UUID does.

📖 Answer

Auto-increment (IDENTITY) is convenient for a single DB, but it has drawbacks in microservices:

  • The ID is known only after the INSERT. Preparing an outbox event or an idempotency key in advance gets harder.
  • IDs are sequential: after /orders/1001 it's easy to guess that /orders/1002 exists, and the business volume becomes visible too.
  • You get collisions when you merge the data of two services or split a DB.

A UUID solves these: it's generated anywhere, without the DB. But a plain UUID.randomUUID() (v4) is random: every write goes to a different place in the B-tree index, inserts slow down on a big table and the index bloats.

UUIDv7 has a millisecond timestamp at the front, so new IDs land at the end of the index:

// the JDK doesn't have a v7 generator yet, so use a library (java-uuid-generator)
UUID id = Generators.timeBasedEpochGenerator().generate();

Since PostgreSQL 18 there's also a uuidv7() function in the DB itself.

Another useful habit: separate the internal technical ID from the number shown to people (ORD-2026-000123). People read a number out over the phone, not a UUID.