Introduction
The Drools rule engine is the cornerstone of the aletyx business automation platform. It stores, processes, and evaluates data to execute the business rules or decision models that you define. Understanding how it works is essential for creating effective rule-based applications.What Is a Rule Engine?
At its simplest, a rule engine is a software component that:- Stores business rules in a central repository
- Matches incoming data against these rules
- Executes rules when their conditions are met
- Updates the system state based on rule consequences
The Basic Function of the Drools Rule Engine
The fundamental operation of the Drools rule engine involves matching incoming data (facts) to rule conditions and determining which rules to execute. This process works as follows:- Fact Insertion: When business data enters the Drools system, it’s inserted into the working memory as facts
- Pattern Matching: The Drools rule engine matches these facts against rule conditions stored in production memory
- Rule Activation: When conditions are met, rules are activated and registered in the agenda
- Execution: The Drools rule engine executes activated rules according to conflict resolution strategies
- Updates: Rule execution may modify facts, leading to further rule activations
Key Features
- Declarative Programming: Focus on “what” should happen, not “how” it should happen
- Pattern Matching: Efficiently match facts against rule conditions
- Inference: Derive new facts from existing data
- Truth Maintenance: Automatically maintain consistency in the knowledge base
- Conflict Resolution: Determine execution order when multiple rules are activated
Core Components
The Drools rule engine consists of several key components that work together:
Production Memory
The production memory is where your business rules are stored within the Drools rule engine. When you define rules in DRL files, decision tables, or other formats, they are compiled and stored in this memory area.Working Memory
Working memory (sometimes called the fact base) is where the data that your rules operate on is stored. When you insert data (facts) into the Drools rule engine, these facts go into the working memory.Agenda
The agenda is where activated rules are registered and sorted before execution. When rule conditions are met, the rule becomes activated and is placed on the agenda. The agenda determines the execution order of activated rules based on various conflict resolution strategies.Pattern Matching
The pattern matching process is what connects facts in working memory with rules in production memory. The Drools rule engine uses a sophisticated algorithm called Rete (or its more advanced versions like PHREAK) to efficiently match facts against rule conditions. The following diagram illustrates these basic components of the Drools rule engine:Basic Workflow
The following steps outline the basic workflow of the Drools rule engine:- Rule Definition: Define your business rules using DRL, decision tables, or other formats
- Knowledge Base Creation: Compile your rules into a knowledge base
- Session Creation: Create a session from the knowledge base
- Fact Insertion: Insert facts (data) into the session
- Rule Evaluation: The rule engine evaluates facts against rule conditions
- Rule Execution: Activated rules are executed based on priorities and conflict resolution
- Result Collection: Retrieve the results of rule execution
KIE Sessions
KIE (Knowledge Is Everything) sessions are the primary interface between your application and the Drools rule engine. A KIE session stores and executes runtime data and is created from a KIE base.KIE Base vs. KIE Session
KIE Base: A repository that contains all rules, processes, functions, and data models. It does not contain any runtime data. KIE Session: A runtime environment that allows you to interact with the Drools rule engine by inserting facts, executing rules, and querying results. You can configure a KIE base and KIE session in the KIE module descriptor file (kmodule.xml):
- name: A unique identifier for the KIE base
- packages: Comma-separated list of packages to include in the KIE base
- includes: Other KIE bases to include
- default: Whether this is the default KIE base
- equalsBehavior: Identity or equality (discussed in the Fact Equality Modes section)
- eventProcessingMode: Cloud or stream (for event processing)
- declarativeAgenda: Enabled or disabled (for declarative agenda control)
- name: A unique identifier for the KIE session
- type: Stateful or stateless
- default: Whether this is the default KIE session
- clockType: Realtime or pseudo (for time-based rules)
- beliefSystem: Simple, jtms, or defeasible (truth maintenance strategies)
Types of KIE Sessions
Drools supports two types of KIE sessions, each designed for different use cases:Stateless KIE Sessions
A stateless KIE session is designed for single-shot rule executions. It does not maintain state between invocations - facts and rules are evaluated, actions are executed, and the session is disposed of. Stateless sessions are ideal for:- Validation (e.g., validating a mortgage application)
- Calculation (e.g., computing premiums or discounts)
- Routing and filtering (e.g., categorizing customer requests)
execute() call acts as a combination method that:
- Instantiates the KieSession object
- Adds all the user data
- Executes user commands
- Calls
fireAllRules() - Calls
dispose()
fireAllRules() and dispose().
Working with Complex Data in Stateless Sessions
For more complex use cases, stateless sessions can handle collections of objects or commands:Stateful KIE Sessions
A stateful KIE session maintains state between invocations. Facts inserted into a stateful session remain there until explicitly removed, and you can iteratively add, modify, or remove facts over time. Stateful sessions are ideal for:- Monitoring (e.g., stock market monitoring)
- Diagnostics (e.g., fault detection systems)
- Logistics (e.g., package tracking)
- Complex event processing (e.g., fraud detection)
- Use
modifyblocks (rather than just changing object properties) so the rule engine can track changes - Use
update()when directly changing objects outside of rules - Use
delete()when facts are no longer needed
When to Use Which Session Type
Working with Facts
Facts are the data objects that you insert into the Drools rule engine. They represent the state of your system and are matched against rule conditions.Inserting Facts
Facts are inserted into the rule engine using theinsert() method in stateful sessions or passed directly to the execute() method in stateless sessions:
One concept that has changed a lot with the introduction of RuleUnits is that insert still works with regards to the working memory of Drools, if you need to utilize data from the working memory (e.g. to pass back in a query) then instead of the usual
insert(new Charge($order.getItemsCount() * 7.50)); that you would use, it would become charges.add(new Charge($order.getItemsCount() * 7.50)); where charges is the RuleUnit associated with the Charge object.Modifying Facts
In stateful sessions, you can modify facts using theupdate() method:
modify block:
modify is critical because it notifies the rule engine that the fact has changed, allowing it to reconsider rules that might be affected by the change.
Retracting Facts
To remove facts from working memory in stateful sessions, use thedelete() method:
Global Variables
Global variables provide a way to make external objects available to rules. Unlike facts, globals are not used for pattern matching in rule conditions. They primarily serve as a means to provide services or data to the rules that don’t need to be asserted as facts.Types of Global Variables
Globals can be used for various purposes:- Services: Providing access to services like logging, databases, or external systems
- Shared Data: Making reference data available to all rules
- Collectors: Collecting output from rule execution
Declaring and Setting Globals
You can declare globals in your DRL files:Using Globals in Rules
Globals can be accessed directly in rule consequences:Globals in Stateless KIE Sessions
TheStatelessKieSession object supports global variables (globals) that you can configure to be resolved as session-scoped globals, delegate globals, or execution-scoped globals.
Session-Scoped Globals
For session-scoped globals, you can use the methodgetGlobals() to return a Globals instance that provides access to the KIE session globals. These globals are used for all execution calls. Use caution with mutable globals because execution calls can be executing simultaneously in different threads.
Delegate Globals
For delegate globals, you can assign a value to a global (withsetGlobal(String, Object)) so that the value is stored in an internal collection that maps identifiers to values. Identifiers in this internal collection have priority over any supplied delegate. If an identifier cannot be found in this internal collection, the delegate global (if any) is used.
Execution-Scoped Globals
For execution-scoped globals, you can use theCommand object to set a global that is passed to the CommandExecutor interface for execution-specific global resolution.
Out Identifiers for Exporting Data
TheCommandExecutor interface also enables you to export data using out identifiers for globals, inserted facts, and query results:
Inference and Truth Maintenance
Inference is the process of deriving new facts from existing data. Truth maintenance is how the Drools rule engine ensures that inferred facts remain valid as the knowledge base changes.The Power of Inference
Inference allows you to write rules that build on each other. Early rules can establish facts that later rules use, creating complex reasoning chains. Example of inference:Government ID Example: Knowledge Decoupling
Let’s examine a more substantial business example to illustrate how inference helps with modular rule design. Consider a government ID department responsible for issuing ID cards when citizens become adults. They might have a monolithic decision table that includes logic like this: RuleTable ID Card
This approach has several problems:
- The ID department doesn’t set policy on who qualifies as an adult - that’s done at a central government level
- If the central government changes the age from 18 to 21, it requires coordination across departments
- The ID department’s rules contain information it shouldn’t need to know or manage
ID Department Rules:
RuleTable ID Card
This improved design:
- Properly separates concerns by department
- Encapsulates the “age >= 18” logic behind a semantic abstraction (IsAdult)
- Allows the central government to change the adult age policy without requiring changes to the ID department’s rules
- Decouple knowledge responsibilities: Each department or domain expert should maintain only their own rules
- Encapsulate knowledge: Hide implementation details behind logical facts
- Provide semantic abstractions: Use meaningful fact types (like IsAdult) rather than raw conditions
Logical Insertions
Logical insertions provide automatic truth maintenance. Facts inserted logically are automatically retracted when the conditions that led to their insertion are no longer true.IsChild fact would be automatically retracted, which would then cause the ChildBusPass fact to be retracted as well.
When you use logical insertions, you can build a chain of dependencies that maintain themselves automatically as facts change. For example, we can extend our bus pass example:
ChildBusPass is automatically retracted, and they still have an old child bus pass that hasn’t been returned.
For logical insertions to work correctly, your fact objects must properly implement the
equals() and hashCode() methods.Benefits of Truth Maintenance
- Consistency: The knowledge base remains consistent as facts change
- Modularity: Rules can be broken down into smaller, more maintainable pieces
- Reduced Complexity: You don’t need to write rules to explicitly retract facts
Stated vs. Logical Insertions
Fact Equality Modes
The Drools rule engine supports two equality modes that determine how it stores and compares facts:Identity Mode (Default)
In identity mode, facts are compared using the== operator. Two facts are considered the same only if they are the exact same object in memory.
Equality Mode
In equality mode, facts are compared using theequals() method. Two facts are considered the same if they are equal according to their equals() implementation.
Setting the Equality Mode
You can set the equality mode in several ways:- System property:
- Programmatically:
- In kmodule.xml:
Advanced Execution Control
Understanding how rules are evaluated and executed in the Drools rule engine is crucial for building efficient rule-based applications. This section explores the advanced concepts of execution control, including rule execution modes, fact propagation modes, and the Phreak algorithm.Two-Phase Execution Process
After the first call offireAllRules() in your application, the Drools rule engine cycles repeatedly through two phases:
- Agenda Evaluation Phase: The Drools rule engine selects rules that can be executed. If no executable rules exist, the execution cycle ends. If an executable rule is found, the engine registers the match in the agenda and moves to the next phase.
- Working Memory Actions Phase: The engine performs the rule consequence actions (the
thenportion of each rule) for all activated rules previously registered in the agenda. After all consequence actions are complete orfireAllRules()is called again, the engine returns to the agenda evaluation phase.
Rule Execution Modes
The Drools rule engine supports two execution modes that determine how and when rules are executed:Passive Mode (Default)
In passive mode, the Drools rule engine evaluates rules only when your application explicitly callsfireAllRules().
This mode is best for:
- Applications that require direct control over rule evaluation
- Complex event processing (CEP) applications using the pseudo clock implementation
Active Mode
In active mode, initiated by callingfireUntilHalt(), the Drools rule engine evaluates rules continuously until your application explicitly calls halt().
This mode is best for:
- Applications that delegate control of rule evaluation to the engine
- Complex event processing applications using real-time clock implementation
- Applications using active queries
Thread Safety in Active Mode
For thread safety in active mode, the Drools rule engine provides asubmit() method to group and perform operations atomically:
Fact Propagation Modes
The Drools rule engine supports different fact propagation modes that determine how inserted facts progress through the engine network:Lazy Propagation (Default)
Facts are propagated in batch collections at rule execution time, not in real time as they are individually inserted. The order of propagation may differ from the insertion order.Immediate Propagation
Facts are propagated immediately in the order they are inserted. This mode can be necessary for certain rules that depend on insertion order.Eager Propagation
Facts are propagated lazily (in batch collections) but before rule execution. The Drools rule engine uses this propagation behavior for rules with theno-loop or lock-on-active attribute.
To specify a propagation mode for a specific rule, use the @Propagation(<type>) tag:
Agenda Filters
AnAgendaFilter allows you to control which rules are allowed to fire during agenda evaluation:
Activation Groups
An activation group (also called a match group) is a set of rules bound together by the sameactivation-group rule attribute. In this group, only one rule can be executed - after conditions are met for a rule to execute, all other pending rule executions from that group are removed from the agenda.
Phreak Rule Algorithm
The Drools rule engine uses the Phreak algorithm for rule evaluation. Phreak offers several advantages over the traditional Rete algorithm:- Lazy Evaluation: Unlike Rete’s eager evaluation, Phreak deliberately delays pattern matching until rule execution is required
- Goal-Oriented: Focuses on executing the most promising rules first
- Stack-Based: Uses a stack-based rather than recursion-based approach, allowing rule evaluation to be paused and resumed
- Three-Layer Memory System: Uses node, segment, and rule memory types for more contextual understanding
- Set-Oriented Processing: Processes batches of data rather than individual tuples
How Phreak Works
- When the Drools rule engine starts, all rules are considered unlinked from pattern-matching data
- Insert, update, and delete actions are queued
- When all required input values for a rule are populated, the rule is linked to relevant data
- A goal is created for the linked rule and placed in a priority queue
- Only the rule for which the goal was created is evaluated, delaying other potential evaluations
- For the evaluating rule, the engine processes all queued actions at each node, propagating results to child nodes
Memory Management in Phreak
Phreak uses a three-layered memory system:- Node Memory: Stores data at individual nodes in the network
- Segment Memory: Groups related nodes that share common rule dependencies
- Rule Memory: Maintains context for specific rules
Rule Base Configuration
The Drools rule engine provides configuration options to tune execution behavior:Consequence Exception Handler
You can specify a custom exception handler for rule consequences:Parallel Execution
To improve performance, you can enable parallel rule evaluation and execution:sequential: Evaluates and executes all rules sequentially (default)parallel_evaluation: Evaluates rules in parallel but executes consequences sequentiallyfully_parallel: Evaluates and executes everything in parallel
In fully parallel mode, rules that use queries, salience, or agenda groups are not supported. The engine will emit a warning and switch back to single-threaded evaluation if these elements are present.
Sequential Mode
Sequential mode makes the Drools rule engine evaluate rules one time in the order they are listed, ignoring any changes in working memory:Controlling Rule Execution Order
Salience
Salience is a rule attribute that determines execution priority. Rules with higher salience are executed before rules with lower salience. For performance reasons, salience is typically not recommended to use and should be used as a last effort to control the rule order if required.Agenda Groups
Agenda groups allow you to partition rules into groups and focus execution on specific groups:auto-focus attribute to automatically give focus to a group when one of its rules is activated:
Rule Flow Groups
Rule flow groups associate rules with a specific part of a process flow:KIE Session Pools
For applications with high-throughput requirements, creating and disposing of KIE sessions can become a performance bottleneck. KIE session pools provide a solution by reusing sessions.Creating and Using a KIE Session Pool
Benefits of Session Pools
- Performance: Reduces the overhead of session creation
- Resource Efficiency: Reuses sessions instead of creating new ones
- Scalability: Dynamically grows as needed
When to Use Session Pools
- High-volume rule processing scenarios
- Applications with rapid session creation/disposal cycles
- When performance optimization is critical
Lifecycle of KIE Sessions and Pools
When working with a high turnover of KIE sessions, the creation and disposal process can become a bottleneck. Here’s how a KIE session pool manages this lifecycle:- Pool Creation: A pool is initialized with a specified number of KIE sessions
- Session Acquisition: A session is obtained from the pool
- Session Use: The session is used normally for rule execution
- Session Return: Instead of being destroyed, the session is reset and returned to the pool
- Pool Shutdown: When finished with the pool, shut it down to release resources
Performance Tuning Considerations
The following key concepts and practices can help you optimize Drools rule engine performance.Sequential Mode for Improved Performance
When using stateless KIE sessions that don’t require important rule engine updates, consider using sequential mode for better performance. In sequential mode, the Drools rule engine evaluates rules one time in the order they are listed, ignoring any changes in working memory.Optimizing Event Listeners
Event listeners can impact performance if they perform complex operations. Use these best practices:- Keep operations simple: Use event listeners for simple operations like debug logging and property settings
- Limit the number of listeners: Too many listeners can slow down rule execution
- Remove listeners when done: Clean up listeners after you’re done with a session
Lambda Externalization for Executable Model
To optimize memory consumption during runtime, enable lambda externalization:Alpha Node Range Index Threshold
Configure the threshold of the alpha node range index using thedrools.alphaNodeRangeIndexThreshold system property. The default value is 9, but you can adjust it based on your rules:
Join Node Range Index for Large Fact Sets
When your application inserts a large number of facts (e.g., 256*16 combinations), enable the join node range index:LambdaIntrospector Cache Size
Configure the size ofLambdaIntrospector.methodFingerprintsMap cache for executable model builds:
Parallel Execution for Multi-Core Systems
On systems with multiple processor cores, enable parallel execution to utilize the available hardware:Efficient Rule Design
- Avoid cross-product patterns: Patterns that generate a large number of combinations can slow down the engine
- Use property reactivity: Let the engine react only to relevant property changes
- Optimize pattern order: Put the most restrictive patterns first in your rule conditions
- Use indexes effectively: Mark frequently used constraints with the
@indexedannotation
Memory Management
- Dispose of sessions: Always dispose of stateful sessions when done
- Use stateless sessions: For simple, independent rule evaluations
- Manage fact lifecycle: For event processing, set appropriate expiration policies for events
- Use sliding windows: For temporal reasoning, use sliding windows to limit the facts being processed
Example: Loan Approval System
Let’s examine a complete example of a loan approval system that illustrates many of the concepts we’ve covered.Domain Model
Rules
Application Code
- Fact insertion and updating
- Rule activation and execution based on business conditions
- Pattern matching across multiple facts
- Inference (credit ratings derived from credit scores)
- Truth maintenance (risk assessments update when credit ratings change)
- Rule prioritization with salience
- Working memory updates with the modify block
Conclusion
The Drools rule engine is a powerful tool for implementing complex business logic in a declarative way. By understanding its core components and mechanisms, you can leverage its full potential for your business automation needs. In this guide, we’ve covered:- The basic components of the Drools rule engine
- Types of KIE sessions and when to use each
- Working with facts in the rule engine
- Inference and truth maintenance
- Controlling rule execution
- Optimizing performance with session pools
- Best practices for rule design