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.
Service Bus scaling decisions for the Consumption and Premium plans are made based on target-based scaling. For more information, see Target-based scaling.
Important
This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration guide.
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.
The Python v1 programming model requires you to define bindings in a separate function.json file in the function folder. For more information, see the Python developer guide.
This article supports both programming models.
ExampleA C# function can be created by using one of the following C# modes:
Microsoft.Azure.Functions.Worker.Extensions.*
namespaces.Microsoft.Azure.WebJobs.Extensions.*
namespaces.This code defines and initializes the ILogger
:
private readonly ILogger<ServiceBusReceivedMessageFunctions> _logger;
public ServiceBusReceivedMessageFunctions(ILogger<ServiceBusReceivedMessageFunctions> logger)
{
_logger = logger;
}
This example shows a C# function that receives a single Service Bus queue message and writes it to the logs:
[Function(nameof(ServiceBusReceivedMessageFunction))]
[ServiceBusOutput("outputQueue", Connection = "ServiceBusConnection")]
public string ServiceBusReceivedMessageFunction(
[ServiceBusTrigger("queue", Connection = "ServiceBusConnection")] ServiceBusReceivedMessage message)
{
_logger.LogInformation("Message ID: {id}", message.MessageId);
_logger.LogInformation("Message Body: {body}", message.Body);
_logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
var outputMessage = $"Output message created at {DateTime.Now}";
return outputMessage;
}
This example shows a C# function that receives multiple Service Bus queue messages in a single batch and writes each to the logs:
[Function(nameof(ServiceBusReceivedMessageBatchFunction))]
public void ServiceBusReceivedMessageBatchFunction(
[ServiceBusTrigger("queue", Connection = "ServiceBusConnection", IsBatched = true)] ServiceBusReceivedMessage[] messages)
{
foreach (ServiceBusReceivedMessage message in messages)
{
_logger.LogInformation("Message ID: {id}", message.MessageId);
_logger.LogInformation("Message Body: {body}", message.Body);
_logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
}
}
This example shows a C# function that receives multiple Service Bus queue messages, writes it to the logs, and then settles the message as completed:
[Function(nameof(ServiceBusMessageActionsFunction))]
public async Task ServiceBusMessageActionsFunction(
[ServiceBusTrigger("queue", Connection = "ServiceBusConnection", AutoCompleteMessages = false)]
ServiceBusReceivedMessage message,
ServiceBusMessageActions messageActions)
{
_logger.LogInformation("Message ID: {id}", message.MessageId);
_logger.LogInformation("Message Body: {body}", message.Body);
_logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
// Complete the message
await messageActions.CompleteMessageAsync(message);
}
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", Connection = "ServiceBusConnection")]
string myQueueItem,
Int32 deliveryCount,
DateTime enqueuedTimeUtc,
string messageId,
ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
log.LogInformation($"DeliveryCount={deliveryCount}");
log.LogInformation($"MessageId={messageId}");
}
The following Java function uses the @ServiceBusQueueTrigger
annotation from the Java functions runtime library to describe the configuration for a Service Bus queue trigger. The function grabs the message placed on the queue and adds it to the logs.
@FunctionName("sbprocessor")
public void serviceBusProcess(
@ServiceBusQueueTrigger(name = "msg",
queueName = "myqueuename",
connection = "myconnvarname") String message,
final ExecutionContext context
) {
context.getLogger().info(message);
}
Java functions can also be triggered when a message is added to a Service Bus topic. The following example uses the @ServiceBusTopicTrigger
annotation to describe the trigger configuration.
@FunctionName("sbtopicprocessor")
public void run(
@ServiceBusTopicTrigger(
name = "message",
topicName = "mytopicname",
subscriptionName = "mysubscription",
connection = "ServiceBusConnection"
) String message,
final ExecutionContext context
) {
context.getLogger().info(message);
}
The following example shows a Service Bus trigger TypeScript function. The function reads message metadata and logs a Service Bus queue message.
import { app, InvocationContext } from '@azure/functions';
export async function serviceBusQueueTrigger1(message: unknown, context: InvocationContext): Promise<void> {
context.log('Service bus queue function processed message:', message);
context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc);
context.log('DeliveryCount =', context.triggerMetadata.deliveryCount);
context.log('MessageId =', context.triggerMetadata.messageId);
}
app.serviceBusQueue('serviceBusQueueTrigger1', {
connection: 'MyServiceBusConnection',
queueName: 'testqueue',
handler: serviceBusQueueTrigger1,
});
TypeScript samples are not documented for model v3.
The following example shows a Service Bus trigger JavaScript function. The function reads message metadata and logs a Service Bus queue message.
const { app } = require('@azure/functions');
app.serviceBusQueue('serviceBusQueueTrigger1', {
connection: 'MyServiceBusConnection',
queueName: 'testqueue',
handler: (message, context) => {
context.log('Service bus queue function processed message:', message);
context.log('EnqueuedTimeUtc =', context.triggerMetadata.enqueuedTimeUtc);
context.log('DeliveryCount =', context.triggerMetadata.deliveryCount);
context.log('MessageId =', context.triggerMetadata.messageId);
},
});
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 = async 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);
};
The following example shows a Service Bus trigger binding in a function.json file and a PowerShell function that uses the binding.
Here's the binding data in the function.json file:
{
"bindings": [
{
"name": "mySbMsg",
"type": "serviceBusTrigger",
"direction": "in",
"topicName": "mytopic",
"subscriptionName": "mysubscription",
"connection": "AzureServiceBusConnectionString"
}
]
}
Here's the function that runs when a Service Bus message is sent.
param([string] $mySbMsg, $TriggerMetadata)
Write-Host "PowerShell ServiceBus queue trigger function processed message: $mySbMsg"
This example uses SDK types to directly access the underlying ServiceBusReceivedMessage
object provided by the Service Bus trigger:
The function reads various properties of the ServiceBusReceivedMessage
type and logs them.
import logging
import azure.functions as func
import azurefunctions.extensions.bindings.servicebus as servicebus
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.service_bus_queue_trigger(arg_name="receivedmessage",
queue_name="QUEUE_NAME",
connection="SERVICEBUS_CONNECTION")
def servicebus_queue_trigger(receivedmessage: servicebus.ServiceBusReceivedMessage):
logging.info("Python ServiceBus queue trigger processed message.")
logging.info("Receiving: %s\n"
"Body: %s\n"
"Enqueued time: %s\n"
"Lock Token: %s\n"
"Message ID: %s\n"
"Sequence number: %s\n",
receivedmessage,
receivedmessage.body,
receivedmessage.enqueued_time_utc,
receivedmessage.lock_token,
receivedmessage.message_id,
receivedmessage.sequence_number)
For more examples using Service Bus SDK types, see the ServiceBusReceivedMessage
samples. For a step-by-step tutorial on how to include SDK-type bindings in your function app, follow the Python SDK Bindings for Service Bus Sample.
Note
Known limitations include:
message
property is not supported.To learn more, including what other SDK type bindings are supported, see SDK type bindings.
The following example demonstrates how to read a Service Bus queue message via a trigger. 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="ServiceBusQueueTrigger1")
@app.service_bus_queue_trigger(arg_name="msg",
queue_name="<QUEUE_NAME>",
connection="<CONNECTION_SETTING>")
def test_function(msg: func.ServiceBusMessage):
logging.info('Python ServiceBus queue trigger processed message: %s',
msg.get_body().decode('utf-8'))
A Service Bus binding is defined in function.json where type is set to serviceBusTrigger
and the queue is set by queueName
.
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "msg",
"type": "serviceBusTrigger",
"direction": "in",
"queueName": "inputqueue",
"connection": "AzureServiceBusConnectionString"
}
]
}
The code in _init_.py declares a parameter as func.ServiceBusMessage
, which allows you to read the queue message in your function.
import azure.functions as func
import logging
import json
def main(msg: func.ServiceBusMessage):
logging.info('Python ServiceBus queue trigger processed message.')
result = json.dumps({
'message_id': msg.message_id,
'body': msg.get_body().decode('utf-8'),
'content_type': msg.content_type,
'expiration_time': msg.expiration_time,
'label': msg.label,
'partition_key': msg.partition_key,
'reply_to': msg.reply_to,
'reply_to_session_id': msg.reply_to_session_id,
'scheduled_enqueue_time': msg.scheduled_enqueue_time,
'session_id': msg.session_id,
'time_to_live': msg.time_to_live,
'to': msg.to,
'user_properties': msg.user_properties,
'metadata' : msg.metadata
}, default=str)
logging.info(result)
The following example demonstrates how to read a Service Bus queue topic via a trigger.
import logging
import azure.functions as func
app = func.FunctionApp()
@app.function_name(name="ServiceBusTopicTrigger1")
@app.service_bus_topic_trigger(arg_name="message",
topic_name="TOPIC_NAME",
connection="CONNECTION_SETTING",
subscription_name="SUBSCRIPTION_NAME")
def test_function(message: func.ServiceBusMessage):
message_body = message.get_body().decode("utf-8")
logging.info("Python ServiceBus topic trigger processed message.")
logging.info("Message Body: " + message_body)
A Service Bus binding is defined in function.json where type is set to serviceBusTrigger
and the topic is set by topicName
.
{
"scriptFile": "__init__.py",
"bindings": [
{
"type": "serviceBusTrigger",
"direction": "in",
"name": "msg",
"topicName": "inputtopic",
"connection": "AzureServiceBusConnectionString"
}
]
}
The code in _init_.py declares a parameter as func.ServiceBusMessage
, which allows you to read the topic in your function.
import json
import azure.functions as azf
def main(msg: azf.ServiceBusMessage) -> str:
result = json.dumps({
'message_id': msg.message_id,
'body': msg.get_body().decode('utf-8'),
'content_type': msg.content_type,
'delivery_count': msg.delivery_count,
'expiration_time': (msg.expiration_time.isoformat() if
msg.expiration_time else None),
'label': msg.label,
'partition_key': msg.partition_key,
'reply_to': msg.reply_to,
'reply_to_session_id': msg.reply_to_session_id,
'scheduled_enqueue_time': (msg.scheduled_enqueue_time.isoformat() if
msg.scheduled_enqueue_time else None),
'session_id': msg.session_id,
'time_to_live': msg.time_to_live,
'to': msg.to,
'user_properties': msg.user_properties,
})
logging.info(result)
Attributes
Both in-process and isolated worker process C# libraries use the ServiceBusTriggerAttribute attribute to define the function trigger. C# script instead uses a function.json configuration file as described in the C# scripting guide.
The following table explains the properties you can set using this trigger attribute:
Property Description QueueName Name of the queue to monitor. Set only if monitoring a queue, not for a topic. TopicName Name of the topic to monitor. Set only if monitoring a topic, not for a queue. SubscriptionName Name of the subscription to monitor. Set only if monitoring a topic, not for a queue. Connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections. IsBatched Messages are delivered in batches. Requires an array or collection type. IsSessionsEnabledtrue
if connecting to a session-aware queue or subscription. false
otherwise, which is the default value. AutoCompleteMessages true
if the trigger should automatically complete the message after a successful invocation. false
if it should not, such as when you are handling message settlement in code. If not explicitly set, the behavior is based on the autoCompleteMessages
configuration in host.json
.
The following table explains the properties you can set using this trigger attribute:
Property Description QueueName Name of the queue to monitor. Set only if monitoring a queue, not for a topic. TopicName Name of the topic to monitor. Set only if monitoring a topic, not for a queue. SubscriptionName Name of the subscription to monitor. Set only if monitoring a topic, not for a queue. Connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections. Access Access rights for the connection string. Available values aremanage
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. IsBatched Messages are delivered in batches. Requires an array or collection type. IsSessionsEnabled true
if connecting to a session-aware queue or subscription. false
otherwise, which is the default value. AutoComplete true
Whether the trigger should automatically call complete after processing, or if the function code will manually call complete.
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 ServiceBusReceiver methods to complete, abandon, or deadletter the message, session, or batch. When an exception is thrown (and none of the ServiceBusReceiver
methods are called), then the lock remains. Once the lock expires, the message is requeued with the DeliveryCount
incremented and the lock is automatically renewed.
When you're developing locally, add your application settings in the local.settings.json file in the Values
collection.
Applies only to the Python v2 programming model.
For Python v2 functions defined using a decorator, the following properties on the service_bus_queue_trigger
:
arg_name
The name of the variable that represents the queue or topic message in function code. queue_name
Name of the queue to monitor. Set only if monitoring a queue, not for a topic. connection
The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.
For Python functions defined by using function.json, see the Configuration section.
AnnotationsThe ServiceBusQueueTrigger
annotation allows you to create a function that runs when a Service Bus queue message is created. Configuration options available include the following properties:
The ServiceBusTopicTrigger
annotation allows you to designate a topic and subscription to target what data triggers the function.
When you're developing locally, add your application settings in the local.settings.json file in the Values
collection.
See the trigger example for more detail.
ConfigurationApplies only to the Python v1 programming model.
The following table explains the properties that you can set on the options
object passed to the app.serviceBusQueue()
or app.serviceBusTopic()
methods.
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 true
if connecting to a session-aware queue or subscription. false
otherwise, which is the default value. autoComplete Must be true
for non-C# functions, which means that the trigger should either automatically call complete after processing, or the function code manually calls complete.
When set to true
, the trigger completes the message automatically if the function execution completes successfully, and abandons the message otherwise.
Exceptions in the function results in the runtime call 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.
The following table explains the binding configuration properties that you set in the function.json file.
Property Description type Must be set toserviceBusTrigger
. 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 queue or topic message in function code. queueName Name of the queue to monitor. Set only if monitoring a queue, not for a topic. topicName Name of the topic to monitor. Set only if monitoring a topic, not for a queue. subscriptionName Name of the subscription to monitor. Set only if monitoring a topic, not for a queue. connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections. accessRights 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 true
if connecting to a session-aware queue or subscription. false
otherwise, which is the default value. autoComplete Must be true
for non-C# functions, which means that the trigger should either automatically call complete after processing, or the function code manually calls complete.
When set to true
, the trigger completes the message automatically if the function execution completes successfully, and abandons the message otherwise.
Exceptions in the function results in the runtime call 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, add your application settings in the local.settings.json file in the Values
collection.
The following table explains the binding configuration properties that you set in the function.json file.
function.json property Description type Must be set toserviceBusTrigger
. 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 queue or topic message in function code. queueName Name of the queue to monitor. Set only if monitoring a queue, not for a topic. topicName Name of the topic to monitor. Set only if monitoring a topic, not for a queue. subscriptionName Name of the subscription to monitor. Set only if monitoring a topic, not for a queue. connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections. accessRights 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 true
if connecting to a session-aware queue or subscription. false
otherwise, which is the default value. autoComplete Must be true
for non-C# functions, which means that the trigger should either automatically call complete after processing, or the function code manually calls complete.
When set to true
, the trigger completes the message automatically if the function execution completes successfully, and abandons the message otherwise.
Exceptions in the function results in the runtime call 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, add your application settings in the local.settings.json file in the Values
collection.
See the Example section for complete examples.
UsageThe following parameter types are supported by all C# modalities and extension versions:
Type Description System.String Use when the message is simple text. byte[] Use for binary data messages. Object When a message contains JSON, Functions tries to deserialize the JSON data into known plain-old CLR object type.Messaging-specific parameter types contain additional message metadata. The specific types supported by the Service Bus trigger depend on the Functions runtime version, the extension package version, and the C# modality used.
Use the ServiceBusReceivedMessage type to receive message metadata from Service Bus Queues and Subscriptions. To learn more, see Messages, payloads, and serialization.
In C# class libraries, the attribute's constructor takes the name of the queue or the topic and subscription.
You can also use the ServiceBusAccountAttribute 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, ILogger log)
{
...
}
The Service Bus account to use is determined in the following order:
ServiceBusTrigger
attribute's Connection
property.ServiceBusAccount
attribute applied to the same parameter as the ServiceBusTrigger
attribute.ServiceBusAccount
attribute applied to the function.ServiceBusAccount
attribute applied to the class.AzureWebJobsServiceBus
app setting.Use the Message type to receive messages with metadata. To learn more, see Messages, payloads, and serialization.
On 30 September 2026, we'll retire the Azure Service Bus SDK libraries WindowsAzure.ServiceBus, Microsoft.Azure.ServiceBus, and com.microsoft.azure.servicebus, which don't conform to Azure SDK guidelines. We'll also end support of the SBMP protocol, so you'll no longer be able to use this protocol after 30 September 2026. Migrate to the latest Azure SDK libraries, which offer critical security updates and improved capabilities, before that date.
Although the older libraries can still be used beyond 30 September 2026, they'll no longer receive official support and updates from Microsoft. For more information, see the support retirement announcement.
In C# class libraries, the attribute's constructor takes the name of the queue or the topic and subscription.
You can also use the ServiceBusAccountAttribute 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, ILogger log)
{
...
}
The Service Bus account to use is determined in the following order:
ServiceBusTrigger
attribute's Connection
property.ServiceBusAccount
attribute applied to the same parameter as the ServiceBusTrigger
attribute.ServiceBusAccount
attribute applied to the function.ServiceBusAccount
attribute applied to the class.AzureWebJobsServiceBus
app setting.The following parameter types are available for the queue or topic message:
autoComplete
is set to false
.On 30 September 2026, we'll retire the Azure Service Bus SDK libraries WindowsAzure.ServiceBus, Microsoft.Azure.ServiceBus, and com.microsoft.azure.servicebus, which don't conform to Azure SDK guidelines. We'll also end support of the SBMP protocol, so you'll no longer be able to use this protocol after 30 September 2026. Migrate to the latest Azure SDK libraries, which offer critical security updates and improved capabilities, before that date.
Although the older libraries can still be used beyond 30 September 2026, they'll no longer receive official support and updates from Microsoft. For more information, see the support retirement announcement.
In C# class libraries, 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
.
You can also use the ServiceBusAccountAttribute 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, ILogger log)
{
...
}
The Service Bus account to use is determined in the following order:
ServiceBusTrigger
attribute's Connection
property.ServiceBusAccount
attribute applied to the same parameter as the ServiceBusTrigger
attribute.ServiceBusAccount
attribute applied to the function.ServiceBusAccount
attribute applied to the class.AzureWebJobsServiceBus
app setting.When you want the function to process a single message, the Service Bus trigger can bind to the following types:
Type Descriptionstring
The message as a string. Use when the message is simple text. byte[]
The bytes of the message. JSON serializable types When an event contains JSON data, Functions tries to deserialize the JSON data into a plain-old CLR object (POCO) type. ServiceBusReceivedMessage1 The message object.
When binding to ServiceBusReceivedMessage
, you can optionally also include a parameter of type ServiceBusMessageActions1,2 to perform message settlement actions.
When you want the function to process a batch of messages, the Service Bus trigger can bind to the following types:
Type DescriptionT[]
where T
is one of the single message types An array of events from the batch. Each entry represents one event.
When binding to ServiceBusReceivedMessage[]
, you can optionally also include a parameter of type ServiceBusMessageActions1,2 to perform message settlement actions.
1 To use these types, you need to reference Microsoft.Azure.Functions.Worker.Extensions.ServiceBus 5.14.1 or later and the common dependencies for SDK type bindings.
2 When using ServiceBusMessageActions
, set the AutoCompleteMessages
property of the trigger attribute to false
. This prevents the runtime from attempting to complete messages after a successful function invocation.
Earlier versions of this extension in the isolated worker process only support binding to messaging-specific types. Additional options are available to extension 5.x and higher
Functions version 1.x doesn't support isolated worker process. To use the isolated worker model, upgrade your application to Functions 4.x.
When 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.
The incoming Service Bus message is available via a ServiceBusQueueMessage
or ServiceBusTopicMessage
parameter.
Access the queue or topic message as the first argument to your function. The Service Bus message is passed into the function as either a string or JSON object.
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.
The Service Bus instance is available via the parameter configured in the function.json file's name property.
The queue message is available to the function via a parameter typed as func.ServiceBusMessage
. The Service Bus message is passed into the function as either a string or JSON object.
Functions also support Python SDK type bindings for Azure Service Bus, which lets you work with data using these underlying SDK types:
Important
Support for Service Bus SDK types support in Python is in Preview and is only supported for the Python v2 programming model. For more information, see SDK types in Python.
For a complete example, see the examples section.
ConnectionsThe 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 stringTo 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".
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 Microsoft Entra 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>.servicebus.windows.net
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.
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'll need to create a role assignment that provides access to your topics and queues at runtime. Management roles like Owner aren't 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.
1 For triggering from Service Bus topics, the role assignment needs to have effective scope over the Service Bus subscription resource. If only the topic is included, an error will occur. Some clients, such as the Azure portal, don't expose the Service Bus subscription resource as a scope for role assignment. In such cases, the Azure CLI may be used instead. To learn more, see Azure built-in roles for Azure Service Bus.
Poison messagesPoison message handling can't be controlled or configured in Azure Functions. Service Bus handles poison messages itself.
PeekLock behaviorThe Functions runtime receives a message in PeekLock mode.
By default, the runtime calls Complete
on the message if the function finishes successfully, or calls Abandon
if the function fails. You can disable automatic completion through with the autoCompleteMessages
property in host.json
.
By default, the runtime calls Complete
on the message if the function finishes successfully, or calls Abandon
if the function fails. You can disable automatic completion through with the autoCompleteMessages
property in host.json
or through a property on the trigger attribute. You should disable automatic completion if your function code handles message settlement.
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 ServiceBusProcessor.MaxAutoLockRenewalDuration. The default value of this setting is 5 minutes.
Messaging-specific types let you easily retrieve metadata as properties of the object. These properties depend on the Functions runtime version, the extension package version, and the C# modality used.
These properties are members of the ServiceBusReceivedMessage class.
Property Type DescriptionApplicationProperties
ApplicationProperties
Properties set by the sender. ContentType
string
A content type identifier utilized by the sender and receiver for application-specific logic. CorrelationId
string
The correlation ID. DeliveryCount
Int32
The number of deliveries. EnqueuedTime
DateTime
The enqueued time in UTC. ScheduledEnqueueTimeUtc
DateTime
The scheduled enqueued time in UTC. ExpiresAt
DateTime
The expiration time in UTC. MessageId
string
A user-defined value that Service Bus can use to identify duplicate messages, if enabled. ReplyTo
string
The reply to queue address. Subject
string
The application-specific label which can be used in place of the Label
metadata property. To
string
The send to address.
These properties are members of the Message class.
Property Type DescriptionOn 30 September 2026, we'll retire the Azure Service Bus SDK libraries WindowsAzure.ServiceBus, Microsoft.Azure.ServiceBus, and com.microsoft.azure.servicebus, which don't conform to Azure SDK guidelines. We'll also end support of the SBMP protocol, so you'll no longer be able to use this protocol after 30 September 2026. Migrate to the latest Azure SDK libraries, which offer critical security updates and improved capabilities, before that date.
Although the older libraries can still be used beyond 30 September 2026, they'll no longer receive official support and updates from Microsoft. For more information, see the support retirement announcement.
ContentType
string
A content type identifier utilized by the sender and receiver for application-specific logic. CorrelationId
string
The correlation ID. DeliveryCount
Int32
The number of deliveries. ScheduledEnqueueTimeUtc
DateTime
The scheduled 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. ReplyTo
string
The reply to queue address. To
string
The send to address. UserProperties
IDictionary<string, object>
Properties set by the sender.
These properties are members of the BrokeredMessage and MessageReceiver classes.
Property Type DescriptionOn 30 September 2026, we'll retire the Azure Service Bus SDK libraries WindowsAzure.ServiceBus, Microsoft.Azure.ServiceBus, and com.microsoft.azure.servicebus, which don't conform to Azure SDK guidelines. We'll also end support of the SBMP protocol, so you'll no longer be able to use this protocol after 30 September 2026. Migrate to the latest Azure SDK libraries, which offer critical security updates and improved capabilities, before that date.
Although the older libraries can still be used beyond 30 September 2026, they'll no longer receive official support and updates from Microsoft. For more information, see the support retirement announcement.
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.
These properties are members of the ServiceBusReceivedMessage class.
Property Type DescriptionApplicationProperties
ApplicationProperties
Properties set by the sender. ContentType
string
A content type identifier utilized by the sender and receiver for application-specific logic. CorrelationId
string
The correlation ID. DeliveryCount
Int32
The number of deliveries. EnqueuedTime
DateTime
The enqueued time in UTC. ScheduledEnqueueTimeUtc
DateTime
The scheduled enqueued time in UTC. ExpiresAt
DateTime
The expiration time in UTC. MessageId
string
A user-defined value that Service Bus can use to identify duplicate messages, if enabled. ReplyTo
string
The reply to queue address. Subject
string
The application-specific label which can be used in place of the Label
metadata property. To
string
The send to address.
Earlier versions of this extension in the isolated worker process only support binding to messaging-specific types. Additional options are available to Extension 5.x and higher
Functions version 1.x doesn't support isolated worker process. To use the isolated worker model, upgrade your application to Functions 4.x.
Next stepsRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4