@catalogicus-international/n8n-nodes-flow-state
v0.2.4
Published
Redis-backed, schema-validated flow sessions and state change events for n8n
Maintainers
Readme
n8n-nodes-flow-state
Redis-backed, schema-validated flow sessions for n8n. The package provides the action node Flow State and the event node Flow State Trigger.
Requirements
Both nodes require Flow State Redis API credentials (host, port, optional database/user/password/SSL, and a key prefix). All state and events live in Redis, so sessions survive process restarts and are shared across n8n instances, including queue-mode workers, that point at the same Redis.
Runtime guarantees and limits
Session state and the id index are stored in Redis. A successful mutation atomically checks the current optimistic version, writes the new record, and publishes an event — all in one Lua call — then returns a new stateRef containing sessionId, sessionKey, and version. Two mutations using the same version cannot both succeed; the loser receives version_conflict.
Sessions have a TTL and terminal retention window. A sweeper emits session.expired when an active session's TTL elapses; a small grace is added to the native Redis key TTL so the sweeper observes and emits expiry before the key is garbage-collected. Events are delivered via Redis Pub/Sub and carry a full session/step snapshot, so a Flow State Trigger in a different process receives them with the requested Output Detail. Pub/Sub has no durable log or replay: do not use events as the only mechanism for critical domain writes; invoke those directly after a successful Transition or Complete.
Compiled JSON-schema validators are cached per process (rebuilt from the session's stored model) and are never persisted or transmitted.
Models and step data
Each created session stores an independent model snapshot; later edits to node parameters do not change existing sessions. Fields mode is convenient for separately configured nodes such as Start Customer Order and Start Shipment. JSON mode can also receive a canonical model from an expression. There is no central model registry, and the package contains no Telegram-specific or domain model.
Create Session accepts a model in two input modes. Fields is the default UI builder and remains compatible with existing workflows. JSON accepts one canonical FlowModel object containing flowId, modelVersion, initialStep, and steps.
Within either model input mode, every step uses one of the same schema modes offered by n8n's When Executed by Another Workflow node:
fieldsdefines optional, named top-level fields and their types. Unknown fields are rejected. Supported types areany,string,number,boolean,array, andobject.jsonExampleinfers those same top-level fields and types from an example object. Every inferred type also acceptsnull, so an unavailable value can be represented explicitly; anullexample value means any type.passthroughaccepts any JSON object data without field restrictions.
For example, the JSON model for a single terminal step is:
{
"flowId": "customer_order",
"modelVersion": "1",
"initialStep": "done",
"steps": {
"done": {
"id": "done",
"label": "Done",
"terminal": true,
"requiredForCompletion": false,
"allowedNextSteps": [],
"schemaMode": "jsonExample",
"jsonExample": {
"message": "example",
"metadata": null
}
}
}
}A JSON expression may return this object directly; a JSON string is accepted as well. Step IDs and schema modes are explicit—there is no shortened or inferred model format.
The canonical JSON contract is validated before a session is created:
flowIdis a non-empty string;modelVersionis an integer or non-empty string;initialStepis a string naming a key insteps.stepsis an object keyed by step ID, not an array. Every step has a matching stringid, stringlabel, booleanterminalandrequiredForCompletion, string-arrayallowedNextSteps, andschemaModeequal tofields,jsonExample, orpassthrough.- Fields definitions contain only a string
nameand a supportedtype. Fields are optional and names must be unique. - JSON Example mode requires an object. It uses
[email protected]to infer the same top-level field types as When Executed by Another Workflow; nested object and array contents are not constrained. Inferred fields remain optional and accept either their inferred type ornull, while unknown fields are rejected.
Values are not coerced. For example, "terminal": "false", "allowedNextSteps": "done", or "steps": [] are invalid rather than being interpreted. Malformed models raise a node parameter error; with Continue On Fail enabled, the input item is preserved and receives the error message. A valid model defines the graph and validation rules, while session step data is the mutable JSON collected while traversing that graph.
Central gateway
A central inbound workflow can build a stable key, run Resolve with an external event ID, route on flowState.session.flowId and currentStep, and call a specialized sub-workflow. Duplicate event IDs return duplicate without changing the session.
Code to Patch
const input = $input.first().json;
return [{ json: {
...input,
patchData: { entityType: 'company', criteria: { name: 'Ромашка', inn: '5610000000' } },
} }];Configure the next Flow State node with Operation Patch, State Reference ={{ $json.stateRef }}, and Patch Data ={{ $json.patchData }}. The node preserves the item and replaces its top-level stateRef with the new version.
Object-valued expressions must occupy the entire JSON field. Do not add whitespace or other text outside the expression. For example, use ={{ { messageText: $json.telegram.messageText } }} rather than embedding that expression in a larger string. If an n8n version still converts the object to [object Object], use ={{ JSON.stringify({ messageText: $json.telegram.messageText }) }} as a compatible fallback. Flow State also recovers whole-field expressions from the node's original parameters when n8n exposes those parameters at execution time.
Multiple workflows and sub-workflows
One workflow can Create Session, another can Resolve it, and sub-workflows can Patch or Transition it as long as every execution runs in the same process and passes the latest stateRef. Handle version_conflict by resolving or inspecting again and making a domain-specific retry decision; never blindly replay a mutation.
Trigger
Flow State Trigger selects one event entity (Step or Session) and then one event from that entity. Step events are Patched and Transitioned; session events are Created, Completed, Cancelled, and Expired. It can additionally filter flow IDs, current/previous step IDs, a session-key prefix, and the status of the current step. All configured filters are applied together. Only Actual Data Changes additionally suppresses step.patched events whose change.changedPaths is empty; it does not affect other event types.
A valid no-op Patch is still a successful mutation: it increments the optimistic step and session versions and emits step.patched by default. Use Only Actual Data Changes when consumers do not need those events. Use Emit Event = false on Patch, Transition, Complete, or Cancel when the mutation must not emit an event at all.
Output detail can be metadata only, the current step, or the full public session. Step and session detail are captured when the committed event is published, so a later or re-entrant mutation cannot change the event's snapshot. Every subscriber receives isolated values. Models, processed event IDs, and compiled validators are never included. Correlation and causation IDs are propagated.
To launch a sub-workflow only when data in an active step actually changes, configure a workflow as follows:
- Add Flow State Trigger with
Event Entity = Step,Event = Patched,Current Step Status = Active,Only Actual Data Changes = true, andOutput Detail = Current Step. - Connect it to n8n's Execute Sub-workflow node and turn off
Wait for Sub-Workflow Completion. - Accept the complete event item in the sub-workflow. It includes
eventId,stateRef,flowId,currentStep,change.changedPaths, and the currentstepsnapshot.
Each matching patch starts a separate execution, so use eventId as an idempotency key and do not assume that concurrent sub-workflows finish in event order. If the sub-workflow patches the same session, set Emit Event = false on that mutation or apply an explicit causation guard to prevent a feedback loop.
TTL and capacity
Active TTL defaults to 30 minutes and terminal retention to 5 minutes. Access extends active TTL. Cleanup runs before operations and every 30 seconds. Expired active sessions emit session.expired. The default capacity is 10,000 records; expired records and then old tombstones are removed before an active session is rejected with capacity_exceeded. Active sessions are never evicted for capacity.
Storage
State is backed by Redis via the Flow State Redis API credential. Keys are namespaced by the credential's key prefix (flowstate by default): {prefix}:session:{sessionKey} holds the record, with companion {prefix}:ver:* and {prefix}:status:* keys used for atomic version checks, {prefix}:id:{sessionId} as the reverse index, and {prefix}:events as the Pub/Sub channel. The public stateRef contract is unchanged from earlier in-memory versions.
