Optimize Dropwizard: Turbocharge with Drools & Singleton Rulebase
Optimize Dropwizard: Turbocharge with Drools & Singleton Rulebase

Executing Sequential Agenda Groups in Drools with Singleton Rule Loading in Dropwizard

Boost your Dropwizard app efficiency using Drools with sequential agenda groups and optimized singleton rulebase loading.7 min


Integrating Drools into your Dropwizard application can significantly boost the efficiency of your business rules management. Drools is a robust, open-source rules engine powered by Java, allowing developers to define complex logic that business users can easily manage. Using Dropwizard to deploy Drools rules ensures your application remains lightweight, maintainable, and scalable.

When handling complex business logic, you often face scenarios where rules span multiple stages or categories. Drools offers a practical solution for this scenario through the use of agenda groups. Agenda groups allow you to execute sets of rules in a specified sequence, ensuring logic flows logically and predictably.

If you’re integrating Drools with Dropwizard, you might want specific agenda groups executed sequentially—such as running four agenda groups one after another. For example, imagine a loan-approval scenario. You might first run initial application validation, then credit scoring, risk analysis, and finally decision-making. Executing these four agenda groups sequentially ensures accurate evaluations at each step.

To execute agenda groups sequentially, Drools provides methods such as getAgenda().getAgendaGroup("your-group").setFocus(). Setting focus on an agenda group ensures that the rules defined in this group execute first. Once this group’s execution is completed or stopped based on defined criteria, the next agenda group takes over.

It’s also crucial that Drools stops rule execution within an agenda group once a specific condition is met or a match is found. Continuing with our earlier loan example—if a rule validation group finds a critical mismatch in documents, there’s no reason to continue evaluating further validations in that group. Therefore, the rule that finds the issue should be able to stop any further rule processing.

How does Drools handle rule execution within an agenda group?

Drools follows a simple principle: Once you’ve set the focus to an agenda group, all active rules from that agenda group are evaluated. To explicitly stop further execution when a rule successfully matches, you typically use control statements such as drools.halt() or manage facts that remove conditions leading to subsequent rule matches.

Here is a concise example rule to illustrate this behavior clearly:

rule "Validate Documents - critical mismatch"
agenda-group "document-validation"
when
    $application : LoanApplication(documentsValid == false)
then
    System.out.println("Critical document mismatch found, stopping further validation.");
    drools.halt();
end

Here, if a critical mismatch is found, Drools halts any further rule evaluation, and execution ends for the current group. After completing a group’s execution, Drools resumes with the next specified agenda group.

The Benefits of Singleton Rule Loading

Another optimization you should consider when integrating Drools into Dropwizard is singleton rule loading—loading the rulebase just once per application environment. Rather than reloading Drools rules on every request, singleton loading initializes the rules once on application startup. Subsequent requests use this single rule instance, significantly improving performance and reducing overhead.

Singleton rule loading can be achieved using Dropwizard’s efficient YAML configuration. Simply place a reference to your rules file (.drl) in the Dropwizard YAML configuration file. When the application starts, you load this rules file once, storing the pre-built KnowledgeBase in memory as a Singleton.

Here’s how your YAML configuration might look:

drools:
  rulesFile: "rules/ruleFile.drl"

Drools’ environment-specific configurations can greatly simplify deployment across environments—development, testing, and production. The Drools KnowledgeBase, built from your singleton-loaded rules, remains accessible and reusable throughout your application’s lifecycle.

Step-by-step Guide to Implement Sequential Agenda Groups with Singleton Rule Loading in Dropwizard

1. Integrate Drools into Dropwizard

In Dropwizard, integrating Drools effectively starts with adding Drools dependencies to your project. Using Maven, you might add:

<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-core</artifactId>
    <version>7.73.0.Final</version>
</dependency>
<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-api</artifactId>
    <version>7.73.0.Final</version>
</dependency>

2. Setting Environment-Specific YAML Configuration

As mentioned earlier, create an entry pointing to your rules file within the Dropwizard config YAML, specifically tailored for each environment (dev, test, prod):

rulesConfiguration:
  rulesFilePath: "rules/myAppRules.drl"

3. Loading and Executing Rules in Drools (Singleton Initialization)

Next, create a singleton class to load your Drools KnowledgeBase once upon application startup:

public class DroolsLoader {
    private static DroolsLoader instance;
    private KieContainer kieContainer;

    private DroolsLoader(String rulesPath){
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newClassPathResource(rulesPath));
        kieServices.newKieBuilder(kieFileSystem).buildAll();
        kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
    }

    public static synchronized DroolsLoader getInstance(String rulesPath){
        if(instance == null){
            instance = new DroolsLoader(rulesPath);
        }
        return instance;
    }

    public KieSession getKieSession(){
        return kieContainer.newKieSession();
    }
}

4. Executing Agenda Groups in Order

Within your Java code, clearly specify the sequence of agenda groups you’d like to execute via setFocus() method calls:

KieSession kieSession = DroolsLoader.getInstance("rules/myAppRules.drl").getKieSession();
kieSession.getAgenda().getAgendaGroup("document-validation").setFocus();
kieSession.getAgenda().getAgendaGroup("credit-scoring").setFocus();
kieSession.getAgenda().getAgendaGroup("risk-analysis").setFocus();
kieSession.getAgenda().getAgendaGroup("approval-decision").setFocus();

kieSession.insert(loanApplication);
kieSession.fireAllRules();
kieSession.dispose();

5. Verify Agenda Group Execution Behaviour

Before going live, verify that your sequential rules execute as expected. Use unit tests to confirm that rules halt correctly after matches are found and the next agenda group’s rules fire afterward. Libraries like JUnit 5 can help run extensive Drools rule tests effectively.

Best Practices for Sequential Agenda Groups and Singleton Rule Loading

  • Keep Agenda Groups Small: Avoid populating groups with excessive rules. Small groups execute faster and are simpler to maintain.
  • Clear Stop Conditions: Explicitly define clear stopping points within agenda groups to avoid unnecessary rule evaluations.
  • Singleton Pattern Efficiently: Verify your singleton initialization occurs exactly once to avoid memory leaks or redundant loading.
  • Rebuild Only When Necessary: Reload Drools rules only when rules change drastically, limiting the performance overhead.

Wrapping Up

Using Drools with sequential execution of agenda groups and singleton rule loading in Dropwizard brings significant benefits. It improves performance, provides clear rule-sequencing control, and streamlines your application’s logical structures.

Ready to refine your business logic with Drools and Dropwizard? Experiment with sequential agenda groups and singleton loading strategies to maximize your application’s efficiency. Have you tried this approach in your projects? Share your experiences or challenges in the comments below!


Like it? Share with your friends!

Shivateja Keerthi
Hey there! I'm Shivateja Keerthi, a full-stack developer who loves diving deep into code, fixing tricky bugs, and figuring out why things break. I mainly work with JavaScript and Python, and I enjoy sharing everything I learn - especially about debugging, troubleshooting errors, and making development smoother. If you've ever struggled with weird bugs or just want to get better at coding, you're in the right place. Through my blog, I share tips, solutions, and insights to help you code smarter and debug faster. Let’s make coding less frustrating and more fun! My LinkedIn Follow Me on X

0 Comments

Your email address will not be published. Required fields are marked *