Azure IoT Hub trigger for Azure Functions
This article explains how to work with Azure Functions bindings for IoT Hub. The IoT Hub support is based on the Azure Event Hubs Binding.
For information on setup and configuration details, see the overview.
Important
While the following code samples use the Event Hub API, the given syntax is applicable for IoT Hub functions.
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.
Scaling
Each instance of an event triggered function is backed by a single EventProcessorHost instance. The trigger (powered by Event Hubs) ensures that only one EventProcessorHost instance can get a lease on a given partition.
For example, consider an Event Hub as follows:
- 10 partitions
- 1,000 events distributed evenly across all partitions, with 100 messages in each partition
When your function is first enabled, there is only one instance of the function. Let's call the first function instance Function_0
. The Function_0
function has a single instance of EventProcessorHost that holds a lease on all ten partitions. This instance is reading events from partitions 0-9. From this point forward, one of the following happens:
New function instances are not needed:
Function_0
is able to process all 1,000 events before the Functions scaling logic take effect. In this case, all 1,000 messages are processed byFunction_0
.An additional function instance is added: If the Functions scaling logic determines that
Function_0
has more messages than it can process, a new function app instance (Function_1
) is created. This new function also has an associated instance of EventProcessorHost. As the underlying Event Hubs detect that a new host instance is trying read messages, it load balances the partitions across the host instances. For example, partitions 0-4 may be assigned toFunction_0
and partitions 5-9 toFunction_1
.N more function instances are added: If the Functions scaling logic determines that both
Function_0
andFunction_1
have more messages than they can process, newFunctions_N
function app instances are created. Apps are created to the point whereN
is greater than the number of event hub partitions. In our example, Event Hubs again load balances the partitions, in this case across the instancesFunction_0
...Functions_9
.
As scaling occurs, N
instances is a number greater than the number of event hub partitions. This pattern is used to ensure EventProcessorHost instances are available to obtain locks on partitions as they become available from other instances. You are only charged for the resources used when the function instance executes. In other words, you are not charged for this over-provisioning.
When all function execution completes (with or without errors), checkpoints are added to the associated storage account. When check-pointing succeeds, all 1,000 messages are never retrieved again.
The following example shows a C# function that logs the message body of the event hub trigger.
[FunctionName("EventHubTriggerCSharp")]
public static 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 (requires a using statement for Microsoft.Azure.EventHubs
). 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 static 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 static 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}");
}
}
Attributes and annotations
In C# class libraries, use the EventHubTriggerAttribute attribute.
The attribute's constructor takes the name of the event hub, the name of the consumer group, and the name of an app setting that contains the connection string. For more information about these settings, see the trigger configuration section. Here's an EventHubTriggerAttribute
attribute example:
[FunctionName("EventHubTriggerCSharp")]
public static void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] string myEventHubMessage, ILogger log)
{
...
}
For a complete example, see Trigger - C# example.
Configuration
The following table explains the binding configuration properties that you set in the function.json file and the EventHubTrigger
attribute.
function.json property | Attribute property | Description |
---|---|---|
type | n/a | Must be set to eventHubTrigger . This property is set automatically when you create the trigger in the Azure portal. |
direction | n/a | Must be set to in . This property is set automatically when you create the trigger in the Azure portal. |
name | n/a | The name of the variable that represents the event item in function code. |
path | EventHubName | Functions 1.x only. 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. |
eventHubName | EventHubName | Functions 2.x and higher. 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 | 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 | n/a | Used for all non-C# languages. Set to many in order to enable batching. If omitted or set to one , a single message is passed to the function.In C#, this property is automatically assigned whenever the trigger has an array for the type. |
connection | Connection | The name of an app setting that contains the connection string to the event hub's namespace. Copy this connection string by clicking the Connection Information button for the namespace, not the event hub itself. This connection string must have at least read permissions to activate the trigger. If you are using version 5.x or higher of the extension, instead of a connection string, you can provide a reference to a configuration section which defines the connection. See Connections. |
When you're developing locally, app settings go into the local.settings.json file.
Usage
Default
You can use the following parameter types for the triggering Event Hub:
string
byte[]
POCO
EventData
- The default properties of EventData are provided in the for the Microsoft.Azure.EventHubs namespace.
Additional types
Apps using the 5.0.0 or higher version of the Event Hub extension use the EventData
type in Azure.Messaging.EventHubs instead of the one in Microsoft.Azure.EventHubs namespace. This version drops support for the legacy Body
type in favor of the following types:
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.
host.json properties
The host.json file contains settings that control Event Hub trigger behavior. See the host.json settings section for details regarding available settings.