Business Rules Engine - HLD
Difficulty: Intermediate–Advanced · Prerequisites: Message Queues, Caching Asked at: Amazon, Flipkart, Razorpay, PayPal, Uber, Goldman Sachs
TL;DR
A business rules engine decouples decision logic from application code. Product teams author rules (“if order > $500 AND user is new, apply 10% discount”) via a management UI. The engine evaluates incoming events against thousands of active rules in sub-50ms, then triggers actions without redeploying any service.
flowchart LR
ADMIN["Rule Authors"]
API["Rules API"]
DB[("Rule Store<br/>Postgres")]
CACHE[("Rule Cache<br/>Redis and in-memory")]
ENGINE["Evaluation Engine<br/>Rete network"]
KAFKA["Action Bus<br/>Kafka"]
ACTIONS["Action Executor<br/>webhook email DB"]
ADMIN -->|"1. author rule"| API
API -->|"2. version it"| DB
DB -->|"3. change event"| KAFKA
KAFKA -->|"4. invalidate"| CACHE
ENGINE -->|"5. load rules"| CACHE
ENGINE -->|"6. matched actions"| KAFKA
KAFKA -->|"7. execute"| ACTIONS
In 3 sentences: Rule authors define conditions as structured expressions (stored as pre-parsed abstract syntax trees, or ASTs, in JSONB). The evaluation engine loads compiled rules from in-memory cache, runs them through a Rete network for shared sub-expression optimization, and collects matches in < 50ms. Matched actions are dispatched via Kafka to a decoupled executor with retries and dead-letter queues (DLQs).
💡 An abstract syntax tree (AST) is the condition stored as a tree of nodes instead of as text: total > 500 AND tier == 'NEW' becomes an AND node with two comparison children. Trees can be walked and checked; strings have to be re-parsed every time, which is the whole point of doing it once at write time.
Understanding the Problem
⚙️ What is a rules engine? Somewhere in every large product there is a pile of business logic that changes far more often than the code around it. Who qualifies for free shipping. Which transactions get held for review. When to send the win-back email. Each of these is a small condition over some event, and each is owned by someone who is not an engineer — a risk analyst, a growth manager, a pricing team.
Putting that logic in application code means every change is a code change, a review, and a deploy. A rules engine moves it into data: the condition is authored through a UI, stored, versioned, and evaluated at runtime, so changing a threshold from $500 to $400 is an edit rather than a release.
That inversion is the whole value and also the whole difficulty. Once business users can write conditions that run in your hot path, you have handed them a way to break production without a deploy — so the engine has to be fast with thousands of active rules, has to reject nonsense before it ships, and has to make a bad rule reversible in seconds.
Naive First Cut
A 30-second whiteboard sketch:
flowchart LR
EVENT["Event"]
SVC["Service with if-else block"]
DB[("Rules Table")]
EVENT --> SVC
SVC -->|"SELECT all rules"| DB
SVC -->|"eval each string with eval()"| SVC
What the sketch shows: rules live as expression strings in a table. On each event the service selects every active rule and evaluates the strings one by one in a loop.
It works for fifty rules and fails in six specific ways:
- A database read per event. At 50K events/sec this is 50K queries/sec for data that changes a few times a day — the worst possible read pattern.
- Re-parsing the same strings forever. Every evaluation re-parses text into something executable. That cost is paid per event per rule, when it could be paid once per rule at write time.
- The work is quadratic in the wrong dimension. 10,000 rules times every event, with no sharing, even though hundreds of rules begin with the identical
country == 'US'check. eval()on user-authored strings is remote code execution wearing a business-logic costume. The authoring surface has to be a restricted expression grammar, not a language.- A typo reaches production instantly, because nothing validates a rule before it goes live, and there is no staged rollout or shadow mode to catch it.
- Partial action failure is silent. A rule that fires three actions where the second one times out leaves the system in a state nobody recorded.
The rest of this doc evolves that into pre-compiled ASTs, a shared evaluation network, a push-based cache, validation at authoring time, and transactional action dispatch.
Prior Art We’re Drawing From
- Rete (Charles Forgy, 1979) — the algorithm every production rules engine descends from. It compiles rules into a dataflow network and evaluates conditions incrementally, caching partial matches so a small change to working memory does not force a full re-evaluation. That is exactly the “400 rules share one comparison” problem in deep dive 1. Its trade-off is explicit and worth repeating: it buys speed with memory. Oracle’s own documentation is unusually candid that many business-rule workloads do not match Rete’s assumed usage profile, and so pay the memory overhead without collecting the speedup — which is why this design keeps the network but notes where a simpler indexed scan would do. (Oracle: Rules Engine Algorithms)
- Drools — the reference open-source BRMS, built on an enhanced Rete variant (Phreak) and the usual answer to “why not just use something off the shelf”. Worth naming the reason to build instead: Drools assumes rules are deployed artifacts, while this design treats them as live data edited through an API. (Drools overview)
- Rete node sharing — the specific mechanism borrowed here: identical condition nodes across rules are compiled once and their results reused, turning repeated sub-expressions from a per-rule cost into a per-distinct-condition cost. (How the Rete algorithm works)
- Pre-parsed ASTs over expression strings — storing the parsed tree rather than the text moves parsing and validation to write time, which is both the latency win and the safety win, since an unparseable rule can be rejected before it is ever active.
Content from these sources was rephrased for compliance with licensing restrictions.
Functional Requirements
Core (top 3)
- Author and manage rules — CRUD rules with structured conditions (comparisons, arithmetic, boolean logic, nested expressions), assign actions, activate/deactivate, version with rollback.
- Evaluate events against rules — given an event payload (JSON), find all matching rules and return decisions + trigger actions, in < 50ms P99 (the latency 99% of requests beat) for 10K active rules.
💡 P99 is the slow tail rather than the average: 99 of every 100 evaluations must finish under 50ms. Designing against the tail matters because this engine sits inside someone else’s checkout request. - Hot reload without downtime — when a rule changes, all engine instances pick up the new version within 2 seconds without restart or dropped evaluations.
Below the line
- Visual rule builder UI (assume it calls our API).
- A/B testing of rule variants.
- Rule simulation across historical event datasets.
- Multi-tenant isolation at the compute level (we do namespace isolation only).
- Complex event processing (time-windowed correlations across multiple events).
Non-Functional Requirements
- Latency — P99 evaluation < 50ms for 10K active rules against a single event.
- Throughput — 50K evaluations/sec per engine instance, horizontally scalable.
- Consistency — rule changes propagated to all instances within 2s. Strong consistency for blocking rules via direct DB read.
- Auditability — full immutable execution log for compliance.
Discussion
Newest first