Azure Service Bus trigger for Azure Functions

Use the Service Bus trigger to respond to messages from a Service Bus queue or topic. Starting with extension version 3.1.0, you can trigger on a session-enabled queue or topic.

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


The following example shows a C# function that reads message metadata and logs a Service Bus queue message:

public static void Run(
    [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
    string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    ILogger log)
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");

Attributes and annotations

In C# class libraries, use the following attributes to configure a Service Bus trigger:

  • ServiceBusTriggerAttribute

    The attribute's constructor takes the name of the queue or the topic and subscription. In Azure Functions version 1.x, you can also specify the connection's access rights. If you don't specify access rights, the default is Manage. For more information, see the Trigger - configuration section.

    Here's an example that shows the attribute used with a string parameter:

    public static void Run(
        [ServiceBusTrigger("myqueue")] string myQueueItem, ILogger log)

    Since the Connection property isn't defined, Functions looks for an app setting named AzureWebJobsServiceBus, which is the default name for the Service Bus connection string. You can also set the Connection property to specify the name of an application setting that contains the Service Bus connection string to use, as shown in the following example:

    public static void Run(
        [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
        string myQueueItem, ILogger log)

    For a complete example, see Trigger - example.

  • ServiceBusAccountAttribute

    Provides another way to specify the Service Bus account to use. The constructor takes the name of an app setting that contains a Service Bus connection string. The attribute can be applied at the parameter, method, or class level. The following example shows class level and method level:

    public static class AzureFunctions
        public static void Run(
            [ServiceBusTrigger("myqueue", AccessRights.Manage)] 
            string myQueueItem, ILogger log)

The Service Bus account to use is determined in the following order:

  • The ServiceBusTrigger attribute's Connection property.
  • The ServiceBusAccount attribute applied to the same parameter as the ServiceBusTrigger attribute.
  • The ServiceBusAccount attribute applied to the function.
  • The ServiceBusAccount attribute applied to the class.
  • The "AzureWebJobsServiceBus" app setting.


The following table explains the binding configuration properties that you set in the function.json file and the ServiceBusTrigger attribute.

function.json property Attribute property Description
type n/a Must be set to "serviceBusTrigger". 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 queue or topic message in function code.
queueName QueueName Name of the queue to monitor. Set only if monitoring a queue, not for a topic.
topicName TopicName Name of the topic to monitor. Set only if monitoring a topic, not for a queue.
subscriptionName SubscriptionName Name of the subscription to monitor. Set only if monitoring a topic, not for a queue.
connection Connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.
accessRights Access Access rights for the connection string. Available values are manage and listen. The default is manage, which indicates that the connection has the Manage permission. If you use a connection string that does not have the Manage permission, set accessRights to "listen". Otherwise, the Functions runtime might fail trying to do operations that require manage rights. In Azure Functions version 2.x and higher, this property is not available because the latest version of the Service Bus SDK doesn't support manage operations.
isSessionsEnabled IsSessionsEnabled true if connecting to a session-aware queue or subscription. false otherwise, which is the default value.
autoComplete AutoComplete true Whether the trigger should automatically call complete after processing, or if the function code will manually call complete.

Setting to false is only supported in C#.

If set to true, the trigger completes the message automatically if the function execution completes successfully, and abandons the message otherwise.

When set to false, you are responsible for calling MessageReceiver methods to complete, abandon, or deadletter the message. If an exception is thrown (and none of the MessageReceiver methods are called), then the lock remains. Once the lock expires, the message is re-queued with the DeliveryCount incremented and the lock is automatically renewed.

In non-C# functions, exceptions in the function results in the runtime calls abandonAsync in the background. If no exception occurs, then completeAsync is called in the background. This property is available only in Azure Functions 2.x and higher.

When you're developing locally, app settings go into the local.settings.json file.


The connection property is a reference to environment configuration which specifies how the app should connect to Service Bus. 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

To obtain a connection string, follow the steps shown at Get the management credentials. The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.

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.

If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name. For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus". If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named "AzureWebJobsServiceBus".

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 Service Bus namespace. <service_bus_namespace>

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

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. 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. You will need to assign a role in Azure RBAC, using either built-in or custom roles which provide those permissions.


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 topics and queues at runtime. The scope of the role assignment must be for a Service Bus namespace, not limited to a specific queue or topic. Management roles like Owner are not sufficient. The following table shows built-in roles that are recommended when using the Service Bus extension in normal operation. Your application may require additional permissions based on the code you write.

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


The following parameter types are available for the queue or topic message:

  • string - If the message is text.
  • byte[] - Useful for binary data.
  • A custom type - If the message contains JSON, Azure Functions tries to deserialize the JSON data.
  • BrokeredMessage - Gives you the deserialized message with the BrokeredMessage.GetBody<T>() method.
  • MessageReceiver - Used to receive and acknowledge messages from the message container (required when autoComplete is set to false)

These parameter types are for Azure Functions version 1.x; for 2.x and higher, use Message instead of BrokeredMessage.

Additional types

Apps using the 5.0.0 or higher version of the Service Bus extension use the ServiceBusReceivedMessage type in Azure.Messaging.ServiceBus instead of the one in the Microsoft.Azure.ServiceBus namespace. This version drops support for the legacy Message type in favor of the following types:

Poison messages

Poison message handling can't be controlled or configured in Azure Functions. Service Bus handles poison messages itself.

PeekLock behavior

The Functions runtime receives a message in PeekLock mode. It calls Complete on the message if the function finishes successfully, or calls Abandon if the function fails. If the function runs longer than the PeekLock timeout, the lock is automatically renewed as long as the function is running.

The maxAutoRenewDuration is configurable in host.json, which maps to OnMessageOptions.MaxAutoRenewDuration. The maximum allowed for this setting is 5 minutes according to the Service Bus documentation, whereas you can increase the Functions time limit from the default of 5 minutes to 10 minutes. For Service Bus functions you wouldn’t want to do that then, because you’d exceed the Service Bus renewal limit.

Message metadata

The Service Bus trigger provides several metadata properties. These properties can be used as part of binding expressions in other bindings or as parameters in your code. These properties are members of the Message class.

Property Type Description
ContentType string A content type identifier utilized by the sender and receiver for application-specific logic.
CorrelationId string The correlation ID.
DeadLetterSource string The dead letter source.
DeliveryCount Int32 The number of deliveries.
EnqueuedTimeUtc DateTime The enqueued time in UTC.
ExpiresAtUtc DateTime The expiration time in UTC.
Label string The application-specific label.
MessageId string A user-defined value that Service Bus can use to identify duplicate messages, if enabled.
MessageReceiver MessageReceiver Service Bus message receiver. Can be used to abandon, complete, or deadletter the message.
MessageSession MessageSession A message receiver specifically for session-enabled queues and topics.
ReplyTo string The reply to queue address.
SequenceNumber long The unique number assigned to a message by the Service Bus.
To string The send to address.
UserProperties IDictionary<string, object> Properties set by the sender. (For version 5.x+ of the extension this is not supported, please use ApplicationProperties.)

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

Additional message metadata

The below metadata properties are supported for apps using 5.0.0 of the extension or higher. These properties are members of the ServiceBusReceivedMessage class.

Property Type Description
ApplicationProperties ApplicationProperties Properties set by the sender. Use this in place of the UserProperties metadata property.
Subject string The application-specific label which can be used in place of the Label metadata property.
MessageActions ServiceBusMessageActions The set of actions which can be performed on a ServiceBusReceivedMessage. This can be used in place of the MessageReceiver metadata property.
SessionActions ServiceBusSessionMessageActions The set of actions that can be performed on a session and a ServiceBusReceivedMessage. This can be used in place of the MessageSession metadata property.

Next steps