Creating a Stateful Service in Azure Service Fabric

Creating a Stateful Service in Service Fabric

After learning about Stateless services, it’s time to understand and create a Stateful Service in Service Fabric. Stateful services are powerful because they maintain data consistency across replicas without needing an external database!

🌟 What is a Stateful Service?

A Stateful Service maintains internal state across client requests. Service Fabric itself ensures the data is replicated, consistent, and available even during node failures.

  • Examples: Shopping cart data, Game session state, IoT device telemetry processors.
  • Provides automatic high availability via replicas.
Real-World Analogy:

Think of a library system — every time you borrow or return a book, your data (borrow history) is stored carefully and replicated to avoid loss.

🛠️ Prerequisites

  • Service Fabric SDK installed.
  • Cluster running (local or Azure).
  • Visual Studio installed.

🚀 Step-by-Step Guide: Create and Deploy a Stateful Service

Step 1: Create a New Service Fabric Application
  1. Open Visual Studio.
  2. File → New → Project → Search Service Fabric Application.
  3. Name it StatefulAppDemo (or your choice).
  4. Click Create.
Step 2: Add a Stateful Service
  1. In the service selection window, choose: Stateful Service (C# Worker).
  2. Click OK.
Step 3: Understand the Generated Code
  • The service class inherits from:
    public class YourServiceName : StatefulService
                
  • Important Overridden Methods:
    • CreateServiceReplicaListeners: Setup listeners for client communication.
    • RunAsync: Main execution loop for background tasks.
  • StateManager: Built-in object for handling reliable dictionaries and queues (auto-replicated).
Step 4: Working with StateManager

Example of using a reliable dictionary to store key-value pairs:

var myDictionary = await StateManager.GetOrAddAsync>("myDictionary");

using (var tx = StateManager.CreateTransaction())
{
    await myDictionary.AddOrUpdateAsync(tx, "counter", 0, (key, value) => value + 1);
    await tx.CommitAsync();
}
    
Step 5: Build and Deploy the Application
  • Build the solution.
  • Publish to Local or Azure Cluster (Right-click → Publish).
Step 6: Monitor the Service
  • Open Service Fabric Explorer.
  • Check your Application → Service → Partitions → Replicas.
  • Healthy replicas indicate successful deployment and state replication.

📈 Visual Flow Summary

[Create New SF App] 
    → [Add Stateful Service] 
        → [Work with StateManager]
            → [Build and Publish]
                → [Monitor Replicas]
    

💡 Did You Know?

Even if 2 nodes crash simultaneously, Service Fabric can heal and restore state from remaining replicas automatically!

⚡ Common Beginner Issues and Solutions

  • Problem: Replica drop or 'Not Ready' status.
    Solution: Check if VM resources are sufficient. Add more nodes if needed.
  • Problem: State not persisted.
    Solution: Ensure you call CommitAsync() after modifying state inside transactions.
  • Problem: Slow service start.
    Solution: Avoid expensive blocking operations inside RunAsync().

🚨 Best Practices

  • Use batching when writing a lot of data to StateManager (commit multiple operations together).
  • Design idempotent operations to survive service restarts and retries.
  • Keep service instances lightweight — move heavy processing to external queues if needed.

✅ Self-Check Quiz

  • What is the purpose of the StateManager?
  • Why do we need CommitAsync() inside transactions?
  • What happens if a primary replica fails?