Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CQRS command validation that requires a DB call

In CQRS, What is the best way to validate commands that require DB call? For example, I have Order aggregate that is validating a command say CommitOrder and I don't want to accept this command unless there is enough stock. In this case, how can command handler check if I have stock of the order items or no? Can I query the read side from the write one?

Note: I'm using akka for implementation

like image 844
Mutaz Avatar asked Mar 11 '23 04:03

Mutaz


1 Answers

If an aggregate needs to query the read model to perform rule validation, then the usual way to do that is via a domain service -- you pass to the service an interface that specifies the contract of the query, the implementation of that contract runs the query.

But you need to stay aware of the fact that the answer you get from running the query is old; data stored in another aggregate cannot be assumed to be "up to date".

You should also double check your requirements; in many domains, it desirable to accept orders even when the inventory is not currently available. After all, the order is an opportunity to add business value; you don't want to veto that over a concern that isn't relevant. This is especially true when the business already understands how to mitigate an "out of stock" exception.

Remember, the data from the other aggregates is stale -- it's entirely possible that another part of the system is currently updating the stock levels so that you could accept the order.

If you can't relax the requirements to commit orders when stock is not available, and if the error rate from using the stale query data is unacceptably high, then you need to redesign your aggregates so that the current stock level is in the same consistency boundary as the order commit.

like image 90
VoiceOfUnreason Avatar answered Apr 01 '23 04:04

VoiceOfUnreason