Azure Event Hubs trigger for Azure Functions

This article explains how to work with Azure Event Hubs trigger for Azure Functions. Azure Functions supports trigger and output bindings for Event Hubs.

For information on setup and configuration details, see the overview.

Use the function trigger to respond to an event sent to an event hub event stream. You must have read access to the underlying event hub to set up the trigger. When the function is triggered, the message passed to the function is typed as a string.

Event Hubs scaling decisions for the Consumption and Premium plans are done via Target Based Scaling. For more information, see Target Based Scaling.

For information about how Azure Functions responds to events sent to an event hub event stream using triggers, see Integrate Event Hubs with serverless functions on Azure.

Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.

The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see the Python developer guide.

This article supports both programming models.

Important

The Python v2 programming model is currently in preview.

Example

The following example shows a C# function that logs the message body of the Event Hubs trigger.

[FunctionName("EventHubTriggerCSharp")]
public void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] string myEventHubMessage, ILogger log)
{
    log.LogInformation($"C# function triggered to process a message: {myEventHubMessage}");
}

To get access to event metadata in function code, bind to an EventData object. You can also access the same properties by using binding expressions in the method signature. The following example shows both ways to get the same data:

[FunctionName("EventHubTriggerCSharp")]
public void Run(
    [EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData myEventHubMessage,
    DateTime enqueuedTimeUtc,
    Int64 sequenceNumber,
    string offset,
    ILogger log)
{
    log.LogInformation($"Event: {Encoding.UTF8.GetString(myEventHubMessage.Body)}");
    // Metadata accessed by binding to EventData
    log.LogInformation($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
    log.LogInformation($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
    log.LogInformation($"Offset={myEventHubMessage.SystemProperties.Offset}");
    // Metadata accessed by using binding expressions in method parameters
    log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.LogInformation($"SequenceNumber={sequenceNumber}");
    log.LogInformation($"Offset={offset}");
}

To receive events in a batch, make string or EventData an array.

Note

When receiving in a batch you cannot bind to method parameters like in the above example with DateTime enqueuedTimeUtc and must receive these from each EventData object

[FunctionName("EventHubTriggerCSharp")]
public void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData[] eventHubMessages, ILogger log)
{
    foreach (var message in eventHubMessages)
    {
        log.LogInformation($"C# function triggered to process a message: {Encoding.UTF8.GetString(message.Body)}");
        log.LogInformation($"EnqueuedTimeUtc={message.SystemProperties.EnqueuedTimeUtc}");
    }
}

The following example shows an Event Hubs trigger binding in a function.json file and a JavaScript function that uses the binding. The function reads event metadata and logs the message.

The following example shows an Event Hubs binding data in the function.json file, which is different for version 1.x of the Functions runtime compared to later versions.

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

Here's the JavaScript code:

module.exports = function (context, myEventHubMessage) {
    context.log('Function triggered to process a message: ', myEventHubMessage);
    context.log('EnqueuedTimeUtc =', context.bindingData.enqueuedTimeUtc);
    context.log('SequenceNumber =', context.bindingData.sequenceNumber);
    context.log('Offset =', context.bindingData.offset);

    context.done();
};

To receive events in a batch, set cardinality to many in the function.json file, as shown in the following examples.

{
  "type": "eventHubTrigger",
  "name": "eventHubMessages",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "cardinality": "many",
  "connection": "myEventHubReadConnectionAppSetting"
}

Here's the JavaScript code:

module.exports = function (context, eventHubMessages) {
    context.log(`JavaScript eventhub trigger function called for message array ${eventHubMessages}`);

    eventHubMessages.forEach((message, index) => {
        context.log(`Processed message ${message}`);
        context.log(`EnqueuedTimeUtc = ${context.bindingData.enqueuedTimeUtcArray[index]}`);
        context.log(`SequenceNumber = ${context.bindingData.sequenceNumberArray[index]}`);
        context.log(`Offset = ${context.bindingData.offsetArray[index]}`);
    });

    context.done();
};

Here's the PowerShell code:

param($eventHubMessages, $TriggerMetadata)

Write-Host "PowerShell eventhub trigger function called for message array: $eventHubMessages"

$eventHubMessages | ForEach-Object { Write-Host "Processed message: $_" }

The following example shows an Event Hubs trigger binding and a Python function that uses the binding. The function reads event metadata and logs the message. The example depends on whether you use the v1 or v2 Python programming model.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="EventHubTrigger1")
@app.event_hub_message_trigger(arg_name="myhub", 
                               event_hub_name="<EVENT_HUB_NAME>",
                               connection="<CONNECTION_SETTING>") 
def test_function(myhub: func.EventHubEvent):
    logging.info('Python EventHub trigger processed an event: %s',
                myhub.get_body().decode('utf-8'))

The following example shows an Event Hubs trigger binding which logs the message body of the Event Hubs trigger.

@FunctionName("ehprocessor")
public void eventHubProcessor(
  @EventHubTrigger(name = "msg",
                  eventHubName = "myeventhubname",
                  connection = "myconnvarname") String message,
       final ExecutionContext context )
       {
          context.getLogger().info(message);
 }

In the Java functions runtime library, use the EventHubTrigger annotation on parameters whose value comes from the event hub. Parameters with these annotations cause the function to run when an event arrives. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

The following example illustrates extensive use of SystemProperties and other Binding options for further introspection of the Event along with providing a well-formed BlobOutput path that is Date hierarchical.

package com.example;
import java.util.Map;
import java.time.ZonedDateTime;

import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

/**
 * Azure Functions with Event Hub trigger.
 * and Blob Output using date in path along with message partition ID
 * and message sequence number from EventHub Trigger Properties
 */
public class EventHubReceiver {

    @FunctionName("EventHubReceiver")
    @StorageAccount("bloboutput")

    public void run(
            @EventHubTrigger(name = "message",
                eventHubName = "%eventhub%",
                consumerGroup = "%consumergroup%",
                connection = "eventhubconnection",
                cardinality = Cardinality.ONE)
            String message,

            final ExecutionContext context,

            @BindingName("Properties") Map<String, Object> properties,
            @BindingName("SystemProperties") Map<String, Object> systemProperties,
            @BindingName("PartitionContext") Map<String, Object> partitionContext,
            @BindingName("EnqueuedTimeUtc") Object enqueuedTimeUtc,

            @BlobOutput(
                name = "outputItem",
                path = "iotevents/{datetime:yy}/{datetime:MM}/{datetime:dd}/{datetime:HH}/" +
                       "{datetime:mm}/{PartitionContext.PartitionId}/{SystemProperties.SequenceNumber}.json")
            OutputBinding<String> outputItem) {

        var et = ZonedDateTime.parse(enqueuedTimeUtc + "Z"); // needed as the UTC time presented does not have a TZ
                                                             // indicator
        context.getLogger().info("Event hub message received: " + message + ", properties: " + properties);
        context.getLogger().info("Properties: " + properties);
        context.getLogger().info("System Properties: " + systemProperties);
        context.getLogger().info("partitionContext: " + partitionContext);
        context.getLogger().info("EnqueuedTimeUtc: " + et);

        outputItem.setValue(message);
    }
}

Attributes

Both in-process and isolated worker process C# libraries use attribute to configure the trigger. C# script instead uses a function.json configuration file.

In C# class libraries, use the EventHubTriggerAttribute, which supports the following properties.

Parameters Description
EventHubName The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced in app settings, like %eventHubName%
ConsumerGroup An optional property that sets the consumer group used to subscribe to events in the hub. When omitted, the $Default consumer group is used.
Connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. To learn more, see Connections.

Decorators

Applies only to the Python v2 programming model.

For Python v2 functions defined using a decorator, the following properties on the cosmos_db_trigger:

Property Description
arg_name The name of the variable that represents the event item in function code.
event_hub_name The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime.
connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections.

For Python functions defined by using function.json, see the Configuration section.

Annotations

In the Java functions runtime library, use the EventHubTrigger annotation, which supports the following settings:

Configuration

Applies only to the Python v1 programming model.

The following table explains the trigger configuration properties that you set in the function.json file, which differs by runtime version.

function.json property Description
type Must be set to eventHubTrigger. This property is set automatically when you create the trigger in the Azure portal.
direction Must be set to in. This property is set automatically when you create the trigger in the Azure portal.
name The name of the variable that represents the event item in function code.
eventHubName The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced via app settings %eventHubName%
consumerGroup An optional property that sets the consumer group used to subscribe to events in the hub. If omitted, the $Default consumer group is used.
cardinality Set to many in order to enable batching. If omitted or set to one, a single message is passed to the function.
connection The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Usage

To learn more about how Event Hubs trigger and IoT Hub trigger scales, see Consuming Events with Azure Functions.

The parameter type supported by the Event Hubs output binding depends on the Functions runtime version, the extension package version, and the C# modality used.

In-process C# class library functions supports the following types:

This version of EventData drops support for the legacy Body type in favor of EventBody.

The parameter type can be one of the following:

  • Any native Java types such as int, String, byte[].
  • Nullable values using Optional.
  • Any POJO type.

To learn more, see the EventHubTrigger reference.

Event metadata

The Event Hubs trigger provides several metadata properties. Metadata properties can be used as part of binding expressions in other bindings or as parameters in your code. The properties come from the EventData class.

Property Type Description
PartitionContext PartitionContext The PartitionContext instance.
EnqueuedTimeUtc DateTime The enqueued time in UTC.
Offset string The offset of the data relative to the event hub partition stream. The offset is a marker or identifier for an event within the Event Hubs stream. The identifier is unique within a partition of the Event Hubs stream.
PartitionKey string The partition to which event data should be sent.
Properties IDictionary<String,Object> The user properties of the event data.
SequenceNumber Int64 The logical sequence number of the event.
SystemProperties IDictionary<String,Object> The system properties, including the event data.

See code examples that use these properties earlier in this article.

Connections

The connection property is a reference to environment configuration which specifies how the app should connect to Event Hubs. It may specify:

If the configured value is both an exact match for a single setting and a prefix match for other settings, the exact match is used.

Connection string

Obtain this connection string by clicking the Connection Information button for the namespace, not the event hub itself. The connection string must be for an Event Hubs namespace, not the event hub itself.

When used for triggers, the connection string must have at least "read" permissions to activate the function. When used for output bindings, the connection string must have "send" permissions to send messages to the event stream.

This connection string should be stored in an application setting with a name matching the value specified by the connection property of the binding configuration.

Identity-based connections

If you are using version 5.x or higher of the extension, instead of using a connection string with a secret, you can have the app use an Azure Active Directory identity. To do this, you would define settings under a common prefix which maps to the connection property in the trigger and binding configuration.

In this mode, the extension requires the following properties:

Property Environment variable template Description Example value
Fully Qualified Namespace <CONNECTION_NAME_PREFIX>__fullyQualifiedNamespace The fully qualified Event Hubs namespace. <event_hubs_namespace>.servicebus.chinacloudapi.cn

Additional properties may be set to customize the connection. See Common properties for identity-based connections.

Note

When using Azure App Configuration or Key Vault to provide settings for Managed Identity connections, setting names should use a valid key separator such as : or / in place of the __ to ensure names are resolved correctly.

For example, <CONNECTION_NAME_PREFIX>:fullyQualifiedNamespace.

When hosted in the Azure Functions service, identity-based connections use a managed identity. The system-assigned identity is used by default, although a user-assigned identity can be specified with the credential and clientID properties. Note that configuring a user-assigned identity with a resource ID is not supported. When run in other contexts, such as local development, your developer identity is used instead, although this can be customized. See Local development with identity-based connections.

Grant permission to the identity

Whatever identity is being used must have permissions to perform the intended actions. For most Azure services, this means you need to assign a role in Azure RBAC, using either built-in or custom roles which provide those permissions.

Important

Some permissions might be exposed by the target service that are not necessary for all contexts. Where possible, adhere to the principle of least privilege, granting the identity only required privileges. For example, if the app only needs to be able to read from a data source, use a role that only has permission to read. It would be inappropriate to assign a role that also allows writing to that service, as this would be excessive permission for a read operation. Similarly, you would want to ensure the role assignment is scoped only over the resources that need to be read.

You will need to create a role assignment that provides access to your event hub at runtime. The scope of the role assignment can be for an Event Hubs namespace, or the event hub itself. Management roles like Owner are not sufficient. The following table shows built-in roles that are recommended when using the Event Hubs extension in normal operation. Your application may require additional permissions based on the code you write.

Binding type Example built-in roles
Trigger Azure Event Hubs Data Receiver, Azure Event Hubs Data Owner
Output binding Azure Event Hubs Data Sender

host.json settings

The host.json file contains settings that control Event Hubs trigger behavior. See the host.json settings section for details regarding available settings.

Next steps