Skip to main content
Think of state as shared memory for your workflow.

When to Use State

Use state when:
  • Multiple agents need access to the same data
  • You’re tracking workflow progress
  • You need to accumulate results across agents
  • Prop drilling becomes cumbersome
Don’t use state for:
  • Simple data passing between adjacent agents (use outputs instead)
  • Data that only one agent needs
  • Temporary calculations

Basic State

Define Schema

Read State

Write State

State Patterns

Pattern 1: Accumulator

Build up results across agents:

Pattern 2: Configuration State

Share configuration across agents:

Pattern 3: Error Tracking

Track errors across the workflow:

Pattern 4: Multi-Step Context

Build context across multiple AI calls:

State vs Outputs

Use Outputs For

Simple data passing between adjacent agents:

Use State For

Data needed by multiple non-adjacent agents:

State Persistence

KV-Backed State

Persist state across executions:

D1-Backed State

For complex queries and relationships:

State Scoping

Ensemble-Level State

Shared across all agents in the ensemble:

Agent-Level State

Each agent has its own state (for custom agents):

Best Practices

  1. Minimize State Usage - Use outputs for simple data passing
  2. Clear Schema - Define types explicitly
  3. Declare Dependencies - Always use use: and set:
  4. Persist When Needed - Use KV/D1 for long-running workflows
  5. Avoid Circular Dependencies - Don’t create state loops
  6. Initialize State - Provide defaults (|| 0, || [])
  7. Test State Logic - Unit test state transformations
  8. Monitor State Size - Keep state compact

Performance Considerations

State Access Cost

Reading state is fast (in-memory):

State Write Cost

Writing to persistent backends has latency:
Tip: Batch state writes at the end of the workflow rather than after each agent.

Debugging State

Log State Changes

Output State

Include state in ensemble output for debugging:

Next Steps

Flow Control

Control execution flow

A/B Testing

Test multiple variants

Operations

Learn about operations

Playbooks

Real-world examples