'DDD - Can we update a value with incremental database feature in the save repository method to avoid concurrency?
Hi everyone,
I don't see why when we are talking about concurrency in DDD with aggregates, we don't force it with the incremental database feature (when we can).
Imagine I have to deal with a quantity of concert ticket (number) in an entity Concert. The invariant here is: the quantity can't be lower than 0 (logic).
async execute(command: BookConcertCommand): Promise<any> {
const concert = await this.concertRepository.findById(command.concertId);
if (!concert) {
return;
}
concert.ticketQuantity -= 1;
await this.concertRepository.save(concert);
}
If two users buy a ticket in the same, there will maybe be a concurrency problem.
Why the advices are:
- Optmistic concurrency
- Pessimistic concurrency
- Eventual consistency ...
While with just this in the save:
update concerts set ticketQuantity = ticketQuantity - 1
And also, Why we can't force invariant inside this save with a WHERE clause like: WHERE ticketQuantity > 0 ?
Solution 1:[1]
Something I think when talking about DDD is the difference in analyzing the domain using DDD tools (BCs, aggregates, etc...) and implementation of a domain model.
Usually saying DDD imply both the things.
The approach you describe is against a domain model, as your are making the invariants part of the SQL logic, rather then the domain model (think of it as a model in the sense of a math model).
The approach you propose needs two different "save" methods for saying buying a ticket vs change the event name.
Usually I have heard this kind of pattern referred to as a Transactional Script approach, that is kind of the opposite of what DDD is.
DDD comes in help when it is not so easy to map these logics inside the SQL queries.
Still, nobody prohibits to study the business in a DDD way (event storming?) and then implement it as a transactional script
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
