Use Azure Event Grid in C#: A Complete Guide with Example

In modern cloud-based applications, different services often need to communicate with each other when something happens, such as a new order being created, a file being uploaded, or a customer registering on a website.

Instead of continuously checking for changes, applications can use an event-driven architecture to notify other services when these events occur. Azure Event Grid is a fully managed event routing service provided by Microsoft Azure that enables applications and Azure services to communicate through events.

In this article, we will explore what Azure Event Grid is, how it works, and its key components. We will also learn how to integrate Azure Event Grid with a C# application using a practical example, including creating an Event Grid topic, publishing custom events, and receiving and processing those events in an application.

What Is Azure Event Grid?

Azure Event Grid is a fully managed event routing service provided by Microsoft Azure that enables applications and Azure services to communicate with each other using events. It follows an event-driven architecture, where an event is generated when something happens in a system and is delivered to interested subscribers for further processing.

For example, when a customer places an order in an e-commerce application, the application can publish an OrderCreated event to Azure Event Grid. Event Grid routes this event to subscribed services, such as an email notification service, an order processing service, or an inventory management system. Each subscriber can then perform its task independently without requiring the original application to communicate directly with every service.

Azure Event Grid supports events from Azure services, custom applications, and other supported event sources. Developers can route these events to destinations such as Azure Functions, webhooks, and other supported Azure services.

Why Use Azure Event Grid?

Without an event routing service, an application might need to call multiple services whenever an important action occurs. This creates tight coupling between components and makes the application more difficult to maintain as it grows.

Azure Event Grid simplifies this process by allowing the publisher to emit an event without needing to know which services will consume it. Event Grid handles routing, while subscribers independently process the events they receive.

For C# developers, Azure Event Grid provides SDKs and APIs to publish custom events and integrate event-driven workflows into .NET applications. This makes it useful for building loosely coupled applications, automating workflows, and responding to changes in real time.

Key Components of Azure Event Grid

Azure Event Grid consists of several components that work together to capture, route, and deliver events from event sources to interested subscribers. Understanding these components helps you integrate Azure Event Grid with a C# application effectively.

  1. Event

    An event represents a change or an occurrence in a system. It contains information about what happened, when it happened, and the resource or object associated with the occurrence.

  2. Event Source

    An event source is the system or application where an event originates. It generates events when specific actions or changes occur.

  3. Topic

    A topic is an endpoint where events are published. It acts as a logical entry point for events from one or more related event sources.

  4. Event Subscription

    An event subscription defines which events a subscriber wants to receive and where those events should be delivered.

  5. Event Handler

    An event handler is the destination that receives and processes events delivered by Azure Event Grid.

    • Azure Functions
    • Webhooks
    • Azure Logic Apps
    • Other supported Azure services
  6. Event Publisher

    An event publisher is the application or service that sends events to an Event Grid topic.


Steps to Create an Event Grid Topic in Azure

An Azure Event Grid Topic is an endpoint where an application or Azure service publishes events. Other services can subscribe to the topic and receive notifications when specific events occur.

For example, in a C# application, you can publish a CustomerCreated event to an Event Grid Topic and configure a subscriber, such as an Azure Function, to process that event.

Prerequisites
  1. An active Azure subscription.
  2. Access to the Azure portal.
  3. Permission to create Event Grid resources in your Azure resource group.

Steps to Create an Event Grid Topic

The following steps will guide you through creating an Event Grid topic in the Azure portal.

  1. Open the Azure portal
    • Navigate to the Azure portal.
    • Sign in using your Azure account.
    • Search for Event Grid Topics in the search bar.
    • Select Event Grid Topics from the search results.
  2. Create an Event Grid Topic
    • Click + Create.
    • Select your Azure subscription.
    • Choose an existing resource group or create a new one.
    • Enter a unique name for the topic, such as customer-events-topic.
    • Select the Azure region where you want to deploy the resource.
  3. Review and create the topic
    • Select Review + create.
    • Wait for Azure to validate the configuration.
    • If validation succeeds, click Create.
    • Wait for the deployment to complete.
    • Select Go to resource to open your newly created Event Grid topic.
  4. Verify the Event Grid Topic

    On the topic's Overview page, verify that the resource was created successfully. You can view details such as Topic endpoint. The topic endpoint is the URL to which your application publishes events.

  5. Copy the topic endpoint and access key
    • Open your Event Grid topic.
    • On the Overview page, copy the Topic Endpoint.
    • Select Access keys from the left navigation menu.
    • Copy an access key for authentication if you are using local key authentication.
  6. Create an event subscription
    • Open your Event Grid topic.
    • Select + Event Subscription.
    • Enter a name, such as customer-events-subscription.
    • Choose an event schema and an endpoint type, such as Azure Function or Web Hook.
    • Configure the destination endpoint.
    • Select Create.

Create a C# Application to Publish Events to Azure Event Grid

Azure Event Grid allows developers to publish events and route them to interested subscribers, helping build loosely coupled, scalable, and responsive applications. It supports event-driven workflows by delivering events from event sources to appropriate handlers, such as Azure Functions, Webhooks, and other supported Azure services.

In this example, we will create a C# console application that publishes custom events to an Azure Event Grid Topic using the Azure SDK.

We will use a practical example in which a customer registration application publishes a CustomerCreated event. Azure Event Grid receives the event and routes it to any configured event subscribers, such as an Azure Function.

What you need
  • An Azure subscription.
  • An Event Grid topic already created in the Azure portal.
  • The topic endpoint and an access key for authentication.
  • Visual Studio or the .NET CLI.

Create a C# Application to Publish Events
  1. Create a C# console application
  2. Install the required NuGet package
    </> Bash
      dotnet add package Azure.Messaging.EventGrid
      
    
  3. Get the Event Grid Topic endpoint and key
    • Open your Event Grid topic.
    • Copy the Topic Endpoint from the Overview page.
    • Select Access keys.
    • Copy Key1.
  4. Write the C# code to publish an event
    </> C#
    using System;
    using System.Threading.Tasks;
    using Azure;
    using Azure.Messaging.EventGrid;
    class Program
    {
      static async Task Main(string[] args)
      {
        // Event Grid Topic endpoint
        string topicEndpoint =
        "https://YOUR-TOPIC-REGION.eventgrid.azure.net/api/events";
        // Event Grid Topic access key
        string topicKey = "YOUR-EVENT-GRID-ACCESS-KEY";
        // Create the Event Grid publisher client
        EventGridPublisherClient client =
        new EventGridPublisherClient(
        new Uri(topicEndpoint),
        new AzureKeyCredential(topicKey));
        // Define the event data
        var customerData = new
        {
          CustomerId = 101,
          CustomerName = "John",
          Email = "john@example.com"
          };
          // Create an Event Grid event
          EventGridEvent customerCreatedEvent =
          new EventGridEvent(
          subject: "customers/101",
          eventType: "CustomerCreated",
          dataVersion: "1.0",
          data: customerData
          );
          try
          {
            // Publish the event
            await client.SendEventAsync(customerCreatedEvent);
            Console.WriteLine(
            "CustomerCreated event published successfully.");
          }
          catch (Exception ex)
          {
            Console.WriteLine(
            $"Failed to publish event: {ex.Message}");
          }
        }
      }
    

    This example uses the Event Grid event schema and the topic's access key. Replace the sample endpoint and key with the values from your Azure resource.

  5. Understand the event structure
    • Subject: Identifies the event source or affected entity. Example: customers/101
    • EventType: Describes what happened. Example: CustomerCreated
    • DataVersion: Specifies the version of the event data structure. Example: 1.0
    • Data: Contains the actual event payload. Example: Customer ID, name, and email.
  6. Run the application
    If publishing succeeds, you should see:
    
        CustomerCreated event published successfully.
        
    

    A successful response means Azure Event Grid accepted the event. It does not guarantee that a subscriber has processed it.

  7. Verify event delivery
    • Open your Event Grid topic in the Azure portal.
    • Confirm that an event subscription exists.
    • Configure an endpoint, such as an Azure Function or webhook.
    • Check the subscriber's logs to verify that it received the CustomerCreated event.
    Event Grid delivers events to configured subscribers; creating a topic alone does not automatically provide a receiver.

For a quick demonstration, a topic access key is convenient. Do not commit access keys to source control or hardcode them in production applications. Store secrets in configuration backed by a secure secret store, such as Azure Key Vault. For production workloads, consider Microsoft Entra ID authentication with the EventGrid Data Sender role.

Next step: You can create an Azure Function that subscribes to this topic and processes the CustomerCreated event, completing the publisher-to-subscriber workflow.

Error Handling, Retries, and Dead-Lettering in Azure Event Grid

When integrating Azure Event Grid with a C# application, handling errors is essential to ensure reliable event publishing and delivery. Network failures, temporary service interruptions, and unavailable subscriber endpoints can prevent events from being processed successfully.

Azure Event Grid provides retry mechanisms and dead-lettering capabilities to help handle delivery failures. Your C# publisher should also handle exceptions when sending events to Azure.

1. Error Handling in C#

When publishing an event, errors can occur because of invalid credentials, an incorrect topic endpoint, network issues, or service-side failures.

Use try-catch to handle exceptions and log useful information.
</> C#
try
{
  await client.SendEventAsync(customerCreatedEvent);
  Console.WriteLine("Event published successfully.");
}
catch (Azure.RequestFailedException ex)
{
  Console.WriteLine(
  $"Azure error: {ex.Status} - {ex.Message}");
}
catch (Exception ex)
{
  Console.WriteLine($"Unexpected error: {ex.Message}");
}

Important: A successful publish means Event Grid accepted the event. It does not mean the subscriber has successfully processed it.

2. Retry handling in the C# publisher

If publishing fails because of a temporary network issue or service interruption, your application can retry the request. However, avoid retrying every error indefinitely.

The following example implements a simple retry policy with exponential backoff:
</> C#
using System;
using System.Threading.Tasks;
using Azure;
using Azure.Messaging.EventGrid;
static async Task PublishWithRetryAsync(
EventGridPublisherClient client,
EventGridEvent eventToPublish)
{
  int maxAttempts = 3;
  for (int attempt = 1; attempt <= maxAttempts; attempt++)
  {
    try
    {
      await client.SendEventAsync(eventToPublish);
      Console.WriteLine("Event published successfully.");
      return;
    }
    catch (RequestFailedException ex)
    {
      Console.WriteLine(
      $"Attempt {attempt} failed: {ex.Status} - {ex.Message}");
      // Do not retry typical permanent client errors.
      if (ex.Status >= 400 && ex.Status < 500 &&
      ex.Status != 408 && ex.Status != 429)
      {
        throw;
      }
      if (attempt == maxAttempts)
      throw;
      int delaySeconds = (int)Math.Pow(2, attempt);
      await Task.Delay(
      TimeSpan.FromSeconds(delaySeconds));
    }
  }
}
Call the method using:
</> C#
await PublishWithRetryAsync(client, customerCreatedEvent);

This example waits 2 seconds and then 4 seconds between attempts. It is a simplified illustration; production retry logic should account for throttling, Retry-After headers, cancellation, and transient network exceptions.

The Azure SDK may also perform retries internally, so avoid stacking aggressive retry policies. In addition, retrying a publish after an uncertain network failure can produce duplicate events. Use a stable event ID and make event processing idempotent.

3. Retry policy in Azure Event Grid

Azure Event Grid has its own retry mechanism for delivering events to subscribers. This is different from the retries your C# application uses to publish events.

For a standard Event Grid Topic, delivery retries use a best-effort backoff schedule. The default delivery window is up to 24 hours or 30 attempts, depending on which limit is reached. Certain permanent HTTP errors, such as 400, 403, and 413, aren't retried for webhook destinations.

  1. HTTP response: 200–204
    • Typical Event Grid behavior: Delivery acknowledged.
  2. HTTP response: 400 Bad Request
    • Typical Event Grid behavior: Not retried for webhook destinations.
  3. HTTP response: 401 Unauthorized
    • Typical Event Grid behavior: Not retried for webhook destinations.
  4. HTTP response: 403 Forbidden
    • Typical Event Grid behavior: Not retried for webhook destinations.
  5. HTTP response: 408 Request Timeout
    • Typical Event Grid behavior: Retried.
  6. HTTP response: 429 Too Many Requests
    • Typical Event Grid behavior: Retry behavior depends on the service response.
  7. HTTP response: 500 or 503
    • Typical Event Grid behavior: Retried according to the retry policy.

4. Dead-lettering in Azure Event Grid

Dead-lettering stores events that Event Grid cannot successfully deliver to a subscriber in an Azure Blob Storage container. This allows you to investigate and recover events instead of losing them when delivery fails.

For example, suppose your CustomerCreated event is published successfully, but the subscriber's endpoint has been deleted. If dead-lettering is configured, Event Grid can store the undelivered event in Blob Storage.

Configure dead-lettering in the Azure portal
  1. Create an Azure Storage Account.
  2. Create a Blob Storage container, for example, eventgrid-deadletters.
  3. Open your Event Grid topic in the Azure portal.
  4. Select the event subscription you want to configure.
  5. Open its delivery settings or create a new subscription.
  6. Enable dead-lettering under Additional features.
  7. Select the Storage Account and Blob container.
  8. Configure the required managed identity and permissions if using identity-based access.
  9. Save the configuration.

5. Recover and reprocess dead-lettered events When an event is stored in the dead-letter container, you can:
  • Inspect the event payload and delivery failure details.
  • Correct the subscriber configuration or application bug.
  • Replay the event to the intended processing system.
  • Record the recovery result for auditing.

Best practices

  1. Use try-catch and structured logging in the C# publisher.
  2. Apply bounded retries with exponential backoff for transient publishing failures.
  3. Configure Event Grid's delivery retry limits and dead-letter storage.
  4. Monitor failed deliveries and dead-lettered events.
  5. Make subscribers idempotent because duplicate delivery is possible.
  6. Secure topic credentials and use managed identity where appropriate.
  7. Test failure scenarios, including unavailable endpoints and invalid credentials.

Summary

Azure Event Grid is a powerful event-driven service that enables applications to communicate through events in a scalable, reliable, and loosely coupled manner. It allows developers to build event-driven architectures by routing events from publishers to subscribers without requiring them to communicate directly.

In this article, we explored what Azure Event Grid is, how it works, its key components, and how it differs from Azure Event Hubs. We also learned how to create an Event Grid topic in the Azure portal, publish events from a C# application, configure event subscriptions, and handle incoming events. Additionally, we covered error handling, retries, dead-lettering, and security best practices.

By integrating Azure Event Grid with C#, you can build responsive and scalable applications that react to events such as customer registration, order processing, file uploads, and changes to Azure resources.

If you are developing event-driven applications on Azure, Azure Event Grid is an excellent choice for efficiently distributing events between different services. Combining it with other Azure services, such as Azure Functions, Azure Service Bus, and Azure Storage, can help you build flexible and maintainable cloud solutions.

Thanks

Kailash Chandra Behera

I am an IT professional with over 12 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال