State Management

State Management

The Matrix Framework provides a robust distributed property system for managing state across services.

Property System

Distributed Properties

Properties can be synchronized across services using the distributed property system:

<ServiceNode Name="OrderSystem">
    <ServiceNode.State>
        <!-- Define distributed state -->
        <DistributedState>
            <Property Name="OrderCount" 
                     Type="int" 
                     Default="0" />
            <Property Name="ActiveOrders" 
                     Type="List<Order>" />
        </DistributedState>
    </ServiceNode.State>
</ServiceNode>

Change Notification

Services can observe and react to state changes:

public class OrderProcessor : ServiceNode
{
    protected override void Initialize()
    {
        // Watch for state changes
        WatchState("OrderCount", OnOrderCountChanged);
        WatchState("ActiveOrders", OnActiveOrdersChanged);
    }

    private async Task OnOrderCountChanged(
        PropertyChangedContext context)
    {
        var oldValue = context.OldValue<int>();
        var newValue = context.NewValue<int>();
        
        // React to change
        await UpdateMetrics(oldValue, newValue);
    }
}

State Synchronization

Consistency Models

Choose appropriate consistency for your state:

<ServiceNode Name="InventorySystem">
    <ServiceNode.State>
        <!-- Strong consistency for critical state -->
        <DistributedState Mode="Strong">
            <Property Name="StockLevels" 
                     Type="Dictionary<string, int>" />
        </DistributedState>
        
        <!-- Eventual consistency for metrics -->
        <DistributedState Mode="Eventual">
            <Property Name="AccessMetrics" 
                     Type="MetricsData" />
        </DistributedState>
    </ServiceNode.State>
</ServiceNode>

State Access

Access distributed state safely:

public class InventoryManager : ServiceNode
{
    public async Task UpdateStock(string productId, int delta)
    {
        // Get state accessor
        var stockLevels = GetState<Dictionary<string, int>>(
            "StockLevels");
            
        // Update state atomically
        await stockLevels.UpdateAsync(levels =>
        {
            if (!levels.ContainsKey(productId))
                levels[productId] = 0;
                
            levels[productId] += delta;
        });
    }
}

Best Practices

  1. State Design

    • Choose appropriate consistency models
    • Define clear state boundaries
    • Document state dependencies
    • Version state contracts
  2. Change Management

    • Handle state transitions atomically
    • Validate state changes
    • Log state modifications
    • Monitor state health
  3. Performance

    • Cache frequently accessed state
    • Batch state updates
    • Monitor synchronization lag
    • Profile state access patterns