State Management Template
Maintain context and state across multiple workflow executions. Perfect for multi-step processes, conversational interfaces, long-running operations, and stateful applications.
Time to build: 25 minutes Difficulty: Advanced Perfect for: Multi-step forms, conversational AI, order tracking, progressive workflows
What It Does
Execution 1 → Store state → Execution 2 → Load + update state → Execution 3 → Complete
Workflows remember previous interactions and continue from where they left off.
Step-by-Step
1. Create Workflow
- New workflow → Name it "Multi-Step Onboarding"
- Webhook trigger for user interactions
2. Load Existing State
- Drag Database Query Block
- Connect Webhook to Database
SELECT
state_data,
current_step,
completed_steps,
created_at
FROM workflow_state
WHERE user_id = '<webhook.body.user_id>'
AND workflow_id = '<workflow.id>'
AND status = 'active'
ORDER BY created_at DESC
LIMIT 1
3. Initialize State if New User
- Drag Condition Block
- Connect Database to Condition
Condition: <database.rows_found> > 0
If True: Load existing state
If False: Create new state
4. Create New State (False Path)
- Drag Database Query Block on False path
INSERT INTO workflow_state (
user_id,
workflow_id,
state_data,
current_step,
completed_steps,
status,
created_at
) VALUES (
'<webhook.body.user_id>',
'<workflow.id>',
'{}',
'welcome',
'[]',
'active',
NOW()
) RETURNING id
5. Determine Current Step
- Drag Agent Block to handle routing
Model: GPT-4o-mini
System Prompt:
"Determine the next step in the onboarding process based on state and user input.
Steps in order:
1. welcome - Introduce product
2. profile - Collect user info
3. preferences - Set preferences
4. integration - Connect accounts
5. complete - Finish onboarding
Return ONLY the step name."
User Prompt:
"Current step: <database.current_step>
Completed steps: <database.completed_steps>
User input: <webhook.body.message>"
6. Route to Step Handler
- Drag multiple Condition Blocks for each step
Condition 1 - Welcome:
Condition: <agent.content> == "welcome"
Condition 2 - Profile:
Condition: <agent.content> == "profile"
Condition 3 - Preferences:
Condition: <agent.content> == "preferences"
Condition 4 - Integration:
Condition: <agent.content> == "integration"
Condition 5 - Complete:
Condition: <agent.content> == "complete"
7. Welcome Step Handler
- Drag Agent Block on Welcome path
Model: Claude 3.7 Sonnet
System Prompt:
"Welcome new users and explain the onboarding process. Be friendly and concise."
User Prompt:
"User: <webhook.body.user_id>
State: <database.state_data>"
8. Profile Step Handler
- Drag Agent Block on Profile path
Model: GPT-4o
System Prompt:
"Collect user profile information: name, company, role, team size. Ask one question at a time."
User Prompt:
"State: <database.state_data>
User input: <webhook.body.message>"
Store collected data in state.
9. Preferences Step Handler
- Drag Agent Block on Preferences path
Model: GPT-4o
System Prompt:
"Help user set preferences: notifications, integrations, features. Explain options clearly."
User Prompt:
"State: <database.state_data>
User input: <webhook.body.message>"
10. Integration Step Handler
- Drag HTTP Request Block on Integration path
Method: POST
URL: https://api.yourapp.com/integrations/connect
Body:
{
"user_id": "<webhook.body.user_id>",
"integration_type": "<webhook.body.integration_type>",
"credentials": "<webhook.body.credentials>"
}
11. Complete Step Handler
- Drag Agent Block on Complete path
Model: Claude 3.7 Sonnet
System Prompt:
"Congratulate user on completing onboarding. Summarize their setup and provide next steps."
User Prompt:
"State: <database.state_data>
Profile: <database.state_data.profile>
Preferences: <database.state_data.preferences>"
12. Update State After Each Step
- Drag Database Query Block (connects to all handlers)
UPDATE workflow_state
SET
state_data = jsonb_set(
state_data,
'{<agent.current_step>}',
'<agent.collected_data>'::jsonb
),
current_step = '<agent.next_step>',
completed_steps = jsonb_insert(
completed_steps,
'{-1}',
'"<agent.current_step>"'::jsonb
),
updated_at = NOW()
WHERE user_id = '<webhook.body.user_id>'
AND workflow_id = '<workflow.id>'
AND status = 'active'
13. Check if Workflow Complete
- Drag Condition Block
Condition: <agent.content> == "complete"
If True: Mark workflow as completed
If False: Continue to next step
14. Mark Complete (True Path)
- Drag Database Query Block
UPDATE workflow_state
SET
status = 'completed',
completed_at = NOW()
WHERE user_id = '<webhook.body.user_id>'
AND workflow_id = '<workflow.id>'
15. Send Response with Next Step
- Drag Response Block
{
"user_id": "<webhook.body.user_id>",
"current_step": "<database.current_step>",
"completed_steps": "<database.completed_steps>",
"next_step": "<agent.next_step>",
"message": "<agent.content>",
"progress": "<database.completed_steps.length> / 5 steps",
"state": "<database.state_data>"
}
State Storage Strategies
Database (Recommended)
Pros: Reliable, queryable, persistent
Cons: Requires database
Use for: Production workflows
Memory Tool
Pros: Simple, built-in
Cons: Limited duration
Use for: Short-lived sessions
Redis/Cache
Pros: Fast, ephemeral
Cons: Not durable
Use for: High-traffic workflows
Hybrid Approach
Cache: Hot state (active sessions)
Database: Cold state (inactive sessions)
Best: Performance + reliability
Real-World Examples
E-commerce Checkout
- Step 1: Cart review
- Step 2: Shipping info
- Step 3: Payment method
- Step 4: Order confirmation
- Resume if user abandons cart
Loan Application
- Step 1: Personal info
- Step 2: Employment details
- Step 3: Financial information
- Step 4: Document upload
- Step 5: Review and submit
- Save progress at each step
Customer Support Chat
- Maintain conversation history
- Remember user preferences
- Track issue resolution status
- Seamless handoff between agents
Survey/Quiz Platform
- Track answered questions
- Calculate running score
- Branch based on answers
- Resume incomplete surveys
State Design Patterns
Finite State Machine
States: [created, in_progress, completed, failed]
Transitions: created → in_progress → completed
No backward transitions allowed
Hierarchical State
Main state: onboarding
Sub-states: profile.basic, profile.advanced
Deep state management
Event Sourcing Integration
Store all state changes as events
Rebuild state from event history
Complete audit trail
Advanced Features
State Versioning
- Track state schema version
- Handle migrations gracefully
- Backward compatibility
State Rollback
- Checkpoint important states
- Roll back on errors
- Undo functionality
State Sharing
- Share state across workflows
- User preferences sync
- Team collaboration
State Expiration
- Auto-expire after 30 days
- Archive old states
- Cleanup completed workflows
State Debugging
State Inspector
- View current state in dashboard
- See state history
- Compare state changes
State Validation
- Validate state schema
- Check for corrupted state
- Alert on invalid state
State Replay
- Replay workflow from checkpoint
- Test state transitions
- Debug state issues
Performance Optimization
Lazy Loading
- Load state only when needed
- Cache frequently accessed state
- Reduce database queries
State Compression
- Compress large state objects
- Store diffs instead of full state
- Reduce storage costs
State Sharding
- Shard by user_id
- Distribute across databases
- Scale horizontally
Enhancements
Add State Analytics
- Track completion rates per step
- Identify drop-off points
- Optimize flow based on data
Add State Notifications
- Remind users to complete
- Send progress updates
- Re-engagement campaigns
Add State Export
- Let users download their state
- Data portability
- Compliance with regulations
Add State Sharing
- Share progress with team
- Collaborative workflows
- Multi-user state management
Cost
Per 1,000 state operations:
- Database reads: ~$0.01
- Database writes: ~$0.02
- AI routing: ~$0.20
- Total: ~$0.23
Monthly cost (10,000 users):
- State storage: ~$5-10/month (PostgreSQL)
- Operations: ~$2-5/month
- Total: ~$7-15/month
Next Step
Combine with Event Sourcing for complete audit trail and state replay capabilities!