Dataflow-rs
A high-performance rules engine for IFTTT-style automation in Rust with zero-overhead JSONLogic evaluation.
Dataflow-rs is a lightweight, embeddable rules engine that lets you define IF → THEN → THAT automation in JSON. The builder compiles every rule's JSONLogic once at build time, so runs skip parsing and execute host functions on Tokio. Use it to route events, validate data, or build multi-step automation pipelines.
⚡ Performance
Dataflow-rs is designed for high-throughput workloads. The builder compiles every expression, task config, and write path once at build time. At runtime, each message is evaluated against a single context view with only one clock read.
In the 4.0 release benchmarks against 3.15.0, 16 of 49 metrics were faster, 25 improved, 6 were equal, and the remaining 2 matched across seven rounds. loop_scaling (a 1,000-iteration append loop over a large context) finished in 1–3% of the 3.15 runtime. See Performance for the benchmark methodology and commands.
🧩 Full-Stack Ecosystem
Run the same rule definitions across your stack:
- Rust Backend: Run natively with high speed and concurrency using
dataflow-rs. - Browser & Edge: Run client-side validations or edge routing through the WebAssembly bindings in @goplasmatic/dataflow-wasm.
- React UI Admin Portal: Let your team and your users visualize, edit, and step through rules with @goplasmatic/dataflow-ui.
How It Works: IF → THEN → THAT
┌─────────────────────────────────────────────────────────────────┐
│ Rule (Workflow) │
│ │
│ IF condition matches → JSONLogic against any field │
│ THEN execute actions (tasks) → map, validate, custom logic │
│ THAT chain more rules → priority-ordered execution │
└─────────────────────────────────────────────────────────────────┘
Example: IF order.total > 1000 THEN apply_discount AND notify_manager
Core Concepts
| Term | In the API | Description |
|---|---|---|
| Rule | WorkflowDef |
A condition plus a list of tasks: IF the condition holds, THEN the tasks run |
| Action | TaskDef |
One processing step: a built-in (map, validation, ...) or a function you register |
| Message | Message |
Input and state for a run: payload, a context of data, metadata, and temp_data, an audit trail, and an error list |
| Engine | Engine |
Compiled rules plus registered functions; run takes a message through matching rules |
| Run | Run |
Report for one execution: status, per-rule records, and an optional trace |
Why dataflow-rs?
Dynamic business rules and user-customizable workflows outgrow hardcoded if/else branches, while distributed orchestrators (like Temporal or Zeebe) add infrastructure and network latency. Dataflow-rs sits between the two:
| Capability | Hardcoded Rust | dataflow-rs | Heavy Orchestrators (Temporal/Zeebe) |
|---|---|---|---|
| Hot Reload Rules | Recompile & redeploy | Compile the new JSON, swap the program | Deploy new worker code |
| Execution Overhead | None | Zero (pre-compiled JSONLogic) | DB reads/writes (tens of ms) |
| Browser Execution | Compile full app to WASM | Run same rules in JS via WASM | Network round-trip required |
| Visual Debugger | Build your own UI | Included React UI components | Included dashboard |
| Infrastructure | None | None (embeddable library) | Requires server clusters & DBs |
Getting Started
1. Add to Cargo.toml
[]
= "4.0"
= { = "1", = ["rt-multi-thread", "macros"] }
= "1.0"
JSONLogic's extended operator families are opt-in at runtime on
ExprEngineBuilder; ExprEngine::default() enables core JSONLogic only.
Read JSONLogic → Operator Families
before enabling a family: turning one on can change how an existing rule behaves.
2. Define Rules in JSON
A message arrives with its body in payload. The engine evaluates conditions
and mappings against data, so the first rule loads the payload into data,
and the second rule acts on it. Chaining, the THAT in IF → THEN → THAT,
means rules run in order and each one sees what the previous rules wrote.
The engine evaluates a rule's condition before running its tasks. A condition reads what earlier rules produced, not what its own tasks will write. Place
parse_jsonin an earlier rule sopremium_ordercan check the parsed fields in its condition.
3. Run the Engine
use RunStatus;
use ;
use ;
async
run returns a Run for every outcome without short-circuiting. Pass
RunOptions to run_with when you need a channel, routing bucket, deadline,
cancellation token, trace, or per-run observer.
Handling Errors: Two Channels
A run reports errors through two channels:
run.status()reports how the run ended:Completed,CompletedWithErrors(rules finished, with error records on the message),Stopped(error)(a task failed and its policy stopped the run),TimedOut, orCancelled(the run hit its deadline or cancellation token).message.errors()holds every error record, including errors from tasks whose policies allowed the run to continue.
Using ? on run.into_result() surfaces only stopped, timed-out, or cancelled runs. Check both channels to handle all errors:
use RunStatus;
use ;
use json;
async
Task policies control what happens after each outcome. A 4xx status is a
rejection, governed by on_rejection: "continue" (default) or "halt".
A 5xx status or Err is a failure, governed by on_failure: "fail"
(default, which delegates to the workflow's on_failure of "fail" or
"continue"), "halt" (stops the workflow and continues the run), or
"continue". Because validation returns 400 on failure, it continues to
the next task unless you set "on_rejection": "halt". See the
error handling guide.
Branching on Task Failures
Both error channels live on the host side in Rust. Rule conditions evaluate against
data, metadata, and temp_data, which do not include message.errors() by default.
If you configure an ErrorContext path, the engine mirrors each failure's code into
the message context as it occurs so later rules can branch on it:
use ;
use ;
use ;
async
Each record is {workflow_id, task_id, code, status}, so a later rule can treat
a transient failure differently from a permanent one:
The engine writes to this path only when configured and resets it at the start of each run. The mirrored records omit the error message text because callers receive the serialized context.
Classifying Your Own Errors
Built-in error kinds cover engine concerns such as a missing function, a failed
evaluation, or an invalid path. When a function fails for a service-specific
reason (an open circuit breaker or a tenant rate limit), classify it with
Error::service:
use Error;
let e = service.with_retryable;
assert_eq!;
assert!;
The engine preserves your code string without changing its case and reads the
retryable flag you set. Task on_failure policies, audit entries, and
Run::status handle service errors like any other failure, while
Run::retryable returns the flag you declared.
Key Features
- IF → THEN → THAT Model: Define rules with JSONLogic conditions, execute actions, and chain workflows in priority order.
- Compile at Build: The builder compiles every expression, task config, and write path once and rejects invalid definitions with their authored paths.
- Complete Run Reports:
runreturns aRunwhether execution completed, stopped, timed out, or was cancelled, preserving the message and trace. - Full Context Access: Conditions read any field in
data,metadata, andtemp_data. - Isolated Secrets:
{"secret": "name"}reads an engine-scoped store that stays out of traces, audit entries, and serialized messages.build()rejects workflows that would write a secret into the message. - Async Host Functions: Host functions are
async fnon Tokio; the eight built-in functions run inline. - Tracing and Observability:
TraceOptionsrecords per-step changes that replay to reconstruct the context at any step, bounded by a byte budget and path redaction.Observerreceives inline task events and reads the clock only whenInterest::TIMINGSis set. - Built-in Functions: Parse, Map, Validate, Filter, Log, and Publish.
- Outcome Policies: Configure
on_failureandon_rejectionper task,on_failureper workflow,terminaltasks, and task groups sharing a condition. - Loops and Fan-Outs: Workflow
loopruns a task list for a bounded number of sweeps. Taskfor_eachcalls a host function per array element in isolation and folds results in element order at anymax_concurrency. - Deadlines and Cancellation:
RunOptions::deadlineandCancelTokenend a run asTimedOutorCancelled, returning the partial message and trace. - Routing and Rollout: Route by channel, split traffic by bucket range, and manage workflow
status(active,paused,archived), version, and tags. - Hot Reload: Compile new definitions with
engine.compiler()and swap the program withwith_programwhile in-flight runs finish on the old program. - Extensible: Implement
Functionwith#[derive(FunctionConfig)], wrap host calls in aCallLayer, and unit-test individual calls withfunction::testing::call. - Service-Classified Errors: Attach custom error codes and retryability with
Error::service, and mirror failure codes into the context withErrorContext. - 3.x Compatibility: The compat reader rewrites 3.x spellings into 4.0 format and reports each as an Advisory; see Migrating from 3.x.
- Browser and UI: Run rules in the browser with
@goplasmatic/dataflow-wasmand debug them with@goplasmatic/dataflow-ui. - Auditing: Record an audit trail of context changes as data moves through the pipeline.
Architecture
Compilation (startup). def::parse reads each definition, rewrites 3.x
spellings, and reports issues at their authored paths. Compiler compiles each
workflow against a Registry (expressions, task configs, write paths), so you
can quarantine invalid workflows and keep valid ones. link sorts compiled
workflows by priority into an immutable Program. Engine::builder().build()
runs all three steps and fails if any workflow is rejected.
Execution (runtime). run stamps the message and evaluates active
workflows in priority order, checking rollout and then condition. Built-in
functions run inline over one view of the context. Host functions receive a
Ctx whose writes apply on Ok and drop on Err. After each non-skipped
call, the engine updates metadata.progress so later rules can inspect what
ran. Run reports the final status and per-workflow results, Observer
receives inline events, and Trace records step diffs when requested.
Performance
Key design choices keep per-message overhead low:
- Compile at Build: The builder compiles expressions, folds constants, and pre-splits write paths ahead of time, so runs do no parsing.
- Single Context View: Built-in tasks evaluate against a single arena view of the context and apply writes in place.
- Transactional Overlay Writes: Host function writes go to a per-call overlay that the function can read immediately; the engine commits them to the context only when the call returns
Ok. - Zero-Cost When Unwatched: A standard run reads the system clock once. Observer and trace work runs only when enabled, adding just a single branch per call when disabled.
- Async I/O: Host functions run on Tokio without blocking, and fan-outs run calls concurrently without spawning extra tasks.
In the 4.0 release benchmarks against 3.15.0, 16 of 49 metrics were faster, 25
improved, and 6 were equal, while the two micro_subtree_write_bench rows matched across
seven rounds. loop_scaling ran in 1–3% of the 3.15 runtime. bench/gate.py
compares a base commit against a candidate by alternating both builds within
each round and comparing the median per-round ratio against a 3% noise floor
(or half the interquartile range).
Tuning tip: If you do not inspect audit trails, pass
RunOptions::default().capture_changes(false) or retain only recent entries
with .audit(AuditMode::Last(n)). Skipping old/new value snapshots on every write
provides the largest speedup in mapping-heavy and looping workflows. See the
performance guide.
Always run benchmarks with --release. The crate includes 13 benchmark examples
(listed in CONTRIBUTING.md), and each verifies
its output before timing:
Results typically vary by 2–3% between runs. Compare the average of three or more interleaved A/B runs.
Custom Functions
Extend the engine with your own async actions. A custom function declares a typed
Config (compiled once when the engine is built), receives a Ctx (which automatically
records audit-trail changes for your writes), and returns an Outcome:
use OwnedDataValue;
use Output;
use ;
use RunStatus;
use ;
use ;
/// The task's `input`, compiled once when the engine is built. Invalid
/// configs are rejected at build time with an issue pointing to the field.
;
async
Outcome::Okrecords status200.Outcome::Status(n)records statusn(4xxis treated as a rejection and5xxas a failure under the task's policies).Outcome::Skipskips the task without recording an audit entry.Outcome::Haltrecords status299and stops the rest of the current workflow.
A function call's writes are committed to the message only when call returns Ok. Returning Err discards all writes from that call, ensuring a failed function never leaves partial changes behind.
Every Expr<T> config field accepts either a static JSON literal or a JSONLogic expression. Because any JSON literal is valid JSONLogic for itself, static values like "channel": "orders" are folded to constants at build time with zero runtime overhead. Use Expr<T> for fields your function evaluates, Output for destination paths your function writes to, and #[config(default = ...)] for optional fields with default values. Note that a single-key object whose key matches a JSONLogic operator is parsed as that operator—prefix the key with $ (for example, {"$cat": ...}) when you want a literal object. See Custom Functions and Literal keys and the $ escape.
Built-in Functions
| Function | Purpose | Modifies Data |
|---|---|---|
parse_json |
Parse JSON from payload into data context | Yes |
parse_xml |
Parse XML string into JSON data structure | Yes |
map |
Data transformation using JSONLogic | Yes |
validation |
Rule-based data validation | No (read-only) |
filter |
Pipeline control flow: halt workflow or skip task | No |
log |
Structured logging with JSONLogic expressions | No |
publish_json |
Serialize data to JSON string | Yes |
publish_xml |
Serialize data to XML string | Yes |
All eight built-in functions run inline on the engine's context view. Their names are reserved, and tasks that call them cannot use for_each.
Filter (Pipeline Control Flow)
The filter function evaluates a JSONLogic condition and controls pipeline execution:
on_reject: "halt"stops the entire workflow when the condition is falseon_reject: "skip"skips only the current task and continues
Log (Structured Logging)
The log function outputs structured log messages using the log crate:
Log levels: trace, debug, info, warn, error. Messages and fields support JSONLogic expressions.
Channel Routing
Workflows can specify a channel ({ "id": "order_rule", "channel": "orders", ... }),
allowing a run to execute only the workflows assigned to that channel:
use ;
/// Runs only the Active workflows in the `orders` channel.
async
Only active workflows run, whether or not a channel filter is set. Workflows default to
the "default" channel, and the engine writes the selected channel to metadata.channel when
started with one.
Workflow Lifecycle
Workflows support optional metadata and lifecycle fields:
{
"id": "my_rule",
"channel": "orders",
"version": 2,
"status": "active",
"tags": ["premium", "high-priority"],
"created_at": "2025-01-15T10:00:00Z",
"updated_at": "2025-06-01T14:30:00Z",
"tasks": [...]
}
| Field | Type | Default | Description |
|---|---|---|---|
priority |
number | 0 |
Execution order: lower numbers run first; ties preserve definition order |
channel |
string | "default" |
Channel for message routing |
version |
number | 1 |
Workflow version |
status |
string | "active" |
active, paused, or archived |
tags |
array | [] |
Arbitrary tags for organization |
rollout |
object | null |
Traffic split: {bucket_start, bucket_end} over 0..100 |
created_at |
datetime | null |
Creation timestamp (ISO 8601) |
updated_at |
datetime | null |
Last update timestamp (ISO 8601) |
All fields are optional. Unrecognized keys are preserved in the node's ext map and reported as an issue.
Traffic Splits (Canary Rollouts)
Assign a workflow a percentage of its channel's traffic using a half-open bucket range
over 0..100 so you can roll out a new version gradually alongside the existing one:
{
"id": "checkout_v2",
"channel": "checkout",
"rollout": { "bucket_start": 0, "bucket_end": 10 },
"tasks": [...]
}
This workflow handles buckets 0..=9 (10% of traffic). Because bucket_start is
inclusive and bucket_end is exclusive, a sibling workflow with {"bucket_start": 10, "bucket_end": 100}
covers the remaining 90% without overlap or gaps.
You choose how to compute the bucket for each run (for example, hashing a user ID, random sampling, or round-robin):
use ;
async
If a run does not specify a routing_bucket, all workflows match regardless of their rollout configuration, so existing callers continue working unchanged. Workflows excluded by a rollout bucket are skipped before condition evaluation and recorded in Run as SkippedByRollout.
Secrets
Sensitive values like signing keys or partner tokens often need to be checked in conditions without ever appearing in logs, traces, or serialized messages. Because everything inside Message can be serialized or traced, secrets live in a separate store on the expression engine and are read through the {"secret": "name"} operator:
use OwnedDataValue;
use ;
use ;
use json;
Secret values never enter a Message, so they cannot leak into anything derived from one. At build time, build() rejects any map mapping or log expression that references a secret (SECRET_IN_MESSAGE_WRITE), as well as any secret name missing from the store (UNKNOWN_SECRET). Custom host functions can read secrets via Ctx::secret or an Expr config field (which middleware layers see redacted as null). If you need to compute a value derived from a secret (such as an HMAC signature), do so inside a custom host function. See Secrets for details.
Reloading Definitions
An Engine holds its compiled program and configuration behind an Arc. To hot-reload workflows, compile the new definitions using engine.compiler()—which reuses the registered functions, operators, and secrets—and swap in the new program with with_program:
use Engine;
use ;
use Value;
/// Returns a new `Engine` running `definition`. The original `engine`
/// is unchanged and continues serving any in-flight messages.
Because each workflow compiles independently, you can quarantine invalid workflows while still loading valid ones. You can also call Compiler::check to collect all issues (including advisories) for pre-save validation in an editor.
Execution Tracing & Observability
Enable tracing on a run via RunOptions::trace, and the returned Run will include a Trace containing the initial context followed by a step record for every task execution, skip, or failure along with its exact context changes. By replaying those changes, you can reconstruct the message context after any step without paying the memory cost of full message snapshots. TraceOptions lets you configure timings, change capture, path redaction, and a maximum byte budget.
use TraceOptions;
use ;
async
For lightweight, always-on metrics rather than per-request traces, attach an Observer. It is invoked synchronously for every task (including built-ins), and its Interest flags control which events it receives—if Interest::TIMINGS is not requested, the engine skips per-task clock reads.
use ;
use EngineConfig;
use ;
use Value;
use Arc;
use ;
/// Builds an engine over `definitions` that reports every run to `metrics`.
You can also attach an observer to a single run with RunOptions::observer. When neither an observer nor a trace is active, there is no observability or timing overhead on the execution path.
Visualize & Debug Rules
Because rules are standard JSON, the React UI can render them directly: JSONLogic expressions are displayed as interactive flow diagrams, and the visual debugger runs messages through the engine and steps through traces by replaying context changes at each task. If a run fails or stops early, the debugger highlights the status and the failing step.
Ecosystem
| Package | Description | Install |
|---|---|---|
| dataflow-rs | Core rules engine in Rust (this crate) | cargo add dataflow-rs |
| @goplasmatic/dataflow-wasm | WebAssembly bindings for browsers and Node.js with end-to-end TypeScript types | npm i @goplasmatic/dataflow-wasm |
| @goplasmatic/dataflow-ui | React components for rule visualization, editing, and step-by-step trace debugging | npm i @goplasmatic/dataflow-ui |
| datalogic-rs | JSONLogic compiler and evaluator used internally | cargo add datalogic-rs |
📖 Documentation: User Guide & API Reference · Interactive Playground · Visual Debugger
Migrating from 3.x
Existing 3.x definitions load through the compat reader, which is enabled by
default. The reader rewrites 3.x spellings into 4.0 equivalents
(continue_on_error and halt_on into on_failure and on_rejection, and
validate into validation) and reports each as a V3_SPELLING Advisory at
the 3.x key. dataflow_rs::compat::migrate_v3 writes a definition out in the
4.0 format. In the Rust API, Engine::run returns a Run on every status in
place of the process_message family, host functions implement Function with
#[derive(FunctionConfig)] in place of AsyncFunctionHandler and
TaskContext, Outcome replaces TaskOutcome, Error replaces
DataflowError, and Message::from_json or Message::from_parts replaces
Message::builder. Wire formats for Message, audit trails, and error records
match 3.x. See Migrating from 3.x.
Contributing
Contributions are welcome:
- Fork the repository and clone your fork
- Run tests:
cargo test --workspace --all-features(what CI runs) andcargo testat the root (the default feature set) - Make changes and add tests for new features
- Run the benchmarks before and after:
cargo run --example benchmark --release, interleaving the two builds - Submit a pull request describing your changes
See CONTRIBUTING.md for the CI checks and CHANGELOG for release history.
About Plasmatic
The Plasmatic team develops dataflow-rs and builds open-source tools for data processing and automation.
License
Apache License, Version 2.0. See LICENSE.