The Big Picture: How Drools Works
At a high level, Drools follows this sequence when processing rules:1. Inside the Rule Engine
The Drools rule engine has three key components that interact during rule processing:- Production Memory: Stores your business rules
- Working Memory: Stores your facts (data objects)
- Agenda: Determines which rules to execute and in what order
2. Pattern Matching Process
When facts are inserted into working memory, Drools needs to determine which rules should fire. This process is called pattern matching.The Rete Network Evolution: From Rete to Phreak
Drools originally used the Rete algorithm (pronounced “REE-tee” or “RAY-tay”) for pattern matching. Since Drools 6, it has been completely replaced by Phreak, an enhanced algorithm that provides:- Lazy evaluation: Rules are only evaluated when needed
- Set-oriented propagation: Better performance with large data sets
- Improved memory usage: More efficient fact storage
- Better scalability: Handles thousands of rules and facts efficiently
- Object Type Nodes: Filter facts by their class type
- Alpha Nodes: Apply single-fact constraints (e.g.,
age > 18) - Beta Nodes: Join multiple facts together (e.g.,
$a: Applicant() and $l: Loan(applicant == $a)) - Terminal Nodes: Represent rules that are ready to fire
3. From Rule Definition to Execution
Let’s walk through the lifecycle of a rule from definition to execution using a simple example:Rule Definition
1. Rule Compilation
When you define rules like the one above, Drools compiles them into a network of nodes:2. Fact Insertion
When you insert facts, they flow through this network:3. Pattern Matching and Agenda Creation
As facts flow through the network:- The
LoanApplicationfact is checked against its constraints (not approved) - The
Applicantfact is checked against its constraints (credit score > 700) - If both match, the rule is activated and placed on the agenda
4. Rule Execution
When you callfireAllRules(), Drools executes the rules on the agenda:
5. Working Memory Update
After rule execution, working memory is updated:6. Re-evaluation (if needed)
Because we usedmodify() to change the loan application, Drools automatically re-evaluates any rules that might be affected by this change.
4. The Two-Phase Execution Cycle
When you callfireAllRules(), Drools enters a two-phase execution cycle:
- Agenda Evaluation Phase: The rule engine selects rules that can be executed.
- If no more rules can be executed, the cycle ends
- If executable rules are found, they’re registered in the agenda
- Working Memory Actions Phase: The rule engine executes the consequences (actions) of activated rules.
- After all consequences are complete, or if
fireAllRules()is called again, the process returns to the agenda evaluation phase
5. Conflict Resolution
What happens when multiple rules are eligible to fire? Drools uses conflict resolution strategies to determine the execution order:Salience (Priority)
Rules with higher salience values fire before rules with lower values:Agenda Groups
Rules can be partitioned into agenda groups, and only rules in the focus group are eligible for execution:6. Stateful vs. Stateless Sessions Visualized
Stateful Session
A stateful session maintains facts across multiplefireAllRules() calls:
Stateless Session
A stateless session processes all facts in a single operation and doesn’t maintain state:execute() call is a separate, isolated operation with no shared state between calls.
7. Truth Maintenance and Logical Insertions
Drools supports automatic truth maintenance through logical insertions. When you useinsertLogical() instead of insert(), the fact is automatically retracted when the conditions that led to its insertion are no longer true.
8. Event Processing in Drools
For time-based events, Drools supports two processing modes:Cloud Mode (Default)
All events are treated as regular facts with no temporal constraints:Stream Mode
Events are processed with temporal awareness:9. Sliding Windows
In stream mode, you can define sliding windows of time or length to process only recent events:Time Window
Length Window
10. Temporal Operators
Drools supports temporal operators to define relationships between events:after/beforecoincidesduring/includesfinishes/finished bymeets/met byoverlaps/overlapped bystarts/started by
11. Property Reactivity
By default, Drools only re-evaluates rules when properties that are actually used in constraints change:age property, the rule isn’t re-evaluated because the rule doesn’t use it.
When you change status or spending, the rule is re-evaluated.
This gives you visibility into when:
- Facts are inserted, updated, or deleted
- Rules are activated or fired
- Agenda groups are pushed or popped
Logging
Configure SLF4J logging to see detailed information:13. Life Cycle of a Drools Application
Here’s the typical lifecycle of a Drools application:Summary
You’ve now seen how the Drools rule engine processes rules and facts. Understanding these internal mechanisms will help you:- Write more efficient rules: By understanding how the pattern matching works, you can structure your rules for better performance
- Troubleshoot issues: When rules don’t fire as expected, you know where to look
- Choose the right session type: Based on your use case, you can select stateful or stateless sessions
- Work with events: You can process time-based events using stream mode and sliding windows