Settling Multiple Azure Service Bus Messages on a Single Request using nodejs

Viewed 166

I am receiving messages from Azure Service Bus using @azure/service-bus

using something like this (simplified)

let receivingMode = ReceiveMode.peekLock;
let sbClient = ServiceBusClient.createFromConnectionString(connectionString);  
let subscriptionClient = this.sbClient.createSubscriptionClient(topicName, subscriptionName);
let receiver = this.subscriptionClient.createReceiver(receivingMode);
let messages = await this.receiver.receiveMessages(maxMessageCount, maxWaitTimeInSeconds);

It is possible that I'll get hundreds of messages per bulk and I saw that I can only complete() one by one, for example:

for (let index = 0; index < messages.length; index++) {
    let message = messages[index];
    await message.complete();
}

This seems that it will be a very slow process... is there a better approach?

2 Answers

Process your messages concurrently. As far as I understand, you should not receive new messages unless you have processed old ones.

const promises = [];
for (let index = 0; index < messages.length; index++) {
    let message = messages[index];
    promises.push(settleMessage(message));
}
await Promise.all(promises);

async function settleMessage(message) {
  // process your message here
  // Use other methods (abandon(), deadLetter(), defer()) depending on processing result;
  // Otherwise, I suggest to use different receiving mode;
  await message.complete();
}

Azure Service Bus does not support batch settlement of messages(as of now).

You can settle the messages one by one, you can follow the approach mentioned in the other answers where you'd await on all the outstanding promises to complete the messages.

Related issue https://github.com/Azure/azure-sdk-for-js/issues/11914 that talks about the similar feature request and the reply from the service team.

Also, the code snippet in the question seems to be using the version 1 of @azure/service-bus SDK.

I'd recommend using the latest version 7.0.0 of @azure/service-bus that has been released recently.

Related