Keep invariants with SQL in DDD
06:14 05 Jun 2026

Sometimes, to keep you invariants in valid state, you will need to do it with a SQL. For example, lets say you have an Order and a collection of OrderLines for each Order. From business experts, there is a business rule, "customers cannot have more than 3 orders in total", just for ilustration purposes, not because this rule makes sense in the real world.

Then you can think of creating a Customer aggregate and have a collection of Order entities to keep this invariant but this could be a huge aggregate because a Customer could have a huge amount of Orders. So, you could have just a number in the Customer aggregate representing the current number of orders , then, you could keep this invariant creating a method in Customer aggregate like "addOrder" that accepts the new Order to be saved and internally checks this rule but, this would be the first guardian to keep this invariant but not the most effective. It would not be the most effective because since you fetched this aggregate and the current number of orders for this customer could be 2, other user has created other order for this customer having 3 orders in total for this customer. Then our "addOrder" would validate OK but at the end saving it to the database would violate this business rule.

So, for these use cases, I think the best solution for keeping this business rule would be to create an insert SQL with a previous select or something related but what I mean is that should be a SQL to keep this business rule. Or maybe to keep this invariant, we could have a version number of the Customer table whenever something related has changed for this customer and then, although our "addOrder" method in the Customer aggregate would pass, we then could validate before insert this new order the version number in the Customer aggregate.

What do you think?

domain-driven-design policy