Skip to content

Coordinating stuff that happens over time

mookid8000 edited this page Jun 12, 2012 · 24 revisions

Sometimes, when building systems, stuff happens over time that's implicit and hard to understand, unless someone's being nice and draws it for you on a piece of paper using some sort of state machine notation.

One example can be some kind of financial trading company. When a new customer is registered, we need to collect some legal information regarding that customer, and we need to do that in several systems. You can probably imagine how this could be drawn as a state machine or a sequence diagram on a piece of paper, but when the time comes to implement these things, at least in my experience, then this stuff will be fragmented across the entire system...

Why is it that we're often content with having these state machines as implicit stuff in our code, when object-oriented programming is all about coding stuff that's present in the real world? Wouldn't it be nice of someone came up with a model for stuff that evolves over time, that would make modeling these things easy?

Enter the saga!

A saga is an instance of a state machine whose transitions are triggered by messages. In order to implement something like that, three things must be in place:

  • a representation of the saga's state (in Rebus that's just a class that implements ISagaData), stored somewhere persistent
  • a model of the transitions and actions that constitute the saga (in Rebus that's a special message handler that's derived off of Saga<TSagaData>)
  • a mapping of message fields to saga data fields, that allows for existing saga instances to be found for each message that is handled (or if no instance is found, maybe it's allowed for a message to initiate a new saga?)

"Saga"?

The term is stolen from a paper on long-lived transactions in a database context, and it is not entirely accurate according to the original definition because the Rebus/NServiceBus implementations don't require you to implement any kind of rollback/compensating actions. It's probably just called "Saga" because it sounds cool, way better than "Workflow", "Process Manager", etc.

Clone this wiki locally