Skip to main content
This page covers common patterns for building robust graph workflows. Read the Graph Workflows page first for core API concepts.

Conditional branching

A node can route to different next nodes based on the current state. Return next() with the appropriate nodeId:
nextNodes is used only by graph.toMermaid() to draw diagram edges. It is not enforced at runtime — any string is a valid nodeId in a next() call, as long as a node with that ID is registered in the Graph.

Error handling in nodes

Node errors propagate out of graph.run() as normal exceptions. Wrap the run() call to catch and handle them:

Error recovery inside a node

To recover from an error within a node (rather than letting it propagate), catch it in run() and transition to a dedicated error-handling node:

State design patterns

Keep state flat and serialisable

Graph state is JSON-serialised when you use FileStatePersistence. Avoid storing class instances, functions, or Date objects — use plain primitives, arrays, and objects.

Immutable state transitions

Always spread the previous state when building the next one. BaseNode.run() receives the state by value, but adopting an immutable style prevents subtle bugs, especially when nodes are used in multiple branches.

Carrying error context through state

Add an optional error field to your state type so error nodes can surface details in the final output:

Cycle prevention

By default, the Graph throws MaxGraphIterationsError if any single node is visited more than 100 times. Adjust this with the maxIterations option:
For intentional retry loops, track the attempt count in state and transition to an error node when the limit is reached:

Step-by-step inspection with runIter()

Use graph.runIter() to inspect or log state between every node transition. This is useful for debugging and for human-in-the-loop workflows:

Resumable runs with persistence

Combine FileStatePersistence with a stable graphId to make a graph resumable across process restarts. The graph saves state after each node and resumes from the last checkpoint on restart:
For testing, use MemoryStatePersistence to avoid writing files:

Graph Workflows

Core Graph API: BaseNode, Graph, runIter, toMermaid

Human in the Loop

Pause and resume patterns with ApprovalRequiredError