Azure Functions Durable Entities: Stateful Serverless

Serverless is typically stateless. Durable Functions changed that with orchestrations. Now, “Durable Entities” brings the Actor Model (similar to Akka or Orleans) to Azure Functions, allowing you to define small, stateful objects that persist across calls.

Defining an Entity

[JsonObject(MemberSerialization.OptIn)]
public class Counter
{
    [JsonProperty("value")]
    public int Value { get; set; }

    public void Add(int amount) => this.Value += amount;
    public void Reset() => this.Value = 0;
    public int Get() => this.Value;

    [FunctionName(nameof(Counter))]
    public static Task Run([EntityTrigger] IDurableEntityContext ctx)
        => ctx.DispatchAsync<Counter>();
}

Signaling an Entity

Entities are addressed by ID. Signals are one-way (fire and forget) writes.

[FunctionName("HttpStart")]
public static async Task<IActionResult> Run(
    [HttpTrigger] HttpRequest req,
    [DurableClient] IDurableEntityClient client)
{
    var entityId = new EntityId(nameof(Counter), "myCounter");
    
    // Asynchronous signal
    await client.SignalEntityAsync(entityId, "Add", 1);
    
    // Read state
    var state = await client.ReadEntityStateAsync<Counter>(entityId);
    
    return new OkObjectResult(state.EntityState.Value);
}

Key Takeaways

  • Use Entities for aggregating state from streams (e.g., IoT device counters).
  • Automatic locking ensures thread safety for operations.
  • State persists in Azure Storage automatically.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.