Share
Embed
Scaling Business Logic with Rules Engines
This slide deck explores how rule engines can help manage complex and growing business logic in .NET applications. It covers business rules, expert systems, NRules, fact-based reasoning, rule execution, and a practical shipment exception diagnosis demo.
The session also compares traditional C# if/else logic with a rule-engine approach and explains when using a rules engine is actually worth the added complexity.
Nishan Chathuranga
July 29, 2026
Transcript
34 slides
-
SCALING BUSINESS LOGIC WITH RULES ENGINES Building Explainable Expert Systems
with NRules / .NET NISHAN WICKRAMARATHNA ASSOCIATE TECH LEAD @ Xeynergy BSc (Hons) in Information Technology - University of Moratuwa -
THE PROBLEM Let’s define the business problem Understanding the Shipment
Exception Domain A shipment normally begins with a valid booking and a scheduled gate appointment for the truck to enter the terminal. When the truck arrives, the terminal records an ingate transaction confirming that the truck or container has entered, after which the container is processed. Several problems can interrupt this process, including an expiring booking, missing documentation for hazardous cargo, temperature violations in cold-chain shipments, or outdated GPSRULES data. SCALING BUSINESS WITH RULES ENGINES 03 -
FOUNDATION A business rule states what must be true (Cont.)
A business rule is a precise statement that constrains, derives, or triggers business behavior. Constraint Derivation Action What is allowed? What can we conclude? What should happen? A hazardous shipment cannot proceed without a permit. A shipment booking that expires within the next 48 hours may require immediate attention to avoid delays. A critical cold-chain breach must trigger manual review. SCALING BUSINESS RULES WITH RULES ENGINES 04 -
THE TENSION The code is simple—until the knowledge becomes a
network A single rule is easy. The challenge appears when rules overlap, depend on several facts, fire together, and must explain their decisions. WHEN COMPLEXITY GROWS Many independent conditions Multiple conclusions can be true Rules change at different speeds Priority and conflict resolution matter • The system must answer “why?” • • • • The problem is not the syntax. It is the shape of the knowledge. SCALING BUSINESS RULES WITH RULES ENGINES 05 -
EXAMPLES Business rules appear wherever decisions depend on policy PRICING
Orders above $50,000 require director approval. COMPLIANCE Hazardous cargo requires a safety declaration. OPERATIONS A missed gate appointment requires rescheduling. SECURITY Restricted documents cannot be opened off-network. RISK Three weak fraud indicators trigger manual review. SCALING BUSINESS RULES WITH RULES ENGINES 06 -
PLAIN-LANGUAGE RULES Our shipment rules read like operational knowledge 01
IF the shipment is at port AND the appointment has expired 02 IF GPS has not changed for 12 hours AND no ingate exists AND ignition is off THEN report a missed gate AND the vehicle is outside a appointment terminal THEN report a possible breakdown SCALING BUSINESS RULES WITH RULES ENGINES 07 -
PLAIN-LANGUAGE RULES Independent rules can contribute to the same diagnosis
Terminal unavailable IF the driver is near the terminal AND the terminal is closed. Booking expiry risk IF the booking expires within 48 hours AND the shipment is not complete. Missing documentation IF one or more required documents are missing. Stale GPS IF the last GPS update is older than the allowed threshold. Cold-chain breach IF refrigerated cargo exceeds its permitted temperature. Shipment is at high risk and requires manual review. SCALING BUSINESS RULES WITH RULES ENGINES 08 -
IMPLEMENTATION Plain C# is the right starting point for a
small rule set if (shipment.IsAtPort && appointment.IsExpired && !appointment.HasIngate) { diagnosis.Add(MissedAppointment()); } if (gps.StaleHours >= 12 && !vehicle.IgnitionOn && !location.IsAtTerminal) { diagnosis.Add(PossibleBreakdown()); } SCALING BUSINESS RULES WITH RULES ENGINES WHY THIS WORKS Strongly typed Easy to debug No new dependency Excellent for a few stable rules Start here. Graduate only when the rule model earns the extra machinery. 09 -
SCALING POINT If/else strains when rules stop being a sequence
PROCEDURAL FLOW RULE NETWORK First check A A and B may both match otherwise check B C may create a new fact otherwise check C priority may change the order return one result return several explained findings The decision to use a rule engine is architectural—not stylistic. SCALING BUSINESS RULES WITH RULES ENGINES 10 -
EXPERT SYSTEMS An expert system encodes specialist knowledge as executable
reasoning It applies a knowledge base to facts through an inference mechanism, then produces conclusions and explanations. 1 2 3 4 5 Facts Rules Inference Conclusion Explanation What is currently known What domain experts know Which rules apply now What the system recommends Why it reached that result Deterministic expert systems are AI systems—even without machine learning or an LLM. SCALING BUSINESS RULES WITH RULES ENGINES 11 -
EXPERT-SYSTEM ANATOMY The inference engine connects knowledge to the current
situation Facts Working memory Shipment, GPS, booking, terminal, documents The facts available in this evaluation Inference engine Findings Match → resolve → act Diagnosis + recommended action Knowledge base Independent production rules The project supplies the domain and knowledge. Rules Engine supplies the inference machinery. SCALING BUSINESS RULES WITH RULES ENGINES 12 -
CORE FEATURES Useful expert systems are consistent, explainable, and extensible
Knowledge separation Multiple conclusions Rules live outside controllers and orchestration. More than one rule can fire for the same case. Forward chaining Conflict resolution A rule can create facts that activate other rules. The engine decides which activation fires next. Explanation Repeatability Results carry evidence, reasons, and firedrule names. The same facts and rule version produce the same result. SCALING BUSINESS RULES WITH RULES ENGINES 13 -
HISTORICAL EXAMPLES Classic expert systems MYCIN DENDRAL Medical diagnosis and
treatment recommendations Identified molecular structures using expert scientific knowledge XCON/R1 Configured DEC computer systems using thousands of production rules SCALING BUSINESS RULES WITH RULES ENGINES 14 -
EXPERT-SYSTEM SHELLS An expert-system shell provides the reasoning machinery, not
the expertise A shell is a reusable environment containing an inference engine, fact storage, rule language, and development tools. The domain knowledge is added later. CLIPS Jess NASA-developed expert-system building tool Java Expert System Shell from Sandia Rules + facts + inference engine + debugging environment Declarative rules applied repeatedly to a collection of facts Sources: NASA NTRS — CLIPS (1994) • Sandia National Laboratories — Jess SCALING BUSINESS RULES WITH RULES ENGINES 15 -
RULE ENGINES FOR .NET .NET rule engines use different authoring
models OPTION RULE AUTHORING BEST FIT NRules C# internal DSL; Rete inference Interacting facts, multiple activations, forward chaining Microsoft RulesEngine JSON workflows + dynamic expressions Externally stored rules and workflow-style evaluation Code Effects Visual rule editor + .NET engine Business-authored rules and commercial decision automation Choose the authoring and execution model that matches who owns the rules and how they interact. Sources: nrules.net • github.com/microsoft/RulesEngine • codeeffects.com SCALING BUSINESS RULES WITH RULES ENGINES 16 -
NRULES NRules is a production rules engine and inference engine
for .NET Rules are C# classes. Facts are ordinary domain objects. The compiled rule network decides what can fire. C# DSL Rules inherit from Rule and implement Define(). Rete network Compiled patterns efficiently match facts to rules. No fixed order The engine runs a match → resolve → act cycle. Native domain model Rules reason over POCOs instead of string dictionaries. Source: NRules official documentation — nrules.net SCALING BUSINESS RULES WITH RULES ENGINES 17 -
NRULES FEATURES NRules exposes the pieces needed to run and
observe inference ISessionFactory Compiled rules; create once for an application rule set. ISession Independent working memory for one request or fact universe. Working memory Insert, update, retract, and query domain facts. Agenda Holds activations and applies conflict resolution. Forward chaining Rules can insert or yield facts that activate other rules. Rule metadata Names, descriptions, tags, priorities, repeatability. Quantifiers & queries Negative, existential, universal, and complex matches. Events & diagnostics Observe rule firing and inspect the Rete graph. NRules docs: API, architecture, forward chaining, and diagnostics — nrules.net SCALING BUSINESS RULES WITH RULES ENGINES 18 -
HOW INFERENCE RUNS NRules repeatedly matches facts, resolves conflicts, and
acts Facts Match Agenda Resolve Act Inserted into working memory Rete finds rule– fact matches Activations wait to fire Choose the next activation Run actions; facts may change The cycle continues until no activations remain. Rete avoids re-evaluating every condition from scratch when working memory changes. Source: NRules Getting Started and Architecture — nrules.net SCALING BUSINESS RULES WITH RULES ENGINES 19 -
PROJECT ARCHITECTURE The API keeps rules outside controllers and persistence
API controller Diagnoser ISession Facts + rules Diagnosis Accepts request; returns response Maps and orchestrates Independent per request Domain knowledge Findings + evidence Controllers transport data. Rules express knowledge. The service owns execution. This separation makes rules testable without HTTP, databases, or UI concerns. SCALING BUSINESS RULES WITH RULES ENGINES 20 -
DEMO The demo project is an ASP.NET Core Web API
that uses NRules to diagnose possible shipment exceptions. It converts an incoming shipment request into domain facts such as booking, gate appointment, terminal status, GPS location, documentation, and temperature information. These facts are inserted into a new NRules session, where independent rules evaluate them and identify issues such as missed gate appointments, possible vehicle breakdowns, booking-expiry risks, missing documents, and cold-chain breaches. The API returns a combined diagnosis containing the detected problems, their severity, supporting evidence, recommended actions, and the rules that fired. -
PROJECT MAP The project structure mirrors those responsibilities Contracts/ •
• Request and response DTOs Domain/ • • Facts / findings Severity / exception types Rules/ • • Seven rule classes Session factory Services/ • • Diagnoser interface NRules implementation Controllers/ POST /diagnose endpoint Rule discovery happens through the rules assembly—adding a class does not require editing a central decision method. SCALING BUSINESS RULES WITH RULES ENGINES 22 -
DOMAIN MODELS Domain models turn raw request data into facts
the rules can join ShipmentFact identity + evaluation time BookingFact expiry + completion LocationFact at port / terminal / movement DocumentationFact required vs available GateAppointmentFact window + ingate state TemperatureFact actual vs permitted TerminalFact open / closed ShipmentDiagnosis A mutable result fact that collects findings. SCALING BUSINESS RULES WITH RULES ENGINES 23 -
REQUEST-TO-FACTS MAPPING One request becomes several typed facts in working
memory HTTP request Mapper Fact set ISession One shipment snapshot from the API contract Normalizes timestamps, IDs, and nullable fields Seven typed facts + one diagnosis result Independent working memory Fact design is the foundation: rules can only reason over relationships the model makes explicit. SCALING BUSINESS RULES WITH RULES ENGINES 24 -
SESSION LIFECYCLE Compile once; create a fresh session for each
diagnosis ISessionFactory Singleton • compiled rules Request A session Request B session Request C session Facts for SHIP1001 Facts for SHIP1002 Facts for SHIP1003 Sessions share compiled rules—not facts or results. Source: NRules ISessionFactory API — create one factory per rule set; one session per independent fact universe SCALING BUSINESS RULES WITH RULES ENGINES 25 -
RULE WALKTHROUGH 1 A multi-fact rule diagnoses a missed gate
appointment When() .Match(() => shipment) .Match(() => location, x => x.ShipmentId == shipment.ShipmentId, x => x.IsAtPort) .Match(() => appointment, x => x.ShipmentId == shipment.ShipmentId, x => x.IsExpired, x => !x.HasIngateTransaction); Then() .Do(_ => diagnosis.AddFinding( MissedGateAppointment())); SCALING BUSINESS RULES WITH RULES ENGINES WHAT THE ENGINE JOINS • • • • Shipment identity Current port location Expired appointment window Absence of an ingate transaction Result: a high-severity finding with evidence and a rescheduling action. 26 -
RULE WALKTHROUGH 2 A breakdown diagnosis needs several independent facts
When() .Match(() => location, x => x.StaleHours >= 12, x => !x.IsAtTerminal) .Match(() => vehicle, x => x.ShipmentId == location.ShipmentId, x => !x.IgnitionOn); Then() .Do(_ => diagnosis.AddFinding( PossibleVehicleBreakdown())); Weak evidence alone Stale GPS or ignition-off can have innocent causes. Combined evidence Together they support a possible breakdown—not certainty. Expert systems can encode cautious conclusions and recommend human verification. SCALING BUSINESS RULES WITH RULES ENGINES 27 -
RULE WALKTHROUGH 3 A threshold rule turns sensor data into
action When() .Match(() => temperature, x => x.IsRefrigerated, x => x.ActualCelsius > x.MaximumCelsius); Then() .Do(_ => diagnosis.AddFinding(new( code: "COLD_CHAIN_BREACH", severity: Severity.Critical, evidence: $"{temperature.ActualCelsius}°C", action: "Inspect cargo and reefer unit"))); RULE DESIGN CHOICES Boundary: > versus ≥ Missing sensor reading behavior Allowed excursion duration Duplicate-finding prevention Critical severity and manual review A readable rule still needs precise domain semantics. SCALING BUSINESS RULES WITH RULES ENGINES 28 -
SIDE-BY-SIDE COMPARISON The same rule reads procedurally in C# and
declaratively in NRules PLAIN C# NRULES if (location.IsAtPort && appointment.IsExpired && !appointment.HasIngate) { diagnosis.Add( MissedGateAppointment()); } When() .Match(() => location, x => x.IsAtPort) .Match(() => appointment, x => x.IsExpired, x => !x.HasIngate); Control Code determines order Agenda determines firing Composition Central method can grow Independent rule classes Best when Few stable decisions Many interacting facts/rules SCALING BUSINESS RULES WITH RULES ENGINES Then().Do(_ => diagnosis.AddFinding(...)); 29 -
TESTING AND EXTENSION A rule is not finished until its
boundaries and interactions are tested 01 Matching case Expired by one minute + no ingate → fires 02 Non-match Appointment ends in one minute → does not fire 03 Boundary Exactly 48 hours before booking expiry 04 Overlap Appointment missed + terminal closed → both fire 05 Result integrity Severity, evidence, fired rules, no duplicates Adding a new rule should require a new class and tests—not edits across every existing branch. SCALING BUSINESS RULES WITH RULES ENGINES 30 -
DECISION GUIDE Use a rule engine when the knowledge—not merely
the code—is complex GOOD FIT • • • • • • Many independent rules Several rules can fire Facts interact across sources Forward chaining is useful Decisions need explanations Priorities or conflicts matter STAY WITH C# • • • • • • A few stable checks A clear procedural sequence Only one outcome is needed Rules do not infer new facts The logic is already easy to trace A library adds more cost than value Start simple. Adopt inference when it makes the domain easier to express and verify. SCALING BUSINESS RULES WITH RULES ENGINES 31 -
BEYOND THE DEMO Production rule systems need governance around the
engine Versioning Which rule set made this decision? Auditability Which facts matched and which rules fired? Ownership Who approves a rule or threshold change? Observability How often does each rule fire or fail? Conflict policy What happens when findings disagree? Performance How does the network behave at real fact volume? Security Who may author, activate, or disable rules? Deployment Code rules still normally require a release. The engine executes decisions; engineering discipline makes them trustworthy. SCALING BUSINESS RULES WITH RULES ENGINES 32 -
TAKEAWAY Business rules scale when knowledge is explicit. Use plain
C# for simple decisions. Use an inference engine when rules interact, multiple conclusions matter, and the system must explain why. 1 Model the facts clearly 2 Keep rules independent 3 Return evidence, not only answers We represent the available data as multiple manageable domain objects called facts. The rules engine matches those facts against the conditions defined in different rules, executes the matching rules, and combines their findings into the final result. the engine does not simply return the matched rules. The matched rules fire, and their actions produce findings, recommendations, or new facts. SCALING BUSINESS RULES WITH RULES ENGINES 33