Lesson 3 of 4 Serverless APIs with Azure Functions

Using Triggers and Bindings for Data and Messaging

This lesson explains messaging and data triggers, input and output bindings, identity-based connections and how failures are retried.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the behaviour of the Service Bus trigger.
  • Explain why the Event Grid-based Blob trigger is preferred.
  • Describe identity-based connection settings.
  • Explain where failed items end up for each trigger.

Messaging triggers

The Service Bus trigger runs a function for each message in a queue or subscription. The runtime receives in peek-lock mode and completes the message when the function succeeds or abandons it when the function throws; after the entity's maximum delivery count, the message moves to the dead-letter queue. The Event Grid trigger runs for each event delivered by an Event Grid subscription, and the Event Hubs trigger processes batches of events from a stream.

@app.service_bus_queue_trigger(arg_name="msg", queue_name="embed-jobs", connection="ServiceBus")
@app.cosmos_db_output(arg_name="out", database_name="retail", container_name="embeddings",
                      connection="CosmosDB")
def embed_job(msg: func.ServiceBusMessage, out: func.Out[func.Document]) -> None:
    job = json.loads(msg.get_body().decode())
    vector = embed(job["text"])
    out.set(func.Document.from_dict({"id": job["documentId"], "embedding": vector}))

In this example the Service Bus trigger starts the function and a Cosmos DB output binding writes the result: assigning the document with out.set() is all the code needed to store it.

True or false

The Service Bus trigger

Exam skills 3.2.1 · 3.1.1

Decide whether each statement about the Service Bus trigger is true.

Log in to try this activity Interactive activities are free with an account.

Data triggers and bindings

Data services provide triggers that react to changes and bindings that read and write data.

ServiceTriggerInput bindingOutput binding
Cosmos DBChange feed (with a lease container)Read an item by id and partition key, or run a queryCreate or upsert documents
Blob StorageNew or updated blobRead a blobWrite a blob
Storage queuesNew queue messageNoneAdd a queue message
Service BusMessage in a queue or subscriptionNoneSend a message
Event GridDelivered eventNonePublish an event
TimerNCRONTAB scheduleNoneNone

The Blob trigger deserves care. Its original implementation polls the container, which can delay detection on large containers; the recommended form uses an Event Grid source (source=func.BlobSource.EVENT_GRID), which reacts within seconds, and it is the only form supported on the Flex Consumption plan. Input bindings can use expressions from the trigger, such as id="{doc_id}" from an HTTP route, so the function receives the item without writing query code.

Scenario questions

Choosing triggers and bindings

Exam skills 3.2.1

Choose the trigger or binding that fits each requirement.

Log in to try this activity Interactive activities are free with an account.

Connections and identities

Each trigger and binding has a connection property naming a prefix of app settings, not a connection string. With a connection string, the setting with that name holds it. With an identity-based connection, settings with the prefix and a double underscore describe the service, and the function app's managed identity provides the credential, so no secret is stored.

ServiceIdentity-based setting (prefix ServiceBus, CosmosDB, Storage)Example value
Service BusServiceBus__fullyQualifiedNamespaceNAMESPACE.servicebus.windows.net
Cosmos DBCosmosDB__accountEndpointhttps://ACCOUNT.documents.azure.com:443/
Blob StorageStorage__blobServiceUrihttps://ACCOUNT.blob.core.windows.net
Host storageAzureWebJobsStorage__accountNameACCOUNT

For a user-assigned identity, the settings also include __credential set to managedidentity and __clientId with the identity's client ID. The identity needs the right data roles, such as Azure Service Bus Data Receiver for a Service Bus trigger or a Cosmos DB data plane role for Cosmos DB bindings.

The following diagram shows a function's trigger, its two output bindings and the identity settings in a document pipeline.

A document pipeline built from bindings on Flex Consumption. A Blob trigger with an Event Grid source starts the function, a Cosmos DB output binding stores the embedded chunks, and a Service Bus output binding sends the notification. Each connection uses identity-based settings, and the function app's managed identity holds the data roles.
ACCOUNT and NAMESPACE stand for the resource names.
Match the pairs

Identity-based connection settings

Exam skills 3.2.1 · 3.2.2

Match each identity-based app setting with the value it holds.

Log in to try this activity Interactive activities are free with an account.

Failures, retries and poison messages

What happens when a function throws depends on the trigger, because each source has its own delivery semantics. The table summarizes the behaviour that exam scenarios rely on.

TriggerOn failureWhere failed items end up
Service BusMessage abandoned and redeliveredDead-letter queue after the maximum delivery count
Storage queueMessage becomes visible againA -poison queue after five attempts by default
Event GridDelivery reported as failed; Event Grid retriesThe subscription's dead-letter container, if configured
Cosmos DBThe batch can be retried with a retry policyNowhere by default; catch errors and record failed items
TimerThe next run happens on scheduleNot applicable

Function-level retry policies (fixed delay or exponential backoff) are supported for a few triggers, such as timer, Event Hubs and Cosmos DB, which have no built-in redelivery. For triggers with their own redelivery, such as Service Bus and queues, the service's settings control retries. In every case handlers should be idempotent, because at-least-once delivery means repeats.

Match the pairs

Where failures end up

Exam skills 3.2.1

Match each trigger with where repeatedly failing items end up.

Log in to try this activity Interactive activities are free with an account.
Worked example

A document pipeline with bindings

When a PDF is uploaded to Blob Storage, its text must be extracted, embedded and stored in Cosmos DB, and a message must be sent to a Service Bus topic for downstream consumers. The function app runs on Flex Consumption and must not store any connection strings.

The function uses a Blob trigger with an Event Grid source, which Flex Consumption requires, a Cosmos DB output binding for the embedded chunks, and a Service Bus output binding for the notification. Each connection names a prefix with identity-based settings such as Storage__blobServiceUri, CosmosDB__accountEndpoint and ServiceBus__fullyQualifiedNamespace, and the function app's managed identity holds Storage Blob Data Reader, a Cosmos DB data role and Azure Service Bus Data Sender.

A polling Blob trigger is not supported on Flex Consumption. A timer function that lists blobs would add latency and cost. Connection strings in app settings, even as Key Vault references, would still be secrets that identity-based connections avoid.

Check yourself

Which app setting tells a Service Bus trigger with connection="ServiceBus" to use the app's managed identity?

Show answer

ServiceBus__fullyQualifiedNamespace, set to NAMESPACE.servicebus.windows.net. With no connection string, the runtime uses the managed identity.

Exam Tips

Remember for the exam

  • The Service Bus trigger completes on success and abandons on failure; poison messages reach the DLQ.
  • Use the Event Grid-based Blob trigger; it is the only Blob trigger on Flex Consumption.
  • connection names a setting prefix; identity-based settings use __fullyQualifiedNamespace, __accountEndpoint or __blobServiceUri.
  • Retry policies apply to triggers without redelivery, such as timer, Event Hubs and Cosmos DB.