If you are using the Business Rules Engine (BRE) as part of BizTalk or Windows Workflow Foundation and are asking yourself “Why are my rules firing in the wrong order?” you probably need a better understanding of how the BRE executes a set of rules (policy). The priority property of a rule will control the order in which the action of that rule will fire relative to the other actions in a policy. Specifically, an action of a rule with a higher priority will fire before an action of a rule with a lower priority. Notice it is the action of a rule which is affected by the priority and not the evaluation of the rule. The evaluations themselves will still occur in an arbitrary order. For example, assume three rules exist in the same policy, “Rule 1”, “Rule 2”, and “Rule 3” with their priority properties set to 3, 2, and 1 respectively. When the policy is invoked, Rule 2 may be evaluated, then rule 3, and finally rule 1. Only after evaluation of all rules will the actions of the rules fire in the order specified by the priority values. What are the practical consequences of this? A rule dependent on the action of a previous rule within the same policy won’t evaluate as expected.
There are a couple ways to overcome this problem. The first is to place rules dependent on each other in separate polices. This requires the host application to call multiple policies and to be knowledgeable about the order in which they should be called, a detail which should be abstracted from the calling process. The second technique is to use an update action to let the BRE know an object has changed its state and that any rules that had evaluated this fact need to be re-evaluated. The process look like this
- Execute all rules of a policy (these will be evaluated in an arbitrary order)
- Fire any Actions for any rules that evaluated to true (these will be fired according to the rule’s priority property)
- Check if any facts used the update method to notify the BRE that a fact changed its state.
- Re-evaluate any rules that contained updated facts
- Repeat 2-4 until no facts are updated