DEV Community

RuturajMaggirwar
RuturajMaggirwar

Posted on

Track changes in API Management using Event Grids

Introduction to Azure Event Grid

Azure Event Grid is a fully managed event routing service in Microsoft Azure that enables seamless integration between event producers and consumers. It supports high-throughput, low-latency communication and provides a reactive programming model to build scalable, event-driven architectures. At its core, Event Grid allows various Azure services, third-party systems, and custom applications to publish and consume events in a decoupled manner. In this blog, we are going to use these features to track changes that occur in API management to see new users that have been added and take any required actions on those new users.

Image description


How Azure Event Grid Works

Azure Event Grid is designed around the concept of event publishers, event handlers (subscribers), and topics:

  • Event Publishers: These are the sources of events. Examples include Azure resources like Blob Storage, Event Hubs, API Management, or custom applications.
  • Event Handlers (Subscribers): These are the endpoints or systems that respond to events. Examples include Azure Functions, Logic Apps, Webhooks, and third-party services.
  • Event Topics: Topics act as a hub where events are published. You can define custom topics or use system topics for Azure resources.

Image description

We are going to utilize Microsoft.ApiManagement.SubscriptionCreated event to track the new users created in API Management and extract key details from those users such as user email, user name, and user last name.


Azure Event Grid in Action

Azure Event Grid acts as the backbone for building reactive, event-driven architectures. When integrated with Azure API Management (APIM), it enables you to monitor key events and automate workflows that respond to changes in your API management system. Here's a detailed breakdown of how Event Grid works with API Management.

In the context of API Management, the event publisher is the API Management service itself. When specific actions occur within API Management (like the creation of a new subscription), API Management generates events and sends them to Event Grid.

Supported events include

  • Microsoft.ApiManagement.SubscriptionCreated: Triggered when a new subscription is created for an API.
  • Microsoft.ApiManagement.SubscriptionDeleted: Triggered when a subscription is deleted.
  • Microsoft.ApiManagement.UserCreated: Triggered when a new user is created in API Management.

Events like SubscriptionCreated are triggered whenever an action occurs in the API Management service. These events are sent to an Event Grid System Topic associated with the API Management instance.

Step-by-Step: API Management and Event Grid Workflow

Create an Azure function that will handle all the triggers from the Event Grid and fill in all the necessary details.

Image description

In the Azure function app, create a new Azure function which will have the code to fetch all the triggers from the Event Grid.

Image description

Configure API Management to Publish Events

  • Go to your API Management instance in the Azure Portal.
  • Navigate to Events under the Settings section.
  • Click + Event Subscription to create a subscription for Microsoft.ApiManagement.SubscriptionCreated event.

Image description

Fill all the details to create the Event Subscription

When creating the event subscription:

  • Event Type: Select Microsoft.ApiManagement.SubscriptionCreated.
  • Endpoint Type: Choose one of the following as the event handler:
  • Azure Function: Serverless logic to handle the event.
  • Logic App: Workflow automation.
  • Webhook: External endpoint for custom processing.
  • Select the Azure function that will receive all the events from the Event Grid and perform all the necessary actions based on the triggers.

Image description

After connecting the Azure Event Grid and the Azure Function App the integration should look like this:

Image description

Enter the code that will fetch the email from the new users that are added in the API Management:

module.exports = async function (context, eventGridEvent) {
    context.log('Received Event:', eventGridEvent);

    try {
        // Extract email from the event data
        const userEmail = eventGridEvent?.data?.user?.email;

        if (!userEmail) {
            throw new Error('Email not found in the event data.');
        }

        context.log('User Email:', userEmail);

        // Respond with the extracted email
        context.res = {
            status: 200,
            body: `User Email: ${userEmail}`,
        };
    } catch (error) {
        context.log('Error observed:', error.message);

        // Respond with error details
        context.res = {
            status: 500,
            body: 'Error observed: ' + error.message,
        };
    }
};

Enter fullscreen mode Exit fullscreen mode

With this, the data from the new users will be fetched and new code can be added to this so that further processing can be carried out.


Key Advantages of Azure Event Grid

  • Decoupled Communication: Event publishers and subscribers don't need to know about each other, allowing independent evolution.
  • High Throughput and Low Latency: Event Grid supports millions of events per second with low latency, making it suitable for real-time scenarios.
  • Serverless Integration: Works seamlessly with Azure Functions, Logic Apps, and other serverless services, enabling quick development and deployment.
  • Flexible Routing: Supports advanced routing capabilities with filtering based on event properties.
  • Scalable: Automatically scales to handle large volumes of events.
  • Built-In Retry Mechanism: Ensures event delivery with retries and dead-lettering for failed deliveries.

Disadvantages of Azure Event Grid

  • Complex Configuration: For beginners, setting up custom topics, subscriptions, and event handlers may feel overwhelming.
  • Cost for High Volume: While cost-effective for moderate usage, handling large volumes of events can lead to higher costs.
  • Dependency on Azure Ecosystem: Though it supports external publishers and handlers, its tight integration with Azure services may limit multi-cloud strategies.
  • Event Size Limitation: The payload size for events is limited to 1 MB, which might be restrictive for some scenarios.

Other Use Cases of Azure Event Grid

  1. Serverless Workflows: Trigger Azure Functions when new blobs are added to Azure Storage or when database records are updated.
  2. Real-Time Notifications: Notify users of application updates or security events.
  3. IoT Data Processing: Process events from IoT devices using Event Grid and route them to processing systems.
  4. Monitoring and Auditing: Track resource changes (e.g., virtual machine creation) and log them for auditing purposes.

Conclusion

Azure Event Grid is a robust, event-driven solution that simplifies building scalable and reactive architectures. It decouples event producers and consumers, ensuring flexibility and scalability in modern cloud applications. While it has some limitations, its advantages—such as seamless serverless integration, real-time event processing, and high throughput—make it an excellent choice for many use cases.

Azure Event Grid simplifies event-driven automation with Azure API Management. This enables you to track key events like Microsoft.ApiManagement.SubscriptionCreated, Event Grid provides real-time visibility and actionable insights into subscription activities. Whether you're notifying users, updating databases, or triggering workflows, Event Grid ensures a scalable, reliable, and efficient event processing pipeline.

By leveraging the integration of API Management and Event Grid, you can create dynamic, automated workflows that improve API lifecycle management and enhance the developer experience.

Top comments (0)