The risk team wants the fraud threshold on order messages moved from 500 to 400 by Friday. The
threshold sits in an if chain inside the worker, so the change waits for a pull request, a review
and a deploy. The chain also returns at its first match, so an order that is both large and foreign
gets one label and drops the other.
What you get
You will end up with five routing and tagging rules held as JSON, evaluated per message by json-rules-engine, and ten fixture messages that pin the events each one fires. This is for you if people outside the code need to change the rules.
Short answer
Load rules as JSON into a json-rules-engine Engine, each with all or any conditions over
facts, a priority, and one event. Pass each message to engine.run() and read results: every rule
whose conditions hold fires, so reduce route events to one queue yourself. Facts the message lacks
come from an async resolver, cached for one run() only, so memoize database queries outside the
engine.
You will need
Node 22.18 or later, which runs the sample’s .ts files by
stripping the types, and a message type whose fields the
rules test. Verified 2026-11-30 against Node 22.23.5, json-rules-engine 7.3.1 and
@gorules/zen-engine 2.1.12. The dispatcher this extends is covered in
dispatch messages to handlers with a Map keyed by type.
ZEN is compiled Rust loaded into Node. npm ci takes its binary from a prebuilt package for the
platform. It runs no install script and downloads nothing beyond the registry. Its
support matrix lists Linux, macOS and
Windows on x64, and Linux and macOS on arm64. On any other platform the package loads its
WebAssembly build, whose package asks for Node 20.19 or later on line 20, 22.13 or later on line
22, or 23.5 and later. The suite runs the
comparison under both builds and gets the same answers.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| GoRules ZEN engine | Analysts edit decision tables, or one rule set runs in Node, Python, Go and Java | A native binary or a WebAssembly fallback, and every fact a table reads is loaded before the table runs | A fact is expensive and only some rules need it |
| hand-written predicate functions | Developers own every rule change, at deploy cadence | Every threshold change waits for a code review and a release | People outside the team must change rules without a release |
| json-rules-engine | Rules stored as data, edited at runtime, with facts fetched only when a condition asks | No type check on fact names, stack traces that end in the engine, and every match fires | The people who write the rules also deploy the code |
ZEN reads the same five rules as one decision table and evaluates them in Rust. A table matches on the input that reaches it, so the tier is loaded first, by the caller here or by a function node placed ahead of the table. Predicate functions keep the compiler and readable stack traces, and they cost a release per change. json-rules-engine sits between the two: rules are data, facts resolve on demand, and a misspelled fact name surfaces at run time.
Write the rules as data
A rule is a JSON object with conditions, an event and a priority. Conditions nest all and
any blocks over facts, compared with operators such as greaterThanInclusive and notIn from the
rules reference.
[
{
"name": "fraud-review",
"priority": 20,
"conditions": {
"all": [
{ "fact": "amount", "operator": "greaterThanInclusive", "value": 500 },
{
"any": [
{ "fact": "country", "operator": "notIn", "value": ["IE", "FR", "DE", "ES", "NL"] },
{ "fact": "customerTier", "operator": "equal", "value": "new" }
]
}
]
},
"event": { "type": "route", "params": { "queue": "fraud-review" } }
},
The other four rules route gold web orders to priority-fulfillment and tag orders as
high-value, vip or export. Each rule carries one event. A rule that must do two things is two
rules.
Resolve facts the message does not carry
The message carries customerId, not the tier. A dynamic fact fetches it, and the engine calls the
resolver only when a condition asks for customerTier.
export function buildEngine(tierOf: TierLookup, { cache = true } = {}) {
const engine = new Engine([], { allowUndefinedFacts: false })
for (const rule of RULES) engine.addRule(rule)
// A fact the message does not carry. The engine calls this resolver the
// first time a condition asks for customerTier during one run().
engine.addFact(
'customerTier',
async (_params, almanac) => tierOf(await almanac.factValue<string>('customerId')),
{ cache },
)
return engine
}
almanac.factValue
reads another fact, here a field of the message passed to run(). The cache option defaults to
true, per the facts reference.
Run the ten fixtures through one engine:
node demo.ts
m01 ok queue=priority-fulfillment route:priority-fulfillment tag:high-value tag:vip
m02 ok queue=default (none)
m03 ok queue=fraud-review route:fraud-review
m04 ok queue=default tag:export
m05 ok queue=fraud-review route:fraud-review route:priority-fulfillment tag:high-value tag:vip tag:export
m06 ok queue=default tag:vip
m07 ok queue=default tag:high-value
m08 ok queue=fraud-review route:fraud-review tag:vip tag:export
m09 ok queue=default (none)
m10 ok queue=priority-fulfillment route:priority-fulfillment tag:vip
10 of 10 messages fired the expected events
Choose one queue when two routes fire
Message m05 fired two route events. A handler map promises one handler per message, and an engine
promises every rule that matched. Rules of equal priority run in parallel, so the sample sorts
results by priority and then by position in rules.json before it labels them.
// The dispatcher's contract is one queue per message, so the route events
// are reduced to the first one in priority order.
export function pickRoute(events: string[]): string {
return events.find((e) => e.startsWith('route:'))?.slice('route:'.length) ?? 'default'
}
The same rules as a ZEN decision table and as a predicate array give the same answers. ZEN states
the contract in the table itself: hit policy collect returns every matching row, and first
returns one.
node compare.ts
json-rules-engine 10 of 10 fixtures match
ZEN collect 10 of 10 fixtures match
predicates 10 of 10 fixtures match
m05 under ZEN first: route:fraud-review
m05 under ZEN collect: route:fraud-review route:priority-fulfillment tag:high-value tag:vip tag:export
The ZEN editor makes first the default of its
hit policies,1 and the 2.1.12 engine
refuses a table that names none. json-rules-engine has no such switch. engine.stop()
skips later priority sets, but the rules of the set that called it have already started and still
fire, so the reduction belongs in your dispatcher.
Check it worked
The suite checks the ten fixtures in each engine and in the WebAssembly build of ZEN. It also checks
the two routes on m05, engine.stop(), the query counts below, and a misspelled fact in each
style.
node --test rules.test.ts
1..10
# tests 10
# suites 0
# pass 10
# fail 0
# cancelled 0
# skipped 0
# todo 0
Change the high-value threshold in rules.json from 1000 to 999 and the first test fails on
m10, whose amount is 999. That is the review step a rule change needs: edit the JSON, run the
fixtures, and ship the data only when they pass.
When it goes wrong
The customer database takes one query per message. The fact cache lives in the almanac, and
run() builds a fresh almanac on each call that does not pass one,2 so a cached tier never
reaches the next message.
node queries.ts
10 messages, 4 distinct customers
per-run cache customer queries: 10
cache: false customer queries: 30
memoized outside customer queries: 4
The control run with cache: false shows three conditions reading customerTier per message. Wrap
the lookup in a memo that outlives the engine, with a lifetime you can defend for a stale tier:
export function memoize(
lookup: TierLookup,
{ ttlMs, now = Date.now }: { ttlMs: number; now?: () => number },
): TierLookup {
const entries = new Map<string, { at: number; value: Promise<string> }>()
return (customerId) => {
const hit = entries.get(customerId)
if (hit && now() - hit.at < ttlMs) return hit.value
const value = lookup(customerId)
entries.set(customerId, { at: now(), value })
value.catch(() => {
if (entries.get(customerId)?.value === value) entries.delete(customerId)
})
return value
}
}
A misspelled fact passes addRule and fails later. With the default allowUndefinedFacts: false,
run() throws from inside the engine. Set it to true and the rule fires no event, with no error to say why.
node typo.ts
m07, amount 1500, rule reads fact "ammount"
allowUndefinedFacts: false run() threw: Undefined fact: ammount at node_modules/json-rules-engine/dist/errors.js
allowUndefinedFacts: true run() resolved with 0 events
Keep the default, and run the fixtures against every rule change. The same typo in a predicate,
typo-predicate.ts, is a compile error, TS2551, which the last test checks with TypeScript.
When not to do this
Do not adopt a rules engine when the people who change the rules are the developers who deploy the worker. A typed predicate array gives the same events on the same fixtures, keeps the compiler on every field name, and puts a stack trace on the line that threw.
Do not put an engine on a dispatch path whose contract is one handler per message without the reduction step. Every matching rule fires, and a second route event that nobody reduces becomes a message sent to two queues.
Do not resolve a fact from a database inside the engine without a memo or a batch in front of it. The per-run cache saves repeated reads within one message only.
Skip ZEN when the facts are expensive and most rules never need them, because a decision table matches on an input you assembled in advance. Choose it over json-rules-engine when analysts need an editor and the same tables must run in services written in other languages.
Related how-tos
Last verified
Verified 2026-11-30 against Node 22.23.5, json-rules-engine 7.3.1, @gorules/zen-engine 2.1.12
with its prebuilt Linux x64 binary and its WebAssembly build, and TypeScript 7.0.2. Every output block is what the preceding
command printed.
Footnotes
-
The Object Management Group’s Decision Model and Notation 1.5, released in January 2024, names seven hit policies and makes Unique the default. It calls First “still a common usage,” because it resolves inconsistencies by forcing the first hit. It also calls first-hit tables “not considered good practice,” because they “do not offer a clear overview of the decision logic” (section 8.2.11.1). The ZEN documentation offers two of the seven, First and Collect, and marks First as the default. ↩︎ Back to text
-
The almanac is where the cache key ends up, and the key has a history of its own. The comments introducing the key code in json-rules-engine’s fact.js call it an MD5 string. The function under them calls hash-it, and the README of hash-it 6.0.1, the release 7.3.1 installs, shows it returning a number,
13729774857125for{ foo: 'bar' }. The facts reference mentions no algorithm at all. ↩︎ Back to text