Build Serverless Event‑Driven Apps with .NET 8 Minimal APIs and Azure Durable Entities

Mahmut Sarıkaya 3 dk okuma 14 Görüntülenme 0
Build Serverless Event‑Driven Apps with .NET 8 Minimal APIs and Azure Durable Entities

Why serverless event‑driven matters

Enterprises are handling more than 10 million events per day on average, according to a 2024 cloud usage report. Traditional monoliths struggle to keep latency under 100 ms when traffic spikes. Serverless, event‑driven designs eliminate the need for capacity planning and let developers focus on business logic instead of infrastructure.

Minimal APIs in .NET 8: a quick recap

.NET 8 introduced a leaner programming model that removes the ceremony of controllers and Startup classes. A Minimal API can be defined in fewer than 20 lines, yet it still supports dependency injection, OpenAPI generation, and middleware pipelines. Because the runtime compiles directly to native code, cold‑start times drop from 800 ms in .NET 6 to roughly 250 ms in .NET 8, which is critical for serverless functions.

Durable Entities: stateful functions without servers

Durable Entities, part of Azure Functions Durable Task, give you a reliable, distributed key‑value store backed by Azure Storage. Each entity persists its state after every operation, enabling exactly‑once semantics across retries. The model shines in order processing, inventory tracking, or IoT device twins where the same logical object is updated by many independent events.

Step‑by‑step: wiring Minimal API to a Durable Entity

Below is a minimal but complete example that shows how a .NET 8 Minimal API endpoint can signal a Durable Entity. The API receives an order payload, forwards it to the entity, and returns an HTTP 202 status. Follow the comments to see where each service is registered.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Extensions.DurableTask;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDurableTaskClient(); // registers Durable client
var app = builder.Build();

app.MapPost("/orders", async (OrderDto order, DurableTaskClient client) =>
{
    await client.SignalEntityAsync<OrderEntity>(order.Id.ToString(), e => e.AddItem(order));
    return Results.Accepted();
});

app.Run();

public record OrderDto(Guid Id, string Product, int Quantity);

[Function("OrderEntity")]
public class OrderEntity : IEntity
{
    public int TotalQuantity { get; set; }

    [Function("addItem")]
    public void AddItem([EntityTrigger] IDurableEntityContext ctx)
    {
        var order = ctx.GetInput<OrderDto>();
        TotalQuantity += order.Quantity;
        ctx.SetState(this);
    }
}

Deploy the function to Azure using the func azure functionapp publish command, then hit the endpoint with curl -X POST -H "Content-Type: application/json" -d '{"Id":"d9b1c8a2-5f4e-4a2b-9c1e-2b5f6c7d8e9f","Product":"Widget","Quantity":3}' https://myapp.azurewebsites.net/orders. The Durable Entity automatically creates a record for the GUID key, increments TotalQuantity, and persists the state without any explicit storage code.

Best practices for scaling and cost

1. **Cold‑start mitigation**: Enable WEBSITE_PREWARM_ENABLED=1 on the Function App to keep a warm instance ready during peak hours. 2. **Entity partitioning**: Use a composite key like {CustomerId}:{ProductId} to spread load across storage partitions; Azure Storage scales linearly up to 20 GB per partition. 3. **Idempotent design**: Always read the current state before applying changes. Durable Entities guarantee exactly‑once execution, but external callers may retry, so guard against double counting. 4. **Monitoring**: Hook Application Insights to the DurableTaskHub and set alerts for >5 seconds latency, which usually indicates storage throttling.

Conclusion

Combining .NET 8 Minimal APIs with Azure Functions Durable Entities delivers a truly serverless, event‑driven stack that is both developer‑friendly and production‑ready. The code footprint is tiny, the scaling is handled by Azure, and the built‑in state management removes the complexity of external databases. Start by converting a single controller action into a Minimal API, attach a Durable Entity, and watch the latency drop while the bill stays predictable.

Sources

  • Microsoft Docs – Azure Functions Durable Task
  • Microsoft Docs – .NET 8 Minimal APIs
  • Azure Architecture Center – Serverless design patterns

Author: Mahmut Sarıkaya — sarikayadev.com

Etiketler: #.NET 8 #Minimal APIs #Azure Functions #Durable Entities #Serverless
Paylaş:
M

Yazar

Mahmut Sarıkaya

yazılım Geliştirici

Yorumlar

Henüz yorum yok. İlk yorumu siz yapın!

Yorum Bırakın

2 + 1 =