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.

Clean up your Domain Model with Event Sourcing

Vacuum cleaner - Workers collectionI recently had a discussion with a developer who was new to Domain Driven Design, CQRS and Event Sourcing.  They were using Greg Young’s Simple CQRS Example to create there own simple app as learning exercise.

After taking a quick look at their aggregate root, one thing that immediately stood out to me was a class field that contained current state.  Why this is interesting is because this field was not in any invariant.

When I first started reading and exploring Event Sourcing, this was a big “ah ha!” moment for me.

The realization that only certain data within my domain model was really important.

We will use a simple shopping cart example.

First, lets look at what our shopping cart would look like without being event sourced. We would be probably persisting this to a relational database using an ORM or perhaps storing it in a NoSQL document store.

public class ShoppingCart
{
    public Guid Id { get; set; }
    public IList<ShoppingCartLineItem> LineItems { get; set; }
    public bool IsComplete { get; set; }
    public DateTime CompleteDate { get; set; }

    public ShoppingCart(Guid id)
    {
        Id = id;
        LineItems = new List<ShoppingCartLineItem>();
    }

    public void AddProduct(string productSku, int quantity)
    {
        if (string.IsNullOrEmpty(productSku)) throw new ArgumentException("productSku");
        if (quantity <= 0) throw new ArgumentException("quantity");

        LineItems.Add(new ShoppingCartLineItem(productSku, quantity));
    }

    public void Complete()
    {
        if (IsComplete) throw new InvalidOperationException("Already completed.");
        if (LineItems.Any() == false) throw new InvalidOperationException("Cannot complete with no products.");

        IsComplete = true;
        CompleteDate = DateTime.UtcNow;
    }
}

There are a few things to point out in the above code.

Take note of the public properties which represent our current state.  These are the pieces of data that we be persisted to data storage.

Notice we have a IList<ShoppingCartLineItem> which is our collection of products that are in our shopping cart.  The ShoppingCartLineItem class contains the Product SKU and the quantity ordered.

One invariant in this example to mention is in the Complete() method.  There must be at least one product added to the shopping cart in order to mark it as complete.

if (LineItems.Any() == false) throw new InvalidOperationException("Cannot complete with no products.");

Next, let’s implement the above with event sourcing.

public class ShoppingCart : AggregateRoot
{
    private Guid _id;
    private bool _completed;
    private DateTime _completedDate;
    private readonly IList _lineItems;
 
    public override Guid Id
    {
        get { return _id; }
    }

    private void Apply(ShoppingCartCreated e)
    {
        _id = e.Id;
    }

    private void Apply(ProductAdded e)
    {
        _lineItems.Add(new ShoppingCartLineItem(e.ProductSku, e.Quantity));
    }

    private void Apply(Completed e)
    {
        _completed = true;
        _completedDate = e.DateCompleted;
    }

    public ShoppingCart(Guid id)
    {
        _lineItems = new List();

        ApplyChange(new ShoppingCartCreated(id));
    }

    public void AddProduct(string productSku, int quantity)
    {
        if (string.IsNullOrEmpty(productSku)) throw new ArgumentException("productSku");
        if (quantity <= 0) throw new ArgumentException("quantity");

        ApplyChange(new ProductAdded(_id, productSku, quantity));
    }

    public void Complete()
    {
        if (_completed) throw new InvalidOperationException("Already completed.");
        if (_lineItems.Any() == false) throw new InvalidOperationException("Cannot complete with no products.");

        ApplyChange(new Completed(_id, DateTime.UtcNow));
    }
}

In our event sourced implementation above we still are holding current state in the same fashion as our non event sourced version.  I’ve changed them from public properties to private fields since they are not being persisted to data storage.  Instead our events raised through ApplyChange() are what are persisted to data storage.

The example above is typical of a first implementation of event sourcing.  We are taking the concept we know and use of persisting current state along with this new idea of using events as state transitions.

There is actually a lot of code that can be removed from our event sourced example above.

ShoppingCartLineItem class is no longer needed because the data it encapsulates is now encapsulated in our ProductAdded event.  So if we delete that class, then we have the issue with:

private readonly IList<ShoppingCartLineItem> _lineItems;

This private member will no longer be valid since we just deleted the ShoppingCartLineItem class.  So we can remove this private member as well.

Now let’s go back to that invariant that we have:

if (_lineItems.Any() == false) throw new InvalidOperationException("Cannot complete with no products.");

How can we maintain this invariant since we are no longer keep track of the line items?

You only need the data applicable to an invariant

Because of this, we don’t really care what products or quantities are on the shopping cart, just that there is at least one.

Any data that is not used by an invariant does not need to be in your aggregate.

private DateTime _completedDate;

We also no longer need the date the shopping cart was completed because it is not used by an invariant and it is also contained in the Completed event.

Now let’s take a look at our shopping cart with these ideas applied:

public class ShoppingCart : AggregateRoot
{
    private Guid _id;
    private bool _containsProducts;
    private bool _completed;

    public override Guid Id
    {
        get { return _id; }
    }

    private void Apply(ShoppingCartCreated e)
    {
        _id = e.Id;
    }

    private void Apply(ProductAdded e)
    {
        _containsProducts = true;
    }

    private void Apply(Completed e)
    {
        _completed = true;
    }

    public ShoppingCart(Guid id)
    {
        ApplyChange(new ShoppingCartCreated(id));
    }

    public void AddProduct(string productSku, int quantity)
    {
        if (string.IsNullOrEmpty(productSku)) throw new ArgumentException("productSku");
        if (quantity <= 0) throw new ArgumentException("quantity");

        ApplyChange(new ProductAdded(_id, productSku, quantity));
    }

    public void Complete()
    {
        if (_completed) throw new InvalidOperationException("Already completed.");
        if (_containsProducts == false) throw new InvalidOperationException("Cannot complete with no products.");

        ApplyChange(new Completed(_id, DateTime.UtcNow));
    }
}

The invariant is now based on a boolean set when a product has been added.  The aggregate does not care about what products were added or their quantity.  It doesn’t even need to have them in a collection.

With the implementation of event sourcing in our aggregate, we get a much clearer view of what data drives business logic and is important in our domain model.

Bounded Context and Subdomains

CarpetIn a previous blog, I discussed how I recently discovered through eventual consistency that I had poor business alignment.  With more thoughts and insights, I wanted to extend that post by discussion bounded contexts and how they fit within subdomains.

1 to 1?

I’ve often thought of a bounded context as being a one-to-one relationship with a subdomain.   To take that further, you may get the impression that they are indeed the same thing.  When I was first introduced to the concept many years ago, I was under the impression that they mapped directly one to one.

I’m not entirely sure why I had this perception early on.  It may be due examples or just the assumption I made.  I do not remember actually ever reading how a subdomain and a bounded context don’t map directly one to one.

Over the years I’ve realized this not to be the case, but always had a tough time giving an explanation that others could visualize.

I heard Eric Evans gave a great example that I will paraphrase, which should help you visualize the difference.

Living Room Floor

Imagine a room in your house.  It may have a closet or some different length walls which makes it not totally uniform.  Imagine there is carpet in this room.  The carpet covers every inch of the floor.  Wall to wall carpet.

This carpet represents your bounded context.

Underneath the carpet, say the cement, is your subdomain.

By Design

It just so happens that your bounded context is mapped to your subdomain exactly.  However, that is just because the bounded context (carpet) was designed that way.

A bounded context doesn’t necessarily need to cover the entire subdomain.  It only needs to cover the aspects of the subdomain which help solve the problem space.

To use the carpet analogy again, I mentioned that the room wasn’t completely uniform as maybe it had a closet in it.  The carpet doesn’t need to cover the entire floor beneath it.  There may be bare floor exposed in the closet because that portion of the subdomain doesn’t require to be modeled as it isn’t needed for problem you are trying to solve.

More Than One?

I’m still trying to determine if a subdomain can have more than one bounded context.  I do think it may be possible if you are implementing something technical apart of that subdomain.  I would love to hear others thoughts on this.

Eventual Consistency and Business Alignment

mapI 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.

Based on the above, the “preferred” flag and any business rules associated to it, most likely exists in some sort of the CRM bounded context.  However, this detail is required in the Sales bounded context in order to apply a discount if eligible.

As you can see, there is information that needs to be shared between bounded contexts.

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.

Business Alignment

There are many situations where data being eventually consistent is totally acceptable.  I’ve found in the real world we often make decisions with stale data all the time.

However, there are times where full consistency is required.  When describing the example above to the business, does the eventual consistency of the preferred flag have true business impact?  If it truly does matter and the data must be fully consistent, then you may have bad business alignment with your bounded contexts.

Re-evaluate your bounded context and the boundaries as you may have an wrong interpretation of responsibilities.

I’ve found that drawing a context map and the events which are published and subscribed with a domain expert should flush out any of these incorrect interpretations and help you re-align boundaries and responsibilities.