Search Sreeni's Insights

Filter by content type
cloud September 29, 2015 7 min read

How to send and receive messages with Azure Service Bus queues?

Azure Service Bus queues explained through asynchronous work, queue creation, BrokeredMessage handling, workers, completion, and dead-letter messages for reliable background work.

Share:

How to send and receive messages with Azure Service Bus queues?

Some work does not need to happen during the user’s web request. Generating a report, resizing a news image or sending a notification can take time, and making the customer wait for every operation increases response time. It also means a temporary failure in the dependency can fail the front door of the application, hence we should be moving this work behind a queue.

Azure Service Bus queues help us separate the producer of a message from the worker which processes it. In this article, we are going to see how to create a queue and send and receive messages from an ASP.NET application using the WindowsAzure.ServiceBus package.

We can process work in two common ways:

ApproachProsCons
Synchronous request processing+ Simple response flow<br>+ Immediate result− User waits for dependencies<br>− Temporary failure reaches the front door
Azure Service Bus queue+ Buffers work and retries<br>+ Worker can scale separately− Result is asynchronous<br>− Requires duplicate and poison-message handling

TL;DR Summary

  • A queue buffers work between a producer and a consumer.
  • The web request should send a small command and return quickly.
  • A worker must complete or abandon a message deliberately.
  • Peek-lock processing prevents a message from being removed before successful work.
  • Messages should be idempotent because a retry can process them more than once.
  • Poison messages need a dead-letter or operational handling plan.

Challenges

Slow front door

When a web request performs every downstream operation synchronously, its response time depends on the slowest operation. The customer may click submit once and wait while several systems are called. A queue lets the front liner acknowledge the request and process the remaining work separately.

Temporary failures

An email service or image processor may be unavailable for a short period. Without a queue, the request fails immediately and the user may submit again, creating duplicate work. With a queue, the worker can retry according to a controlled policy.

Duplicate processing

A message can be delivered again when the worker crashes after doing the business action but before completing the message. We must make the operation idempotent, otherwise one article may receive two notifications or one payment-like action may be applied twice.

What is an Azure Service Bus queue?

An Azure Service Bus queue is a durable stream of messages which allows one producer to communicate asynchronously with one or more competing consumers. FIFO ordering is not guaranteed for an ordinary queue, it is available when we use Service Bus sessions and process messages according to the session.

In simple terms, the web application places an instruction into a mailbox and a worker takes the instruction when it is ready. The message contains enough information to find the business record, but it should not become a large copy of the whole record.

Why use a queue?

Queues absorb a difference in speed between a producer and a consumer. A newspaper office can accept article submissions during a busy hour and editors can process them when capacity is available. The queue does not remove the work, it gives us a controlled place to wait and observe it.

How to use Service Bus queues?

The following diagram depicts a web application, a queue and a worker,

Azure Service Bus queue message flow
Azure Service Bus queue message flow

Option1: Azure Service Bus queue

Steps to Implement:

Follow the following instructions to create and use a Service Bus queue.

  • Create a Service Bus namespace and queue in the Azure portal.

    Namespace: <namespace name>
    Queue: <queue name>
  • Copy a send/listen connection string with the required permissions.

  • Install the WindowsAzure.ServiceBus package.

    Install-Package WindowsAzure.ServiceBus
  • Create the queue from code when the namespace is first provisioned, and replace the input place holders with actual values.

    NamespaceManager manager =
        NamespaceManager.CreateFromConnectionString(
            ConfigurationManager.ConnectionStrings["ServiceBus"].ConnectionString);
    
    string queueName = "<queue-name>";
    if (!manager.QueueExists(queueName))
    {
        QueueDescription description = new QueueDescription(queueName)
        {
            MaxDeliveryCount = 10,
            LockDuration = TimeSpan.FromMinutes(1)
        };
        manager.CreateQueue(description);
    }
  • Create a queue client using the QueueClient type.

    string connectionString =
        ConfigurationManager.ConnectionStrings["ServiceBus"].ConnectionString;
    QueueClient client = QueueClient.CreateFromConnectionString(
        connectionString, "<queue-name>");
  • Send a small command message from the web application.

    var command = new
    {
        ArticleId = articleId,
        RequestedBy = userName
    };
    
    string body = JsonConvert.SerializeObject(command);
    BrokeredMessage message = new BrokeredMessage(body);
    message.Properties["MessageType"] = "ArticlePublished";
    client.Send(message);
  • Create a worker which receives messages using peek-lock mode.

    client.OnMessage(message =>
    {
        try
        {
            string body = message.GetBody<string>();
            ProcessArticlePublished(body);
            message.Complete();
        }
        catch (Exception)
        {
            message.Abandon();
        }
    }, new OnMessageOptions
    {
        AutoComplete = false,
        MaxConcurrentCalls = 1
    });
  • Host the worker in a Cloud Service worker role or a WebJob, not inside an ordinary request which can finish before processing is complete.

  • Make the business handler idempotent by recording the message identifier or processing state.

  • Just to pulse check, send one test message and check that the worker receives and completes it.

    Queue metrics > Active messages: 0
    Worker log > ArticlePublished processed

    Note: Do not place passwords or large file contents in a message. Put a storage blob name or business identifier in the message and retrieve the current data in the worker.

  • Monitor active, dead-letter and scheduled message counts, and configure an operational alert for messages which are not being processed.

Completion and retry

Complete removes the message after the work succeeds. Abandon releases it so the queue can deliver it again. A worker should not catch an exception and complete the message, because that silently loses the work. At the same time, infinite retries can block the queue, so the process must identify poison messages and move them to a dead-letter path after the configured delivery limit.

The handler should check current state before applying a command. For example, if ArticlePublished has already set the article status to Published, receiving the same message again should do nothing and still complete the message. This is the same as pressing an idempotent button: pressing it twice leaves the final state unchanged.

Keep the message contract versioned when the worker and producer are released independently. Add optional properties before removing old ones, and reject an unknown message type in a visible way. The queue should be part of the operational dashboard, because a growing active count is an early signal that the worker is slower or unhealthy.

Dead-letter messages

When a message reaches its maximum delivery count, Service Bus moves it to the dead-letter subqueue. We should not ignore this queue, because it is the place where messages requiring investigation are staying. Read it with a dedicated client,

string deadLetterPath =
    QueueClient.FormatDeadLetterPath("<queue-name>");
QueueClient deadLetterClient =
    QueueClient.CreateFromConnectionString(
        connectionString, deadLetterPath);

The support process should record why the message failed, fix the root cause, and replay it only when the operation is safe. It is better to have visible poison messages than to catch every exception and complete the message, because silent completion is losing customer work.

Message design checklist

Keep the message small and put a business identifier in it, for example ArticleId and MessageType. The worker can read the current article from the system of record, so an old message is not carrying a complete stale copy of the article. Include a correlation identifier when the request is starting from a web call, because operations are needing one way to follow the work end to end.

The producer should be returning a clear accepted response when work is queued, and the UI should not be promising that the notification is already delivered. This small difference is important, otherwise the customer is seeing a success screen while the worker is still retrying. It is also making the reactive support call easier to diagnose.

Wrap up

In this article, we have looked at the need for asynchronous work, created an Azure Service Bus queue, sent a BrokeredMessage, hosted a worker, and handled completion and dead-letter messages. I really appreciate that you took the time to read this article. In the next article, I will walk you through documenting ASP.NET Web API with Swagger.

Related Posts