Wednesday, October 30, 2013

Imagine a world where the past is all and only truth

Palais_de_la_Decouverte_Tyrannosaurus_rex_p1050042 Your computer system must be full of structured and relational databases. You might take regular backup of them if you don’t want to loose any information. Despite all those precautions you loose all in-between state of your information.

If all you care about is the final state it’s not a big deal but there are good chances that you have to answer some questions like:

  • How much time passed between the first item was put in the shopping cart and the completion of the transaction
  • How many times an item was removed from a shopping cart
  • What was the state the purchase order before the crash

If you didn’t implement some ways to trace those events you won’t have any answer to give. Even if you find a way to do it, you will only get information from the moment you put it in place.

I suggest you a new approach to never have to answer “it’s imposible” to your boss when he asks you that kind of question: CQRS and Event Sourcing. The power of this duo comes manly from Event Sourcing. You remember everything that you learned about side effects and why you should do everything possible to avoid them. Here those effects are the only important things. In that kind of system we do not keep data for say, we keep the effect of an action that we call passed events. For example, if we execute the following command:

var command = new AddItemToCart(cartId, itemId);

The system will produce the following event:

var @event = new ItemAdded(cartId, itemId);

The strength of the system comes when we delete items. We are able to trace those delete as events too:

var command = new RemoveItemFromCart(cartId, cartItemIndex);

Will produce:

var @event = new ItemRemoved(cartId, cartItemIndex);

In this system, all event derived from a base event:

public class EventBase
 public Guid Id { get; set; }
 public int Sequence { get; set; }
 public DateTime TimeStamp { get; set; }

A framework class ensure that every events get its date and sequence properties set.

In such system, only events are valuable. They reflect what really happened in the past. Those event will be used to build specific read models for each surrounding system the are interested. Each one will have its own small database to answer to its needs and any changes to that database will only affect this system.

Those read models are only transient representation of the system’s past.

No comments: