Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
I recently discovered through eventual consistency that my bounded contexts were not properly aligned with the business. I won’t lie, it took me quite a while to make this realization. This was most likely the case in many situations I’ve had in the past. Because of this realization, I wanted to let out some of my thoughts about eventual consistency and business alignment.Dependent Bounded Context
I’ve often encounter situations where a bounded context requires information that another bounded context is responsible for. I’d like to use a simple example I’ve heard from Udi Dahan. In the context of an Ecommerce site.- A customer can be a defined as a “preferred” customer.
- Preferred customers receive a 10% discount on all orders.
Publish / Subscribe Domain Events
One approach for decoupling your bounded context is to publish domain events from your domain model. This allows other bounded contexts to subscribe to those events and handle them accordingly. Let’s use our example above to see how this would be implemented. In our CRM bounded context, when a customer is defined as preferred in our domain model, we would publish a CustomerIsPreferred event.class CustomerIsPreferred { public Guid CustomerId { get; private set; } public DateTime Date { get; private set; } public CustomerIsPreferred(Guid customerId, DateTime date) { CustomerId = customerId; Date = date; } }In our Sales bounded context, we would subscribe to this event and update our customer model with a preferred flag. This piece of information is used as a local cache in our Sales bounded context. During our checkout process in Sales, we would then use the preferred flag on the concept of a customer in Sales to determine if they should receive a 10% discount. However, remember that this preferred flag is not owned by Sales. Because of the publish / subscribe model (assuming asynchronicity), at any given time, our preferred flag in Sales could be out of sync with current state in our CRM bounded context. Eventually consistency doesn’t mean our data is wrong, it just means it is stale.