Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 22 of 28
❮Prev Next❯

Azure Event Grid: Custom Events, Filters and Retries

Module 3: Messaging & Functions ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    Azure Event Grid pushes small events ("a blob was created", "a summary is ready") to handlers such as Azure Functions, webhooks and Service Bus. You publish your own events to a custom topic with EventGridPublisherClient, using the CloudEvents 1.0 or Event Grid schema. An event subscription picks the handler and uses filters (event types, subject begins with / ends with, advanced filters on data). If delivery fails, Event Grid retries with backoff, by default up to 30 attempts within 1,440 minutes (24 hours), then drops the event unless dead-lettering to a storage container is set.

    Simulate it » No Azure account needed

    Exam objective: 3.1.2 Implement event-driven workflows by using Azure Event Grid, including filters, custom events, and retries. (Skills measured as of October 7, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Custom topic and a filtered event subscription Create a custom topic and an event subscription with filters and retries.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    Open <strong>Event Grid Topics</strong> and select <strong>+ Create</strong>. A custom topic receives your own events.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. Open Event Grid Topics and select + Create. A custom topic receives your own events.
    2. Name and region are enough. On Advanced the schema defaults to Cloud Event Schema v1.0.
    3. Review and Create.
    4. The topic needs at least one event subscription to deliver anything. Select + Event Subscription.
    5. Send events to the index_document function. Event Grid pushes each event to it.
    6. On Filters, only subjects ending in .pdf get through. A .tmp file is dropped before it reaches your code.
    7. If the function is down, Event Grid retries with back-off for up to 24 hours, then writes the event to a dead-letter blob container.
    8. Publish report.pdf and scratch.tmp. One matched and was delivered; the other was filtered out.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    A function polls storage every minute for new files.

    😊 THE SOLUTION

    Let Event Grid push a “blob created” event the moment it happens.

    • Polling wastes money✓ Push events
    • Every file triggers work✓ Subject filters
    • Handler is down✓ Retries and dead-lettering
    🛠️ Solved with: Azure Event Grid

    Start with a question

    How does your app know a new file arrived without checking every few seconds?

    You could stand at the front door and open it every minute to see if the courier is there. Or you could fit a doorbell. The courier rings, you answer, and the rest of the day you get on with your work.

    Polling Blob Storage for new files is standing at the door. Azure Event Grid is the doorbell. When something happens, like a PDF being uploaded or your own app finishing a summary, Event Grid pushes a small event to whoever subscribed, and filters make sure only the right doorbells ring.

    Explain it like I’m 10

    Visual: Event Grid in motion

    Here’s a blob upload turning into an event, getting filtered, retried and finally dead-lettered.

    ▶ Explainer video See it in motion 8 steps · 1 min 32 sec

    An animation of Azure Event Grid. contract-88.pdf is created in Blob Storage, which publishes a small BlobCreated event to a system topic. An event subscription filtered to subjects ending in .pdf pushes it to an Azure Function, while a draft.tmp event is dropped by the filter. When the function returns 503, Event Grid retries with growing gaps, up to 30 attempts or 24 hours by default, then writes the event to a dead-letter blob container. It ends by contrasting an event with a Service Bus message.
    Read the video script
    1. Something happensA PDF called contract-88 lands in the contracts container. Nobody's polling the folder. Storage just knows something happened.
    2. An event is a small factStorage publishes an event, a small fact: a blob was created, here's its subject and URL. The PDF doesn't travel. The event only points to it.
    3. Into a topicThe event goes to a topic. Azure services publish to system topics, and your own apps publish to custom topics.
    4. Filters choose what gets throughAn event subscription links the topic to a handler and holds the filters. This one only wants subjects ending in .pdf. It matches, so Event Grid pushes it to the function.
    5. A .tmp file? DroppedThen someone saves draft.tmp. It's a blob created event too, but it doesn't end in .pdf, so the subscription drops it. Your function never wakes up.
    6. 503? Back off and retryThe next PDF arrives while the function is returning 503. Event Grid waits and tries again, after ten seconds, thirty, a minute, five, with longer gaps each time.
    7. Limits, then dead-letterBy default it stops after thirty attempts or twenty-four hours, whichever comes first. With a dead-letter container set, the event lands there with the reason. Without one, it's dropped.
    8. An event, not a messageThat's the difference. An event announces a fact and doesn't care who listens. A Service Bus message carries work that a receiver pulls, locks and settles.

    The technical explanation

    Event Grid has three moving parts:

    • Sources publish events to a topic. Azure services publish to system topics (Blob Storage, Key Vault, Resource groups and more). Your apps publish to custom topics.
    • Event subscriptions connect a topic to a handler and hold the filters, retry policy and dead-letter settings.
    • Handlers receive the push: Azure Functions, webhooks (any HTTPS endpoint), Service Bus queues and topics, Storage queues, Event Hubs and Relay hybrid connections.

    Delivery is push and at-least-once, so a handler might see the same event twice. Use the event id to ignore repeats. Event Grid also has namespace topics that support pull delivery and MQTT, but the classic push model below is what most event-driven Azure apps use.

    Two schemas

    CloudEvents 1.0Event Grid schema
    Who defines itCNCF open standardMicrosoft
    Key fieldsid, source, type, subject, time, data, specversionid, topic, subject, eventType, eventTime, data, dataVersion
    Good forNew apps, portable across clouds and toolsOlder integrations that already expect it

    You choose the input schema when you create a custom topic, and you publish in that schema. Microsoft recommends CloudEvents for new work.

    Publish a custom event in Python

    Install azure-eventgrid and azure-identity. Give your app the EventGrid Data Sender role on the topic, or use the topic’s access key with AzureKeyCredential if you must.

    import os
    from azure.identity import DefaultAzureCredential
    from azure.core.messaging import CloudEvent
    from azure.eventgrid import EventGridPublisherClient
    
    client = EventGridPublisherClient(
        os.environ["EVENTGRID_TOPIC_ENDPOINT"],   # https://<topic>.<region>-1.eventgrid.azure.net/api/events
        DefaultAzureCredential(),
    )
    
    client.send([
        CloudEvent(
            source="/contoso/summariser",
            type="Contoso.Docs.SummaryReady",
            subject="contracts/contract-88.pdf",
            data={"docId": "contract-88", "summaryUrl": "summaries/contract-88.json"},
        )
    ])

    For a topic that uses the Event Grid schema, send EventGridEvent(subject=..., event_type=..., data=..., data_version="1.0") from azure.eventgrid instead.

    Filters on the event subscription

    FilterExampleUse it to
    Event typesMicrosoft.Storage.BlobCreated onlyIgnore deletes and other events
    Subject begins with/blobServices/default/containers/contracts/Limit to one container or folder
    Subject ends with.pdfLimit to one file type
    Advanced filtersdata.pages NumberGreaterThan 20, data.tier StringIn premiumMatch on fields inside the event data

    Subject matching is case-insensitive unless you turn on case-sensitive subject matching. Advanced filters have operators for numbers, strings, booleans and null checks, and an event must pass every filter on the subscription.

    az eventgrid event-subscription create \
      --name contracts-to-func \
      --source-resource-id $STORAGE_ID \
      --endpoint-type azurefunction --endpoint $FUNCTION_ID \
      --included-event-types Microsoft.Storage.BlobCreated \
      --subject-begins-with /blobServices/default/containers/contracts/ \
      --subject-ends-with .pdf \
      --max-delivery-attempts 10 --event-ttl 120 \
      --deadletter-endpoint $STORAGE_ID/blobServices/default/containers/eg-deadletter

    Retries and dead-lettering

    If the handler doesn’t return success, Event Grid waits and tries again with exponential backoff. The retry policy on each subscription has two limits, and whichever is hit first ends the retries:

    • Max delivery attempts: 1 to 30, default 30.
    • Event time to live: 1 to 1,440 minutes, default 1,440 (24 hours).

    Some failures aren’t retried at all, such as 400 Bad Request and 413 Request Entity Too Large, because trying again won’t help. When retries end, the event is dropped unless you set a dead-letter destination: a blob container in a storage account, where Event Grid writes the undelivered event as JSON with the reason.

    1. 1 Happen

      contract-88.pdf is created in the contracts container.

    2. 2 Filter

      Type is BlobCreated, subject ends with .pdf: it matches. A .tmp file wouldn't.

    3. 3 Push

      Event Grid calls the function. If it returns 503, Event Grid backs off and retries.

    4. 4 Land

      Success, or after the retry limits, the event goes to the dead-letter container.

    A .pdf upload on its way to a function

    Webhook validation

    Event Grid won’t send events to a random URL until the endpoint proves it wants them. With the Event Grid schema, it first posts a Microsoft.EventGrid.SubscriptionValidationEvent containing a validationCode; your endpoint returns {"validationResponse": "<code>"}, or someone opens the validationUrl in the event within a few minutes. With CloudEvents, Event Grid sends an HTTP OPTIONS request with WebHook-Request-Origin, and your endpoint replies with WebHook-Allowed-Origin. Azure Functions with the Event Grid trigger, Logic Apps and Service Bus handlers don’t need you to code any of this.

    Architect level Event Grid or Service Bus?

    Use Event Grid when the publisher just announces facts and doesn’t care who listens: it’s cheap, push-based and fans out to many handlers with filters. Use Service Bus when the payload is work that must be processed, when the receiver needs to control the pace (pull, peek-lock), or when you need ordering, sessions or transactions.

    They combine well. A common pattern is Event Grid delivering BlobCreated events into a Service Bus queue: Event Grid handles the filtering and the push, and the queue gives your workers peek-lock, a dead-letter queue and a buffer for bursts.

    Real-world business scenario

    Insurance

    Contoso Insurance (fictional)

    The problem
    A claims app checked Blob Storage every 30 seconds for new photos, paying for thousands of list calls a day and still making customers wait for damage assessments.
    What they used
    An Event Grid system topic on the storage account, with an event subscription filtered to BlobCreated and subject ends with .jpg, pushing to an Azure Function that calls a vision model. The function then publishes a custom Contoso.Claims.Assessed CloudEvent to a custom topic that the notifications team subscribes to. Dead-lettering goes to an eg-deadletter container.
    Why that choice
    Events arrive within seconds with no polling, filters keep thumbnails and temp files out, and dead-lettering means no claim photo is silently skipped during an outage.
    The result
    Assessments start as soon as a photo lands, the polling cost is gone, and the operations team reviews the dead-letter container after any incident.

    When to use it and when not to

    ✓ Use it when…

    • You want to react to changes in Azure resources (blobs, Key Vault secrets, resource groups) without polling.
    • Your app needs to announce its own events to several handlers that may change over time.
    • Each handler wants only some events, selected by type, subject or data fields.

    ✕ Think twice when…

    • The receiver must pull at its own pace with locks and settlement. Use Service Bus.
    • You need strict ordering or transactions across messages.
    • You stream large volumes of telemetry for analytics and replay. Use Event Hubs.

    ↔ Alternatives to consider

    • Azure Service Bus for commands and work items that must be processed.
    • Azure Event Hubs for high-throughput event streaming.
    • Event Grid into a Service Bus queue when you want both push filtering and a buffer.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    An Azure Function must run only when a file with the .pdf extension is created in the contracts container of a storage account. Other files and other containers must not invoke the function. What should you configure on the Event Grid event subscription?

    Question 2

    Question 2 of 5

    An event subscription uses the default retry policy. The webhook handler is unavailable. Which statement describes how Azure Event Grid behaves?

    Question 3

    Question 3 of 5

    A custom topic delivers events to a webhook. Events that cannot be delivered after all retry attempts must be retained for later analysis.

    What should you configure?

    Question 4

    Question 4 of 5

    A Python application must publish custom events to an Event Grid custom topic that uses the CloudEvents 1.0 input schema. The application authenticates by using Microsoft Entra ID. Which code should you use?

    Question 5

    Question 5 of 5

    You create an Event Grid subscription that delivers events in the Event Grid schema to a custom HTTPS endpoint. The subscription remains in a failed state and no events are received. What is the most likely cause?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner What's the difference between an event and a message?

    Model answer

    An event is a notification that something happened, like "invoice-42.pdf was uploaded". The publisher doesn't care who reacts or what they do. A message is usually a command or a piece of work, like "summarise invoice-42", and the sender expects someone to process it. Event Grid is built for events, Service Bus for messages.

    Intermediate How would you make sure only PDF uploads in the contracts folder trigger your function?

    Model answer

    On the event subscription I'd filter the event type to Microsoft.Storage.BlobCreated, set subject begins with /blobServices/default/containers/contracts/ and subject ends with .pdf. Then the function never even sees a .tmp file or an upload to another container.

    Experienced developer What does Event Grid do when your handler is down?

    Model answer

    It retries with exponential backoff. By default it tries up to 30 times within 24 hours, and you can lower either value on the subscription. Some errors, like 400 Bad Request or 413, aren't retried. When it gives up, the event is dropped unless I've set a dead-letter destination, which is a blob container in a storage account.

    Scenario You created a webhook subscription and it's stuck failing with a validation error. What would you check?

    Model answer

    The webhook has to answer Event Grid's validation handshake. With the Event Grid schema it must echo the validationCode back as validationResponse, or someone has to open the validationUrl. With CloudEvents it must reply to the OPTIONS request with the WebHook-Allowed-Origin header. If I point the subscription at an Azure Function with the Event Grid trigger instead, the handshake is handled for me.

    Quick revision

    Key points

    • Event Grid pushes events to handlers. Topics receive events, event subscriptions route them.
    • Custom topics take your own events. Use CloudEvents 1.0 (recommended) or the Event Grid schema.
    • Publish in Python with EventGridPublisherClient and DefaultAzureCredential (EventGrid Data Sender role) or the topic key.
    • Filters - event types, subject begins with / ends with, advanced filters on data fields.
    • Retry defaults - 30 attempts, 1,440-minute TTL, exponential backoff. Dead-letter to a blob container.

    Important terminology

    Event
    A small record that says something happened, with a type, subject, time and a little data. It's a fact, not a command.
    Custom topic
    An Event Grid endpoint your own app publishes events to.
    System topic
    A topic that represents events from an Azure service, such as Blob Storage or Key Vault.
    Event subscription
    The rule that says which events from a topic go to which handler, with filters, retry policy and dead-letter settings.
    CloudEvents 1.0
    An open, vendor-neutral event schema from the CNCF that Event Grid supports alongside its own Event Grid schema.
    Subject filter
    An event subscription filter on the start or end of the event subject, such as ends with .pdf.
    Dead-lettering
    Saving events that couldn't be delivered to an Azure Storage blob container instead of dropping them.
    Validation handshake
    The check Event Grid runs when you subscribe a webhook, to prove the endpoint agrees to receive events.

    Common mistakes

    • Thinking Event Grid stores events for you to pull later. Standard topics push, and drop what can't be delivered unless dead-lettering is on.
    • Building a plain webhook and forgetting the validation handshake.

    Exam tips

    • "React when a .jpg lands in a container" = Event Grid with a subject ends with filter.
    • "Don't lose events the handler couldn't accept" = dead-letter to a storage blob container.
    • "Stop retrying sooner" = lower max delivery attempts or event time to live on the subscription.

    Five quick revision questions

    1. 1.What is the default maximum number of delivery attempts?Show

      30.

    2. 2.What is the default event time to live for retries?Show

      1,440 minutes (24 hours).

    3. 3.Where are dead-lettered events stored?Show

      In an Azure Storage blob container.

    4. 4.Which Python class publishes events to a custom topic?Show

      EventGridPublisherClient.

    5. 5.Which two schemas can a custom topic accept (besides a custom input schema)?Show

      Event Grid schema and CloudEvents 1.0.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Azure Functions: Serverless APIs with Triggers and Bindings

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.