Home

Rule Engine Drools

Li

Li Wei

December 11, 20249 min read

Title: Drools Rule Engine

Overview

Rule Engine

Drools is an open‑source rule engine provided by the JBoss community, built on Java. It frees complex and ever‑changing business rules from hard‑coded logic, storing them as rule scripts in files or other storage media (e.g., a database). This means rule changes can take effect in a live environment without modifying code or restarting the server.

Official site: Drools source code download: https://github.com/kiegroup/drools

Rule Engine, formally called a Business Rule Management System (BRMS), separates the decision‑making part of an application from the rest of the code and lets users or developers write business decisions (rules) with predefined semantic modules. These rules can be configured and managed as needed.

Note that a rule engine is not a single technology framework; it refers to a class of systems—business rule management systems. Popular products include Drools, VisualRules, iLog, etc.

A rule engine receives data input, interprets business rules, and makes decisions based on those rules. In other words, it is an input‑output platform.

After introducing a rule engine, business rules no longer reside as program code; they are stored in a rule repository, completely independent of the application. Business users can manage rules just like data—query, add, update, count, submit, etc. The rules are loaded into the engine for the application to invoke.

Benefits of Using a Rule Engine

  • Separates business rules from system code, enabling centralized rule management
  • Allows rule expansion and maintenance without restarting services
  • Supports dynamic rule changes for rapid response to requirement shifts
  • Because the engine only cares about rules, business analysts can also edit and maintain them
  • Reduces the cost and risk of hard‑coded rules
  • Provides rule‑editing tools that simplify the implementation of complex logic

Typical Use Cases

Systems with complex business rules that change frequently are good candidates, such as:

  • Risk control systems – risk loans, risk assessment
  • Anti‑fraud projects – bank loans, credit verification
  • Decision platforms – financial calculations
  • Promotion platforms – discounts, bundle offers

How to Get Started

  • Create a Spring Boot project

  • Add the required dependencies:

    • Add a Drools configuration class:

    • This defines a KieContainer Spring Bean, where KieContainer builds the rule engine by loading rule files from the /resources folder of the application.

  • Create a KieFileSystem instance, configure the engine, and load the DRL file from the application’s resources directory.

  • Use a KieBuilder instance to build the drools module. You can obtain a KieBuilder instance via the KieService singleton.

  • Finally, use KieService to create a KieContainer and set it as spring bean.

  • Define the necessary entity classes, e.g., an Order entity:

    • Create rule files, e.g., resources/rules/order.drl for order‑point rules:

    • Write tests:

Execution Principle

Engine Components

The Drools rule engine consists of three parts:

  • Working Memory

  • Rule Base

  • Inference Engine, which includes:

    • Pattern Matcher – determines which rules match
    • Agenda
    • Execution Engine

(Diagram omitted)

Key Concepts

  • Working Memory: The engine pulls data from here and matches it against the patterns defined in rule files. Your application only needs to insert facts into the Working Memory.
  • Fact: In Drools, a plain JavaBean inserted into Working Memory becomes a Fact. Facts are the bridge between the application and the rule engine.
  • Rule Base: All rules defined in rule files are loaded into this repository.
  • Pattern Matcher: Compares every rule in the Rule Base with the Facts in Working Memory; matching rules are activated and placed on the Agenda.
  • Agenda: Holds activated rules after pattern matching.
  • Execution Engine: Fires the rules stored in the Agenda.

Execution Flow

  1. Insert initial facts into Working Memory.
  2. Pattern Matcher compares rules with facts.
  3. If multiple rules are eligible, a conflict set is created.
  4. Resolve conflicts and order the activated rules onto the Agenda.
  5. Execute the Agenda’s rules. Repeat steps 2‑5 until the Agenda is empty.

About KIE

The core Drools APIs and their relationships are shown in the diagram below:

(Diagram omitted)

Most class names start with Kie. KIE stands for Knowledge Is Everything, the umbrella term for JBoss’s suite of projects. Its main modules include OptaPlanner, Drools, UberFire, and jBPM.

Drools is one component of the KIE ecosystem and also includes Drools‑WB, a visual rule editor.

Basic Syntax

File Structure

When using Drools, writing rule files is essential. Rule files typically have the .drl extension.

DRL stands for Drools Rule Language. The file contains the actual rule definitions.

A complete rule file consists of:

Keyword Description
package Logical package name; queries or functions in the same package can call each other
import Imports classes or static methods
global Declares global variables
function Defines custom functions
query Declares queries
rule … end The rule body

Drools also supports rule definitions in Excel files.

Rule Structure

The rule body is the core part where business logic is evaluated and actions are taken.

Structure:

  • rule – starts a rule; the parameter is the rule’s unique name
  • attributes – optional parameters between rule and when
  • when – introduces the condition (LHS)
  • LHS (Left Hand Side) – the condition part; consists of zero or more pattern elements. If LHS is empty, it is treated as always true.
  • then – introduces the consequence (RHS)
  • RHS (Right Hand Side) – the action part
  • end – terminates the rule

Comments in .drl files follow Java conventions: single‑line comments start with //, multi‑line comments start with /* `*` and end with `*` */.

Pattern Matching

The matcher compares every rule in the Rule Base with Facts in Working Memory, so you define patterns in the LHS. A pattern’s syntax is:

**绑定变量名:Object** (field constraints).

Variable names can be omitted; when used, they are usually prefixed with $. If a variable is bound, you can refer to it in the RHS. Field constraints consist of zero or more expressions that evaluate to true or false.

Example:

  • The Working Memory must contain a Fact of type Order – type constraint
  • The Fact’s amount must be ≥ 100 – attribute constraint
  • The Fact’s amount must be < 500 – attribute constraint

All conditions must be satisfied for the rule to fire.

Comparison Operators

Drools supports the following comparison operators (identical to Java for the first six):

Symbol Meaning
> greater than
>= greater than or equal
(other operators omitted for brevity)

Built‑in Methods

The RHS mainly manipulates Facts in Working Memory—insert, delete, or modify them—to control rule execution. After such operations, the engine re‑evaluates relevant rules, possibly activating previously unmatched ones.

update

Updates a Fact in Working Memory and triggers re‑matching (avoid infinite loops).

  • Purpose: update modifies an existing object in Working Memory. When the object’s state changes, update ensures the engine re‑evaluates related rules.
  • When to use: When you change an object’s properties and want those changes to cause rule re‑evaluation.
  • Example: (omitted)
  • Infinite‑loop risk: If a rule modifies an object and calls update, and the modification satisfies the rule’s own condition, the rule may fire repeatedly. Use no-loop or design logic to prevent repeated activation.
insert

Adds a new object to Working Memory; the engine immediately starts matching rules against it.

  • Purpose: insert inserts a new object.
  • When to use: When you create a new object and want it evaluated right away.
  • Example: (omitted)
retract

Removes an object completely from Working Memory; the engine stops matching it.

  • Purpose: retract deletes a Fact.
  • When to use: When you want to stop rule evaluation for a particular object or clean up the memory under certain conditions.
  • Example: (omitted)

Rule Attributes

Drools provides various rule attributes (partial list):

Attribute Description
salience Execution priority (Integer). Higher numbers run first. Default order is top‑to‑bottom.
dialect Language used in the rule (java or mvel).
enabled Whether the rule is active.
date-effective When the rule becomes effective.
date-expires When the rule expires.
activation-group Only one rule in a group can fire.
agenda-group Only rules in the focused group can fire.
timer Schedules rule activation.
auto-focus Automatically focuses the agenda group (usually used with agenda-group).
no-loop Prevents a rule from re‑activating itself after an update. Boolean, default false.

Advanced Syntax

Global Variables

The global keyword declares variables that the application can access inside rule files, providing data or services to the rules.

Syntax: **global 对象类型 对象名称**;

When using globals, keep in mind:

  • If the global is a wrapper type, changes made inside a rule affect only that rule’s copy; other rules see the original value.
  • If the global is a collection or JavaBean, modifications inside a rule are visible to Java code and all other rules.
Example Code
  • Order entity:
  • Integral (points) entity:
  • Rule file:
  • Test case:

Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.

Keep reading

More related articles from DriftSeas.