Skip to main content

Overview

The RuleEngine is the core component responsible for evaluating rule expressions against data contexts. It provides high-performance rule evaluation with intelligent caching, operator management, and built-in security features.
The Rule Engine is designed to be stateless and reusable. Create a single instance and reuse it throughout your application for optimal performance.

Creating an Engine

Use the factory function to create a new engine instance:

Configuration Options

boolean
default:"false"
Enable strict type checking for operators. When enabled, type coercion is disabled.
number
default:"10"
Maximum nesting depth for rule expressions. Prevents infinite recursion.
boolean
default:"true"
Enable LRU caching for expression results and path resolution.
number
default:"500"
Maximum number of cached expression results. Uses LRU eviction strategy.
number
default:"100"
Maximum number of operators allowed in a single rule expression.
boolean
default:"false"
Enable debug logging for rule evaluation failures.
boolean
default:"false"
Allow access to prototype properties. Always keep false in production for security.

Core Methods

evaluateExpr()

Evaluate a rule expression against a data context:
Return Value:

registerOperator()

Register custom operators for business-specific logic:
Parameters:
  • name (string): Operator identifier
  • handler (function): Implementation function with signature (args, context, evaluateExpr, depth) => boolean
  • options (object): Optional configuration
    • allowOverwrite (boolean): Allow replacing existing operators

Performance Methods

getMetrics()

Get real-time performance metrics:
Monitor these metrics in production to identify performance bottlenecks and optimize rule complexity.

getCacheStats()

Get cache statistics for monitoring:

clearCache()

Clear all caches (expression and path resolver):
Clearing the cache will temporarily impact performance as the cache is rebuilt. Use sparingly in production.

Utility Methods

getOperators()

Get list of all registered operators:

getConfig()

Get current engine configuration:

Architecture

1

Rule Validation

The engine validates rule structure, checks depth limits, and counts operators before evaluation.
2

Cache Check

Looks up the expression in the LRU cache using a composite key of expression + context.
3

Expression Evaluation

Recursively evaluates operators, resolving paths and applying operator logic.
4

Cache Storage

Successful evaluations are cached with LRU eviction when cache is full.
5

Metrics Update

Performance metrics are updated including timing, cache hits, and errors.

Caching Strategy

The Rule Engine uses a two-tier caching system:

Expression Cache

Caches complete rule evaluation results based on expression + context hash.
  • LRU Eviction: Oldest entries removed when cache is full
  • Default Size: 500 entries
  • Key Strategy: Composite of rule structure and context values

Path Resolution Cache

Caches dot-notation path lookups for nested data access.
  • LRU Eviction: Automatic cleanup of least-used paths
  • Default Size: 500 entries
  • Scope: Shared across all rule evaluations

Cache Key Generation

The engine creates intelligent cache keys based on:
  1. Expression Structure: JSON-stringified rule object
  2. Context Identity: Context ID, shape hash, or value hash
  3. Composite Key: expr:{rule}:ctx:{contextId}
For best cache performance, use consistent object shapes and provide explicit id or _id fields in your context objects.

Security Features

The engine blocks access to dangerous paths like __proto__, constructor, and prototype:
Prevents stack overflow attacks through deeply nested rules:
Prevents resource exhaustion from overly complex rules:
Functions in context data are automatically blocked:

Best Practices

Reuse Engine Instances

Create a single engine instance and reuse it across your application for optimal caching.

Configure Cache Size

Adjust cache size based on your rule complexity and data variability.

Monitor Performance

Regularly check metrics to identify slow rules and optimization opportunities.

Handle Errors Gracefully

Always check the success flag and provide fallback behavior.

Common Patterns

Middleware Integration

Batch Evaluation

Next Steps

Stateful Engine

Learn about state tracking and event-driven rules

Path Resolver

Understand how path resolution works

Operators

Explore built-in operators and create custom ones

Performance Guide

Optimize rule performance