0

Let's assume we have an application written using DDD approach. Also, entities and aggregate roots are stored in the database using an incremental identity integer as primary key. As entities are identified by an unique Id, the Id must be know at the creation.

So in this case, how the id must be generated? I see different possibilities:

  1. The entity is created with a null or default id value and the id will be created only when the entity persisted in the db

  2. Querying each time the DB to get the next Id to be used

  3. Using another type of Id (ex:GUID) that could be instantiated without db round trips.

All of these possibilities have their own drawback. In the first one the entity can't be identified during the running of the app and having dummy or null Ids doesn't seems a good practice. The second it's heavy and that force us to pass the service calling the next id generation around the domain. The third one could works, but that mean changing all our db primary keys, which we may have chosen for good reasons.

Maybe, my first assumption is wrong and Entities or Aggregate root should never be created on the fly and always provided by repositories? Thanks

Fede
  • 804
  • 1
  • 10
  • 21

1 Answers1

1

How to generate entities and aggregate roots Id in DDD

In chapter 5 of Implementing Domain Driven Design, Vaughn Vernon describes four different approaches to "identity generation and assignment".

If one of your concerns is avoid the creation of duplicate entities with different identifiers, then you are probably going to need identity generation that happens prior to persistence.

You're probably going to have that concern eventually if creation messages are coming to you over an unreliable network. On an unreliable network "exactly once message delivery and processing" is a polite fiction; instead, you get either "at most once processing" or "at least once processing".

The failure mode of "at most once" is that data gets lost forever. Easy, but unsatisfactory for a wide variety of problems.

The failure mode of "at least once" is that clients will deliberately send multiple copies of messages that have been processed when a processing acknowledgement is lost.

In a log, where the business impact of a duplicate is negligible, you just append the new message to the end and don't worry about it.

But with business critical systems, we usually care quite a bit about having the right quantity (either zero or one) of each entity represented in our persistence store. So you need to have some mechanism in place to recognize duplicates.

And that, as a rule, means that identity generation and assignment happens earlier in the flow.

Note that we might still want to have a database generated "surrogate key" for each row, as a form of metadata (much like having columns to track when the row was created or last updated).

VoiceOfUnreason
  • 52,766
  • 5
  • 49
  • 91