Azure Functions and Event Grid Integration

Introduction

Azure Functions and Azure Event Grid are powerful services that can be combined to create robust, event-driven architectures. Event Grid acts as a fully managed event routing service that enables you to easily build applications with decoupled event handling. Azure Functions provide a serverless compute platform that can react to these events.

This document explores how to leverage Event Grid to trigger Azure Functions, allowing for scalable and responsive event processing.

Core Concepts

Azure Event Grid

Event Grid is a pub/sub eventing service. It allows you to subscribe to events from various Azure services (and custom sources) and route those events to event handlers. Key components include:

Azure Functions

Azure Functions offer an event-driven, serverless compute experience. You can write code that responds to a wide variety of triggers, including HTTP requests, timers, and importantly, events from Azure services like Event Grid.

Integrating Functions with Event Grid

The most common way to integrate Azure Functions with Event Grid is by using the Event Grid Trigger for your Function App. This trigger allows your function to be invoked automatically when an event matching a configured subscription is published to Event Grid.

Diagram showing Event Grid triggering an Azure Function

Simplified architecture: Event Source -> Event Grid -> Azure Function

Setting up an Event Grid Trigger

You can configure an Event Grid trigger in several ways:

  1. Azure Portal: When creating or configuring an Azure Function, select the "Event Grid trigger" as the type. You'll then need to set up an Event Subscription in Event Grid to point to this function.
  2. Azure CLI / PowerShell: Use commands to create Event Subscriptions programmatically, specifying the Function App endpoint as the destination.
  3. ARM Templates / Bicep: Define your Event Grid subscriptions and Function App configurations in infrastructure-as-code.

Example: Responding to Blob Creation Events

Let's consider a scenario where you want to process an image whenever it's uploaded to an Azure Blob Storage container.

1. Configure Event Grid for Blob Storage

In Azure Blob Storage, you can create an Event Subscription that publishes `Microsoft.Storage.BlobCreated` events to Event Grid.

2. Create an Azure Function with an Event Grid Trigger

Create an Azure Function (e.g., in C#, Node.js, Python) with the Event Grid trigger. The function will receive an array of Event Grid events.

Example (C#):


using Microsoft.Azure.WebJobs;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

public static class EventGridBlobTrigger
{
    [FunctionName("ProcessBlobEvent")]
    public static void Run(
        [EventGridTrigger] EventGridEvent[] events,
        ILogger log)
    {
        log.LogInformation($"Processing {events.Length} events.");

        foreach (EventGridEvent eventGridEvent in events)
        {
            log.LogInformation($"Subject: {eventGridEvent.Subject}");
            log.LogInformation($"Event Type: {eventGridEvent.EventType}");
            log.LogInformation($"Event Time: {eventGridEvent.EventTime}");

            // Deserialize the event data
            var blobInfo = JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());

            if (blobInfo != null)
            {
                log.LogInformation($"Blob URI: {blobInfo.Url}");
                log.LogInformation($"Blob Type: {blobInfo.ContentType}");
                // Add your image processing logic here
            }
        }
    }

    // Helper class to deserialize blob event data
    public class StorageBlobInfo
    {
        public string Id { get; set; }
        public string Subject { get; set; }
        public string Url { get; set; }
        public string IsDirectory { get; set; }
        public string Kind { get; set; }
        public string ETag { get; set; }
        public string ContentType { get; set; }
        public string ContentLength { get; set; }
        public string OperationName { get; set; }
        public string SourceSystem { get; set; }
        public string StorageDiagnostics { get; set; }
    }
}
        

Example (Python):


import logging
import json
import azure.functions as func

def main(events: list) -> None:
    logging.info(f"Processing {len(events)} events.")

    for event in events:
        logging.info(f"Subject: {event.get('subject')}")
        logging.info(f"Event Type: {event.get('eventType')}")
        logging.info(f"Event Time: {event.get('eventTime')}")

        data = event.get('data')
        if data:
            logging.info(f"Blob URI: {data.get('url')}")
            logging.info(f"Blob Type: {data.get('contentType')}")
            # Add your image processing logic here

        
Important: The `EventGridTrigger` in Azure Functions can receive a batch of events. Your function code should be designed to handle one or more events in a single invocation.

Event Handling Patterns

Key Considerations

Advanced Scenarios