Search code examples
domain-driven-design

DDD - Should optimistic concurrency property (etag or timestamp) ever be a part of domain?


Theoretically speaking, if we implement optimistic concurrency on Aggregate Root level (changing entities in AR changes version on AR) and lets say we use timestamp for version property (just for simplicity) - should timeline ever be a property on AR or should it be a part of read model on one side and on other (for example, updates) be a separate argument to application service like:

[pseudo]

public class AppService{
.
.
.
   public void UpdateSomething(UpdateModelDTO model, int timestamp)
   {
      repository.GetModel(model.Identifier);
      model.UpdateSomething(model.something);
      repository.ConcurrencySafeModelUpdate(model, timestamp);
   }
}

I see pros/cons for both but wondering which is by-the-book solution?

[UPDATE]

To answer question from @guillaume31, i expect usual scenario:

  1. On read, version identifier is read and sent to client
  2. On update, client sends back the identifier and repository returns some kind of an error if version identifier is not the same.

I don't know if its important but i want to leave responsibility for creating/updating version identifiers themselves to my database system.


Solution

  • There's no by-the-book solution. Sometimes you'll already have a field in your aggregate that fits the role nicely (e.g. LastUpdatedOn), sometimes you can make it non-domain data. For performance reasons, it may be a good idea to select the field as part of the same query that fetches the aggregate though.

    Some ORMs provide facilities to detect concurrency conflicts. Some DBMS's can create and update a version column automatically for you. You should probably look for guidelines about optimistic concurrency in your specific stack.