I'm using event sourcing in an application and constantly find a problem for which I do not find a good solution.
In this scenario we have an application for a hair stylist. We have a
CustomerAggregate which performs all actions for a customer. But some times we need to find a range of specific customers, and for that we use projections. Let's say that we need to find all customers with red hair. For that scenario we have a projection (which is a flat database table), which may look something like this:
CustomerId | HairColor | Name
1 Red Alice
2 Blue Bob
3 Red Cecilia
The aggregate has a method called
ChangeHairColor(newColor), which will apply an event called
HairColorChanged. When the event
HairColorChanged occurs the projection is updated. This works fine. We can query the projection and find all customers with a red hair color if we for example need to make a newsletter targeting that audience.
My problem occurs when my domain logic is depending on a projection. Writing to the projection is async and occurs outside of my domain logic. Let's consider this scenario:
1. Get all customers with red hair.
2. Dye hair to blue for all those customers.
3. Get all customers with blue hair.
4. Send newsletter to all customers with blue hair telling them what a nice color they have!
When we have iterated through step 2 the update of the projection is async and may not be completed before step 3 occurs. Therefore we may not get the correct customers in step 3. We have a race condition.
How do I properly address this issue? As I understand it a projection should be separated from the domain logic. But in this case the domain logic is dependant on the projection. Should I therefore include updating the projection in my