Building Real-Time Event-Driven Microservices with .NET 8, Dapr, and Azure Event Grid

Mahmut Sarıkaya 5 min read 1 Views 0
Building Real-Time Event-Driven Microservices with .NET 8, Dapr, and Azure Event Grid

Why Real-Time Event-Driven Microservices Matter

Imagine an e‑commerce platform that must react to a shopping cart update within milliseconds, otherwise the user experience suffers and revenue is lost. According to the 2023 Cloud Native Survey, 68% of organizations cite latency as the top barrier to scaling microservices. An event‑driven architecture addresses that pressure by decoupling producers from consumers and allowing each service to process only the events it cares about.

When you combine .NET 8’s performance improvements with Dapr’s sidecar model and Azure Event Grid’s global distribution, you obtain a stack that can handle thousands of events per second while keeping code simple and testable.

Core Components: .NET 8, Dapr, and Azure Event Grid

.NET 8 introduces native support for minimal APIs, AOT compilation, and improved async pipelines, which reduces CPU cycles per request by up to 15% compared with .NET 6. Dapr (Distributed Application Runtime) adds building blocks such as pub/sub, state stores, and service invocation without locking you into a specific vendor. Azure Event Grid acts as a fully managed event routing service that guarantees at‑least‑once delivery and supports custom topics, filters, and dead‑letter handling.

The three pieces fit together like this: a .NET 8 microservice publishes an event to Dapr’s pub/sub component, Dapr forwards the payload to an Azure Event Grid topic, and any number of downstream .NET services subscribe to that topic via Dapr bindings. This pattern eliminates direct HTTP calls between services and enables true real‑time processing.

Setting Up the Development Environment

Before writing code, ensure you have the following:

  • Windows 11 or Ubuntu 22.04 with at least 8 GB RAM.
  • .NET 8 SDK (download from dotnet.microsoft.com).
  • Dapr CLI (install with brew install dapr/tap/dapr on macOS or wget -q https://raw.githubusercontent.com/dapr/cli/master/install/install.sh | /bin/bash on Linux).
  • Azure CLI (v2.50+) and an active Azure subscription.

Initialize Dapr locally with the Azure Event Grid component:

dapr init --components-path ./components

Create a components/eventgrid.yaml file that points to your Event Grid topic endpoint and key. This file will be referenced by the .NET services.

Creating a Minimal .NET 8 Service with Dapr

The following example shows a minimal API that receives an order, stores it (omitted for brevity), and publishes an order-created event. The WithTopic extension registers the endpoint as a Dapr subscriber, so the same service can also react to events from other producers.

using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Dapr.Client;  var builder = WebApplication.CreateBuilder(args); builder.Services.AddDaprClient();  var app = builder.Build();  app.MapPost("/orders", async (Order order, DaprClient dapr) => {     await dapr.PublishEventAsync("pubsub", "order-created", order);     return Results.Created($"/orders/{order.Id}", order); }).WithTopic("pubsub", "order-created");  app.Run();  public record Order(int Id, string Product, int Quantity); 

Notice the generic PublishEventAsync call – Dapr handles JSON serialization automatically, and the pubsub name matches the component defined in components/eventgrid.yaml.

Publishing Events to Azure Event Grid

Behind the scenes Dapr uses the Azure Event Grid binding you configured. When the service calls PublishEventAsync, Dapr translates the request into a REST call to https://{topic-endpoint}/api/events with the appropriate authentication header. Azure Event Grid then fans out the event to every registered subscriber, applying any filter rules you defined in the portal.

To verify delivery, you can create a simple subscriber that writes the event payload to the console. Use the Dapr CLI to run both services side by side:

dapr run --app-id order-service --app-port 5000 --components-path ./components dotnet run dapr run --app-id inventory-service --app-port 5001 --components-path ./components dotnet run

When you POST an order to http://localhost:5000/orders, you will see the inventory service log the incoming event within milliseconds.

Consuming Events with Dapr Subscriptions

A subscriber can be any .NET 8 service that declares a matching topic. The following snippet demonstrates a background worker that processes order-created events and updates a SQL Server table. Dapr injects the event payload directly into the method parameter.

app.MapSubscribeHandler();  app.MapPost("/process-order", async (Order order, ILogger logger) => {     // Simulate database update     logger.LogInformation($"Processing order {order.Id} for {order.Product}");     await Task.Delay(100); // pretend DB call     return Results.Ok(); }).WithTopic("pubsub", "order-created"); 

The MapSubscribeHandler endpoint is required for Dapr to discover the subscription metadata at runtime. Azure Event Grid guarantees at‑least‑once delivery, so your handler should be idempotent – for example, check if the order already exists before inserting.

Best Practices and Performance Tips

1. **Leverage AOT compilation** – .NET 8’s native AOT reduces cold‑start latency for containerized services by up to 30%. Add in your project file and rebuild.

2. **Configure Dapr retries** – The default retry policy is three attempts with exponential back‑off. For high‑value events, increase maxRetries to five and set deadLetterTopic to capture failures.

3. **Use Event Grid filters** – By adding a subjectBeginsWith filter, you can route only order-created events to inventory while other services listen to order‑canceled.

4. **Monitor with Azure Monitor** – Enable diagnostic settings on the Event Grid topic to stream metrics such as IngressEvents and DeliveryFailures to Log Analytics. Correlate those logs with Dapr sidecar metrics for end‑to‑end visibility.

Conclusion

Building real‑time event‑driven microservices with .NET 8, Dapr, and Azure Event Grid transforms a monolithic codebase into a resilient, scalable ecosystem. The minimal API model keeps the service footprint tiny, Dapr abstracts the plumbing, and Event Grid guarantees low‑latency delivery across regions. By following the steps above—setting up the environment, publishing events, and handling subscriptions—you can launch a production‑ready architecture within a single afternoon.

Author: Mahmut Sarıkaya — sarikayadev.com

Sources

  • Microsoft .NET 8 Documentation
  • Dapr Official Documentation
  • Azure Event Grid Documentation
Tags: #.NET 8 #Dapr #Azure Event Grid #event-driven architecture #microservices
Share:
M

Written by

Mahmut Sarıkaya

Software Developer

Comments

No comments yet. Be the first to share your thoughts!

Leave a Comment

7 + 0 =