Entity ID – Pros and cons of different approaches

In most cases, I use UUID as an id for aggregate entity. But when it comes to big amount of entities in SQL DB it can become scalability problem to handle UUID as id. Here are some pros and cons of different approaches to entity ids.

Autoincrement Integer: DB

32-bit or 64-bit integer used as a primary key by DB.

Pros:

  • Optimal for DB optimization
  • No additional services needed to guaranteed uniqueness

Cons:

  • Insecure (can be predicted)
  • Exposed as Integer is hard coupling implementation with API clients
  • Hard to change later
  • Entity get ID after persisting to DB (so it’s impacting Events)
  • Needs additional application service if we want to have ID before an entity persisting
  • in case of MySQL you need to create row to obtain ID (no sequence like in PostgreSQL)
  • It’s related to SQL databases and not compatible with NoSQL databases

Unique Integer: Twitter ID snowflake

Pros:

  • Fits in 64-bit Integer
  • Secure (cannot be predicted)

Cons:

  • Require additional service
  • Exposed as Integer is hard coupling implementation with API clients
  • Hard to change later
  • Entity get ID after persisting to DB (so it’s impacting Events)

UUID

Pros:

  • Secure (cannot be predicted)
  • Shared as a string is open for changes later
  • Can be generated at any moment in time

Cons:

  • Can’t fit into 64-bit Integer (requires 128-bit)
  • Is not incremental (unless you will change UUID a little)
  • Is not optimal for SQL databases

Natural ID

Pros:

  • You have them in command to DDD component
  • Are easy to pass in company cause it’s related to aggregate in other domain

Cons:

  • Not optimized for DB (mostly more than one field) so needs an additional primary key in table (should not be exposed)
  • Should be unique but an event with certified ID there may be duplication
  • Many times Natural ID for some rare business reasons can be duplicated. It can be hard to discover.
  • Hard to change later if you will discover the case for duplication

Hi there 👋
It’s nice to meet you.

Sign up to join my mailing list.

I don’t spam!