Skip to main content
The State module provides persistent key-value storage with built-in triggers for reactive state changes. Perfect for application state, user preferences, and cached data.

Configuration

Configure the State module in config.yaml:
config.yaml

Configuration Options

File-based persistent storage:
Or in-memory (development only):

State Concepts

State is organized by scope and key:
  • Scope: Namespace for related data (e.g., ‘users’, ‘config’)
  • Key: Unique identifier within scope (e.g., ‘user_123’, ‘app_settings’)
Example structure:

State Functions

Set

Store a value in state:

Get

Retrieve a value from state:

Delete

Remove a value from state:

Update (Atomic)

Atomically update a value with multiple operations:

List

List all keys in a scope:

List Groups

List all scopes (groups):

Update Operations

Atomic update operations available:

State Triggers

React to state changes automatically:
index.ts

Event Format

State triggers receive events with this structure:

Conditional Triggers

Filter state events with conditions:

Example: User Management

index.ts

Example: Configuration Management

Example: Caching with TTL

Scope Patterns

Recommended scope naming conventions:
  • users - User profiles and data
  • config - Application configuration
  • cache - Temporary cached data
  • sessions - User session data
  • analytics - Analytics counters and stats
  • features - Feature flags

Performance Considerations

  • Use scopes to organize data logically
  • Use atomic updates for concurrent modifications
  • Implement caching for frequently accessed data
  • Use triggers for async processing instead of synchronous updates
  • Consider TTL patterns for temporary data

Data Persistence

With the KvStore adapter using file_based storage:
  • Data persists across restarts
  • Stored in the configured file_path
  • Automatically saved at intervals (configurable in kv_server module)

Best Practices

  1. Use Scopes: Organize data into logical scopes
  2. Atomic Updates: Use state.update for concurrent modifications
  3. Triggers: React to changes asynchronously
  4. Error Handling: Always handle missing keys gracefully
  5. TTL Pattern: Implement expiration for temporary data

Migration from Other Storage

Migrating from another storage system:

Source Code Reference

  • Module: src/modules/state/state.rs:36
  • State functions: src/modules/state/state.rs:254
  • Trigger invocation: src/modules/state/state.rs:110
  • State adapter trait: src/modules/state/adapters/mod.rs