Azure Service Bus bindings for Azure Functions

This article explains how to work with Azure Service Bus bindings in Azure Functions. Azure Functions supports trigger and output bindings for Service Bus queues and topics.

This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the following resources:

Packages - Functions 1.x

The Service Bus bindings are provided in the Microsoft.Azure.WebJobs.ServiceBus NuGet package, version 2.x.

The following table tells how to add support for this binding in each development environment.

Development environment To add support in
Functions 1.x
Local development - C# class library Install the package
Local development - C# script, JavaScript, F# Automatic
Portal development Automatic

Packages - Functions 2.x

The Service Bus bindings are provided in the Microsoft.Azure.WebJobs.Extensions.ServiceBus NuGet package, version 3.x. Source code for the package is in the azure-webjobs-sdk GitHub repository.

The following table tells how to add support for this binding in each development environment.

Development environment To add support in
Functions 2.x
Local development - C# class library Install the package
Local development - C# script, JavaScript, F# Register the extension
Portal development Automatic

To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

Trigger

Use the Service Bus trigger to respond to messages from a Service Bus queue or topic.

Trigger - example

See the language-specific example:

Trigger - C# example

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

[FunctionName("ServiceBusQueueTriggerCSharp")]                    
public static void Run(
    [ServiceBusTrigger("myqueue", AccessRights.Manage, Connection = "ServiceBusConnection")] 
    string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
    log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.Info($"DeliveryCount={deliveryCount}");
    log.Info($"MessageId={messageId}");
}

This example is for Azure Functions version 1.x; for 2.x, omit the access rights parameter.

Trigger - C# script example

The following example shows a Service Bus trigger binding in a function.json file and a C# script function that uses the binding. The function reads message metadata and logs a Service Bus queue message.

Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

Here's the C# script code:

using System;

public static void Run(string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");

    log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.Info($"DeliveryCount={deliveryCount}");
    log.Info($"MessageId={messageId}");
}

Trigger - F# example

The following example shows a Service Bus trigger binding in a function.json file and an F# function that uses the binding. The function logs a Service Bus queue message.

Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

Here's the F# script code:

let Run(myQueueItem: string, log: TraceWriter) =
    log.Info(sprintf "F# ServiceBus queue trigger function processed message: %s" myQueueItem)

Trigger - JavaScript example

The following example shows a Service Bus trigger binding in a function.json file and a JavaScript function that uses the binding. The function reads message metadata and logs a Service Bus queue message.

Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

Here's the JavaScript script code:

module.exports = function(context, myQueueItem) {
    context.log('Node.js ServiceBus queue trigger function processed message', myQueueItem);
    context.log('EnqueuedTimeUtc =', context.bindingData.enqueuedTimeUtc);
    context.log('DeliveryCount =', context.bindingData.deliveryCount);
    context.log('MessageId =', context.bindingData.messageId);
    context.done();
};

Trigger - Java example

The following example shows a Service Bus trigger binding in a function.json file and a Java function that uses the binding. The function is triggered by a message placed on a Service Bus queue, and the function logs the queue message.

Here's the binding data in the function.json file:

{
"bindings": [
    {
    "queueName": "myqueuename",
    "connection": "MyServiceBusConnection",
    "name": "msg",
    "type": "ServiceBusQueueTrigger",
    "direction": "in"
    }
],
"disabled": false
}

Here's the Java code:

@FunctionName("sbprocessor")
 public void serviceBusProcess(
    @ServiceBusQueueTrigger(name = "msg",
                             queueName = "myqueuename",
                             connection = "myconnvarname") String message,
   final ExecutionContext context
 ) {
     context.getLogger().info(message);
 }

Trigger - attributes

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:

    [FunctionName("ServiceBusQueueTriggerCSharp")]                    
    public static void Run(
        [ServiceBusTrigger("myqueue")] string myQueueItem, TraceWriter log)
    {
        ...
    }
    

    You can set the Connection property to specify the Service Bus account to use, as shown in the following example:

    [FunctionName("ServiceBusQueueTriggerCSharp")]                    
    public static void Run(
        [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] 
        string myQueueItem, TraceWriter log)
    {
        ...
    }
    

    For a complete example, see Trigger - C# 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:

    [ServiceBusAccount("ClassLevelServiceBusAppSetting")]
    public static class AzureFunctions
    {
        [ServiceBusAccount("MethodLevelServiceBusAppSetting")]
        [FunctionName("ServiceBusQueueTriggerCSharp")]
        public static void Run(
            [ServiceBusTrigger("myqueue", AccessRights.Manage)] 
            string myQueueItem, TraceWriter 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.

Trigger - configuration

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. Set to "$return" to reference the function return value.
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 that contains the Service Bus connection string to use for this binding. 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".

To obtain a connection string, follow the steps shown at Obtain the management credentials. The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.
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, this property is not available because the latest version of the Storage SDK doesn't support manage operations.

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

Trigger - usage

In C# and C# script, you can use the following parameter types 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() method.

These parameters are for Azure Functions version 1.x; for 2.x, use Message instead of BrokeredMessage.

In JavaScript, access the queue or topic message by using context.bindings.<name from function.json>. The Service Bus message is passed into the function as either a string or JSON object.

Trigger - poison messages

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

Trigger - 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.

Functions 1.x allows you to configure autoRenewTimeout in host.json, which maps to OnMessageOptions.AutoRenewTimeout. 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.

Trigger - 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 are properties of the BrokeredMessage class.

Property Type Description
DeliveryCount Int32 The number of deliveries.
DeadLetterSource string The dead letter source.
ExpiresAtUtc DateTime The expiration time in UTC.
EnqueuedTimeUtc DateTime The enqueued time in UTC.
MessageId string A user-defined value that Service Bus can use to identify duplicate messages, if enabled.
ContentType string A content type identifier utilized by the sender and receiver for application specific logic.
ReplyTo string The reply to queue address.
SequenceNumber Int64 The unique number assigned to a message by the Service Bus.
To string The send to address.
Label string The application specific label.
CorrelationId string The correlation ID.
Properties IDictionary<String,Object> The application specific message properties.

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

Trigger - host.json properties

The host.json file contains settings that control Service Bus trigger behavior.

{
    "serviceBus": {
      "maxConcurrentCalls": 16,
      "prefetchCount": 100,
      "autoRenewTimeout": "00:05:00"
    }
}
Property Default Description
maxConcurrentCalls 16 The maximum number of concurrent calls to the callback that the message pump should initiate. By default, the Functions runtime processes multiple messages concurrently. To direct the runtime to process only a single queue or topic message at a time, set maxConcurrentCalls to 1.
prefetchCount n/a The default PrefetchCount that will be used by the underlying MessageReceiver.
autoRenewTimeout 00:05:00 The maximum duration within which the message lock will be renewed automatically.

Output

Use Azure Service Bus output binding to send queue or topic messages.

Output - example

See the language-specific example:

Output - C# example

The following example shows a C# function that sends a Service Bus queue message:

[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string ServiceBusOutput([HttpTrigger] dynamic input, TraceWriter log)
{
    log.Info($"C# function processed: {input.Text}");
    return input.Text;
}

Output - C# script example

The following example shows a Service Bus output binding in a function.json file and a C# script function that uses the binding. The function uses a timer trigger to send a queue message every 15 seconds.

Here's the binding data in the function.json file:

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

Here's C# script code that creates a single message:

public static void Run(TimerInfo myTimer, TraceWriter log, out string outputSbQueue)
{
    string message = $"Service Bus queue message created at: {DateTime.Now}";
    log.Info(message); 
    outputSbQueue = message;
}

Here's C# script code that creates multiple messages:

public static void Run(TimerInfo myTimer, TraceWriter log, ICollector<string> outputSbQueue)
{
    string message = $"Service Bus queue messages created at: {DateTime.Now}";
    log.Info(message); 
    outputSbQueue.Add("1 " + message);
    outputSbQueue.Add("2 " + message);
}

Output - F# example

The following example shows a Service Bus output binding in a function.json file and an F# script function that uses the binding. The function uses a timer trigger to send a queue message every 15 seconds.

Here's the binding data in the function.json file:

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

Here's F# script code that creates a single message:

let Run(myTimer: TimerInfo, log: TraceWriter, outputSbQueue: byref<string>) =
    let message = sprintf "Service Bus queue message created at: %s" (DateTime.Now.ToString())
    log.Info(message)
    outputSbQueue = message

Output - JavaScript example

The following example shows a Service Bus output binding in a function.json file and a JavaScript function that uses the binding. The function uses a timer trigger to send a queue message every 15 seconds.

Here's the binding data in the function.json file:

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

Here's JavaScript script code that creates a single message:

module.exports = function (context, myTimer) {
    var message = 'Service Bus queue message created at ' + timeStamp;
    context.log(message);   
    context.bindings.outputSbQueue = message;
    context.done();
};

Here's JavaScript script code that creates multiple messages:

module.exports = function (context, myTimer) {
    var message = 'Service Bus queue message created at ' + timeStamp;
    context.log(message);   
    context.bindings.outputSbQueue = [];
    context.bindings.outputSbQueue.push("1 " + message);
    context.bindings.outputSbQueue.push("2 " + message);
    context.done();
};

Output - Java example

The following example shows a Java function that sends a message to a Service Bus queue myqueue when triggered by a HTTP request.

@FunctionName("httpToServiceBusQueue")
@ServiceBusQueueOutput(name = "message", queueName = "myqueue", connection = "AzureServiceBusConnection")
public String pushToQueue(
  @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
  final String message,
  @HttpOutput(name = "response") final OutputBinding<T> result ) {
      result.setValue(message + " has been sent.");
      return message;
 }

In the Java functions runtime library, use the @QueueOutput annotation on function parameters whose value would be written to a Service Bus queue. The parameter type should be OutputBinding<T>, where T is any native Java type of a POJO.

Output - attributes

In C# class libraries, use the ServiceBusAttribute.

The attribute's constructor takes the name of the queue or the topic and subscription. You can also specify the connection's access rights. How to choose the access rights setting is explained in the Output - configuration section. Here's an example that shows the attribute applied to the return value of the function:

[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue")]
public static string Run([HttpTrigger] dynamic input, TraceWriter log)
{
    ...
}

You can set the Connection property to specify the Service Bus account to use, as shown in the following example:

[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string Run([HttpTrigger] dynamic input, TraceWriter log)
{
    ...
}

For a complete example, see Output - C# example.

You can use the ServiceBusAccount attribute to specify the Service Bus account to use at class, method, or parameter level. For more information, see Trigger - attributes.

Output - configuration

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

function.json property Attribute property Description
type n/a Must be set to "serviceBus". This property is set automatically when you create the trigger in the Azure portal.
direction n/a Must be set to "out". 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 in function code. Set to "$return" to reference the function return value.
queueName QueueName Name of the queue. Set only if sending queue messages, not for a topic.
topicName TopicName Name of the topic to monitor. Set only if sending topic messages, not for a queue.
connection Connection The name of an app setting that contains the Service Bus connection string to use for this binding. 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".

To obtain a connection string, follow the steps shown at Obtain the management credentials. The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.
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, this property is not available because the latest version of the Storage SDK doesn't support manage operations.

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

Output - usage

In Azure Functions 1.x, the runtime creates the queue if it doesn't exist and you have set accessRights to manage. In Functions version 2.x, the queue or topic must already exist; if you specify a queue or topic that doesn't exist, the function will fail.

In C# and C# script, you can use the following parameter types for the output binding:

  • out T paramName - T can be any JSON-serializable type. If the parameter value is null when the function exits, Functions creates the message with a null object.
  • out string - If the parameter value is null when the function exits, Functions does not create a message.
  • out byte[] - If the parameter value is null when the function exits, Functions does not create a message.
  • out BrokeredMessage - If the parameter value is null when the function exits, Functions does not create a message.
  • ICollector<T> or IAsyncCollector<T> - For creating multiple messages. A message is created when you call the Add method.

In async functions, use the return value or IAsyncCollector instead of an out parameter.

These parameters are for Azure Functions version 1.x; for 2.x, use Message instead of BrokeredMessage.

In JavaScript, access the queue or topic by using context.bindings.<name from function.json>. You can assign a string, a byte array, or a Javascript object (deserialized into JSON) to context.binding.<name>.

Exceptions and return codes

Binding Reference
Service Bus Service Bus Error Codes
Service Bus Service Bus Limits

Next steps