Which Azure messaging service to choose to publish with different messages to different subscribers? - azure

From last question about Azure messaging service by publishing one common message to multiply subscribers by using service bus topic. But we've encounter an issue that our message size is over-sized of the service buss limitation(256KB), so we changed our design by splitting the GIANT message into small piece of sub-message and send them to different subscribers, here is what I'd like to achieve:
Let's say we are saving an order object in azure function called SaveOrder and after order was saved successfully, we would like to send different messages(content) to 3 subscribers/consumers which is also implemented/triggered with azure functions,
subscriber/azure function 1 would be using for reporting - with message 1, e.g
{
'reportHeader':'Order Report for ID 012913',
'report_notes':'A few additional report notes...'
}
subscriber/azure function 2 would be using for logging(Sql Server) - with message 2, e.g
{
'logAction':'Order Saved Successfully',
'logTime':'08/12/2019 12:38:12 AM',
'logDescription': 'Order Id - 0139281',
'log_notes':'A few additional log notes...'
}
subscriber/azure function 3 would be using for continuing business logic. - with message 3, e.g
{
'action':'Prepare product accumulation',
'ProductList': {
'813891':3
'581231':1
},
'accumulation_notes':'A few additional accumulation notes...'
}
All of above azure functions subscriber will be working independently/isolated, and our azure function SaveOrder doesn't have to wait for any of these 3 functions, it should exit or terminate once the message publishes.
In this case, which of the messaging service should I choose in Azure for handling that? Would service bus still work here? As my understanding is that Service bus topic would send/publish "same/one" message content to multiply subscribers.

If message1 always only goes to function1, message2 only to function2, and so on, creating 3 Service Bus Queues would suffice. This simply transports the message from a sender to a receiver (function) (FIFO-style).
From SaveOrder, you'd send message1 to queue1, message2 to queue2 etc.
function1 receives messages from queue1.
function2 receives messages from queue2.
function3 receives messages from queue3.
Using topics and subscriptions will also work, by creating 3 topics with 1 subscription each:
From SaveOrder, you'd send message1 to topic1, message2 to topic2 etc.
function1 receives messages from subscription1.
function2 receives messages from subscription2.
function3 receives messages from subscription3.
The second scenario is more flexible, as it allows multiple receivers of the same (copy) message, by adding more subscriptions to the same topic.
Also, you can gzip the payloads of your messages to make transport more efficient.

You can have a separate topic or queue for each of multiple outbound streams. However you should probably publish a single message containing all necessary information to a topic and have three separate consumers do different things with the message.
For instance your function shouldn't be coded to generate an "email notification message" that's not its concern. It should publish an OrderSaved message, and if a service wants to subscribe to that and send emails, it can.

Related

Azure Service Bus - random deserialization issues

I've been recently having problems with my Service Bus queue. Random messages (one can pass and the other not) are placed on the deadletter queue with the error message saying:
"DeadLetterReason": "Moved because of Unable to get Message content There was an error deserializing the object of type System.String. The input source is not correctly formatted."
"DeadLetterErrorDescription": "Des"
This happens even before my consumer has the chance to receive the message from the queue.
The weird part is that when I requeue the message through Service Bus Explorer it passes and is successfully received and handled by my consumer.
I am using the same version of Service Bus either for sending and receiving the messages:
Azure.Messaging.ServiceBus, version: 7.2.1
My message is being sent like this:
await using var client = new ServiceBusClient(connString);
var sender = client.CreateSender(endpointName);
var message = new ServiceBusMessage(serializedMessage);
await sender.SendMessageAsync(message).ConfigureAwait(true);
So the solution I have for now for the described issue is that I implemented a retry policy for the messages that land on the dead-letter queue. The message is cloned from the DLQ and added again to the ServiceBus queue and for the second time there is no problems and the message completes successfully. I suppose that this happens because of some weird performance issues I might have in the Azure infrastructure. But this approach bought me some time to investigate further.

Why do my messages always get delivered to Dead Letter Queue in Azure Service Bus?

C# .NetCore 2.2 -
Azure Service Bus 3.4.0
I have 3 queues in Azure Service Bus with same properties. While sending messages to these queues, the messages in one of the queues always get delivered to Dead letter queues, while other 2 queues receive active messages.
I have tried playing with the properties - increase TTL, maximum delivery count etc. The properties of all 3 queues are same, the only difference is the name of the queues.
I have used this tutorial - https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
queue properties image
static async Task SendMessagesAsync(int numberOfMessagesToSend)
{
try
{
for (var i = 0; i < numberOfMessagesToSend; i++)
{
// Create a new message to send to the queue.
string messageBody = $"Message {i}";
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
Console.WriteLine($"Sending message: {messageBody}");
// Send the message to the queue.
await queueClient.SendAsync(message);
}
}
catch (Exception exception)
{
Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
}
}
How do I prevent messages from going to Dead Letter Queue? Why does it happen with only 1 queue, not the other 2?
When messages are dead-lettered, there is a reason user property gets added. Check that property to see the reason and troubleshoot accordingly. Specifically, check for DeadLetterReason and DeadLetterErrorDescription custom properties.
The common reasons for a message to be dead-lettered are
Maximum transfer hop count exceeded
Session Id Is Null
TTLExpiredException
HeaderSizeExceeded
The messages might also have got dead-lettered due to some errors while receiving the message from the Queue. As Sean Feldman mentioned, looking into the DeadLetterReason and DeadLetterDescription property will help you diagnose the error reason clearly.
Also try to increase or set the time to live of the message sent if the DeadLetterReason is TTLExpiredException. Because if you have set the time to live of the message to a lower value then it will override the time to live property of the Queue.
Check whether the Queue whether the queue where the messages are getting dead-lettered is a Session enabled queue and the message sent has the Session Id value set.
Without seeing your app / messages it's hard to help. But probably there's an error with the application that is trying to consume the message. As it could not be completed, the message goes to the dead letter queue.
Log the messages from this particular queue and see if there's any missing required properties. Sometimes you're trying to deserialize to an uncompatible type.
The purpose of the dead-letter queue is to hold messages that cannot
be delivered to any receiver, or messages that could not be processed.

Receiving empty bytes array for Imessage.content from Azure service bus

I am currently using two different platforms to perform sync actions. So, when action happens on platform 1 (C# -visual studio), that same action then needs to happen on platform 2 (Java). To do that, I use SB (Azure service bus) for sharing the Json messages between two platforms.
Action 1: platform 1 ----> Service bus -----> platform 2 .
Works fine. The message is sent and received exactly as it should be.
Action 2: platform 2 ----> Service bus ----> platform 1.
Does not work. The message is sent correctly to SB, but when it's picked up, the content property only contains an empty array, when it should be an array of bytes (containing the message). The other message attributes like contentType, replyTo and so on are set correctly, so the message is getting picked up fine. It's just that there is no content or in other words message body.
Action 3: Azure SB/Send messages -----> Service bus -----> platform 1.
Works fine. Another option is to send the JSON message directly to the Service Bus using Azure Service Bus/Send messages and put the JSON message in there.
For actions 2 and 3 exactly the same message is sent to the service bus (when I view it). One is sent directly to service bus, another is generated by the platform 2. I think the actual message somehow seems to be different in the background, which is why the message body is empty in the action 2.
Threads and processes are being handled correctly.
To set up receiver:
IMessageReceiver receive r= null;
if (config.isSessionsEnabled()) {
receiver = ClientFactory.acceptSessionFromConnectionStringBuilder(new ConnectionStringBuilder(connString), config.getSessionID(), ReceiveMode.PEEKLOCK);
} else {
receiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(new ConnectionStringBuilder(connString), ReceiveMode.PEEKLOCK);
}
For receiving message:
try {
message = receiver.receive(Duration.ofSeconds(1)); //message.Content will be empty array
if(message != null){
//process message
}
} catch (Exception e) {
}
}
Is my understanding correct or perhaps there is another explanation to it!
Is my understanding correct or perhaps there is another explanation to it!
It is very odd that if you send the message from Java platform and the content of message is empty.
Based on my understanding, it seems that message content is empty when you send to ABS. I recommand that you could check the Java send message code before sending to ABS.
You alse could use Azure Service bus exploer to get the message information after it sent to ABS [Before received from .Net platform].

How to listen to a queue using azure service-bus with Node.js?

Background
I have several clients sending messages to an azure service bus queue. To match it, I need several machines reading from that queue and consuming the messages as they arrive, using Node.js.
Research
I have read the azure service bus queues tutorial and I am aware I can use receiveQueueMessage to read a message from the queue.
However, the tutorial does not mention how one can listen to a queue and read messages as soon as they arrive.
I know I can simply poll the queue for messages, but this spams the servers with requests for no real benefit.
After searching in SO, I found a discussion where someone had a similar issue:
Listen to Queue (Event Driven no polling) Service-Bus / Storage Queue
And I know they ended up using the C# async method ReceiveAsync, but it is not clear to me if:
That method is available for Node.js
If that method reads messages from the queue as soon as they arrive, like I need.
Problem
The documentation for Node.js is close to non-existant, with that one tutorial being the only major document I found.
Question
How can my workers be notified of an incoming message in azure bus service queues ?
Answer
According to Azure support, it is not possible to be notified when a queue receives a message. This is valid for every language.
Work arounds
There are 2 main work arounds for this issue:
Use Azure topics and subscriptions. This way you can have all clients subscribed to an event new-message and have them check the queue once they receive the notification. This has several problems though: first you have to pay yet another Azure service and second you can have multiple clients trying to read the same message.
Continuous Polling. Have the clients check the queue every X seconds. This solution is horrible, as you end up paying the network traffic you generate and you spam the service with useless requests. To help minimize this there is a concept called long polling which is so poorly documented it might as well not exist. I did find this NPM module though: https://www.npmjs.com/package/azure-awesome-queue
Alternatives
Honestly, at this point, you may be wondering why you should be using this service. I agree...
As an alternative there is RabbitMQ which is free, has a community, good documentation and a ton more features.
The downside here is that maintaining a RabbitMQ fault tolerant cluster is not exactly trivial.
Another alternative is Apache Kafka which is also very reliable.
You can receive messages from the service bus queue via subscribe method which listens to a stream of values. Example from Azure documentation below
const { delay, ServiceBusClient, ServiceBusMessage } = require("#azure/service-bus");
// connection string to your Service Bus namespace
const connectionString = "<CONNECTION STRING TO SERVICE BUS NAMESPACE>"
// name of the queue
const queueName = "<QUEUE NAME>"
async function main() {
// create a Service Bus client using the connection string to the Service Bus namespace
const sbClient = new ServiceBusClient(connectionString);
// createReceiver() can also be used to create a receiver for a subscription.
const receiver = sbClient.createReceiver(queueName);
// function to handle messages
const myMessageHandler = async (messageReceived) => {
console.log(`Received message: ${messageReceived.body}`);
};
// function to handle any errors
const myErrorHandler = async (error) => {
console.log(error);
};
// subscribe and specify the message and error handlers
receiver.subscribe({
processMessage: myMessageHandler,
processError: myErrorHandler
});
// Waiting long enough before closing the sender to send messages
await delay(20000);
await receiver.close();
await sbClient.close();
}
// call the main function
main().catch((err) => {
console.log("Error occurred: ", err);
process.exit(1);
});
source :
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-nodejs-how-to-use-queues
I asked myslef the same question, here is what I found.
Use Google PubSub, it does exactly what you are looking for.
If you want to stay with Azure, the following ist possible:
cloud functions can be triggered from SBS messages
trigger an event-hub event with that cloud function
receive the event and fetch the message from SBS
You can make use of serverless functions which are "ServiceBusQueueTrigger",
they are invoked as soon as message arrives in queue,
Its pretty straight forward doing in nodejs, you need bindings defined in function.json which have type as
"type": "serviceBusTrigger",
This article (https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus#trigger---javascript-example) probably would help in more detail.

How to guarantee azure queue FIFO

I understand that MS Azure Queue service document http://msdn.microsoft.com/en-us/library/windowsazure/dd179363.aspx says first out (FIFO) behavior is not guaranteed.
However, our application is such that ALL the messages have to be read and processed in FIFO order. Could anyone please suggest how to achieve a guaranteed FIFO using Azure Queue Service?
Thank you.
The docs say for Azure Storage queues that:
Messages in Storage queues are typically first-in-first-out, but sometimes they can be out of order; for example, when a message's
visibility timeout duration expires (for example, as a result of a
client application crashing during processing). When the visibility
timeout expires, the message becomes visible again on the queue for
another worker to dequeue it. At that point, the newly visible message
might be placed in the queue (to be dequeued again) after a message
that was originally enqueued after it.
Maybe that is good enough for you? Else use Service bus.
The latest Service Bus release offers reliable messaging queuing: Queues, topics and subscriptions
Adding to #RichBower answer... check out this... Azure Storage Queues vs. Azure Service Bus Queues
MSDN (link retired)
http://msdn.microsoft.com/en-us/library/windowsazure/hh767287.aspx
learn.microsoft.com
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-azure-and-service-bus-queues-compared-contrasted
Unfortunately, many answers misleads to Service Bus Queues but I assume the question is about Storage Queues from the tags mentioned. In Azure Storage Queues, FIFO is not guranteed, whereas in Service Bus, FIFO message ordering is guaranteed and that too, only with the use of a concept called Sessions.
A simple scenario could be, if any consumer receives a message from the queue, it is not visible to you when you are the second receiver. So you assume the second message you received is actually the first message (Where FIFO failed :P)
Consider using Service Bus if this is not your requirement.
I don't know how fast do you want to process the messages, but if you need to have a real FIFO, don't allow Azure's queue to get more than one message at a time.
Use this at your "program.cs" at the top of the function.
static void Main()
{
var config = new JobHostConfiguration();
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
config.Queues.BatchSize = 1; //Number of messages to dequeue at the same time.
config.Queues.MaxPollingInterval = TimeSpan.FromMilliseconds(100); //Pooling request to the queue.
JobHost host = new JobHost(config);
....your initial information...
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
This will get one message at a time with a wait period of 100 miliseconds.
This is working perfectly with a logger webjob to write to files the traze information.
As mentioned here https://www.jayway.com/2013/12/20/message-ordering-on-windows-azure-service-bus-queues/ ordering is not guaranteed also in service bus, except of using recieve and delete mode which is risky
You just need to follow below steps to ensure Message ordering.:
1) Create a Queue with session enabled=false.
2) While saving message in the queue, provide the session id like below:-
var message = new BrokeredMessage(item);
message.SessionId = "LB";
Console.WriteLine("Response from Central Scoring System : " + item);
client.Send(message);
3) While creating receiver for reviving message:-
queueClient.OnMessage(s =>
{
var body = s.GetBody<string>();
var messageId = s.MessageId;
Console.WriteLine("Message Body:" + body);
Console.WriteLine("Message Id:" + messageId);
});
4) While having the same session id, it would automatically ensure order and give the ordered message.
Thanks!!

Resources