Lesson 1 of 3 Message Queuing with Azure Service Bus

Understanding Azure Service Bus

This lesson explains why message brokers are used, Service Bus namespaces, tiers and messages, sending and receiving from Python, and peek-lock settlement.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain load levelling and competing consumers.
  • Compare the Basic, Standard and Premium tiers.
  • Describe the four settlement actions.
  • Explain the effect of lock duration.

Why a message broker

Many back-end operations in AI solutions are slow or bursty: generating embeddings for an uploaded document set, calling a model to summarize a long transcript, or exporting results. If an API performs such work while the caller waits, requests time out and spikes overload downstream services. A message broker decouples the two sides. The API places a message describing the work in a queue and returns at once; one or more workers take messages from the queue and process them at their own pace.

Azure Service Bus provides this with durable storage, so messages survive restarts; load levelling, so bursts wait in the queue rather than overwhelming workers; competing consumers, so adding workers increases throughput; and features for reliability such as locks, retries, dead-lettering, sessions, duplicate detection, scheduled delivery and transactions.

The following diagram shows a summarization API decoupled from its processing with a Service Bus queue.

Decoupling the summarization API with a Service Bus queue. The API stores each transcript in Blob Storage, sends a message with the blob reference and a message_id equal to the transcript ID, and returns 202 Accepted. Workers receive in peek-lock mode, renew locks while the model works, write the summary idempotently and then complete the message, so the queue levels the Monday burst.
The queue holds a reference to the transcript, not the transcript itself.
Match the pairs

What a broker gives you

Exam skills 3.1.1

Match each Service Bus capability with the problem it solves.

Log in to try this activity Interactive activities are free with an account.

Namespaces, tiers and entities

A namespace, reached at NAMESPACE.servicebus.windows.net, is the container for messaging entities: queues, which deliver each message to one receiver, and topics with subscriptions, which deliver a copy to each subscription, as described in the next topic. The namespace's tier decides the available features and the capacity model.

Basic
QueuesYes
Topics, sessions, duplicate detection, transactionsNo
CapacityShared, pay per operation
Maximum message size256 KB
Private endpoints and virtual network rulesNo
Choose when Simple queues on a budget
Standard
QueuesYes
Topics, sessions, duplicate detection, transactionsYes
CapacityShared, pay per operation
Maximum message size256 KB
Private endpoints and virtual network rulesNo
Choose when Most applications that need topics and reliability features
Premium
QueuesYes
Topics, sessions, duplicate detection, transactionsYes
CapacityDedicated messaging units
Maximum message sizeUp to 100 MB
Private endpoints and virtual network rulesYes
Choose when Predictable performance, large messages, network isolation

Queue properties are set when the entity is created, and some cannot be changed later. The most important are the lock duration (how long a receiver holds a message, default one minute, maximum five), the maximum delivery count (default 10), the default time to live, and switches for sessions, duplicate detection and dead-lettering on expiration.

Scenario questions

Tiers and queue properties

Exam skills 3.1.1

Choose the Service Bus tier or queue setting that fits each requirement.

Log in to try this activity Interactive activities are free with an account.

Messages

A message has a body, which is opaque to Service Bus and usually JSON, and properties. System properties include message_id (used for duplicate detection), correlation_id, session_id, subject, content_type, time_to_live and scheduled_enqueue_time_utc. Application properties are custom key-value pairs, such as priority or tenant, which subscription filters can evaluate without reading the body.

Messages should carry references to large data rather than the data itself. A message such as {"documentId": "d-781", "blob": "https://..."} stays well within the 256 KB limit, while the document stays in Blob Storage. This is called the claim check pattern.

Sort into groups

Body or properties?

Exam skills 3.1.1

Decide where each piece of information belongs in a Service Bus message.

Log in to try this activity Interactive activities are free with an account.

Sending and receiving from Python

The azure-servicebus library connects with a ServiceBusClient and DefaultAzureCredential. The identity needs Azure Service Bus Data Sender to send, Azure Service Bus Data Receiver to receive, or Azure Service Bus Data Owner for both and for management. Senders batch messages for efficiency.

import json
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient, ServiceBusMessage

client = ServiceBusClient("NAMESPACE.servicebus.windows.net", credential=DefaultAzureCredential())

with client.get_queue_sender("embed-jobs") as sender:
    batch = sender.create_message_batch()
    for doc_id in ["d-781", "d-782"]:
        batch.add_message(ServiceBusMessage(json.dumps({"documentId": doc_id}),
                                            message_id=doc_id, application_properties={"tenant": "contoso"}))
    sender.send_messages(batch)

with client.get_queue_receiver("embed-jobs", max_wait_time=5) as receiver:
    for msg in receiver.receive_messages(max_message_count=10):
        job = json.loads(str(msg))
        process(job)                       # do the work
        receiver.complete_message(msg)     # remove it from the queue
Sort into groups

Which Service Bus role?

Exam skills 3.1.1

Choose the least-privilege Service Bus data role for each identity.

Log in to try this activity Interactive activities are free with an account.

Peek-lock and settlement

The default receive mode is peek-lock. The receiver obtains the message and a lock, which hides it from other receivers for the lock duration. The receiver must then settle the message in one of four ways.

  • Complete: the work succeeded; the message is deleted.
  • Abandon: the work failed but may succeed later; the lock is released and the message becomes available again, with its delivery count increased.
  • Defer: the message cannot be processed yet; it stays in the queue but can only be received by its sequence number.
  • Dead-letter: the message can never be processed; it moves to the dead-letter queue with a reason.

If the receiver crashes or the lock expires before settlement, the message also becomes available again and its delivery count increases. This gives at-least-once processing, so handlers must be idempotent. Long-running work must renew the lock, which the Python SDK's AutoLockRenewer does automatically; otherwise another receiver may process the same message in parallel. The alternative receive-and-delete mode removes the message as soon as it is received, which is faster but loses the message if processing fails.

Lock duration

A worker that takes three minutes per message on a queue with a one-minute lock duration, and does not renew the lock, will see each message processed several times by different workers. The fix is lock renewal or a longer lock duration, not a larger maximum delivery count.

Match the pairs

Settling a message

Exam skills 3.1.1

Match each situation with the settlement a worker should use.

Log in to try this activity Interactive activities are free with an account.
Worked example

Decoupling a summarization API

An API accepts meeting transcripts and returns a summary generated by a language model. Summaries take up to 90 seconds, and Monday mornings bring bursts of 5,000 requests in ten minutes, causing timeouts and throttling at the model endpoint. Every transcript must be processed exactly once in effect, and no connection strings may be stored.

The API should store each transcript in Blob Storage, send a Service Bus queue message with the blob reference and a message_id equal to the transcript ID, and return 202 Accepted. Workers receive in peek-lock mode, renew locks with AutoLockRenewer, write the summary idempotently and then complete the message. Enabling duplicate detection discards accidental re-sends, and the queue levels the Monday burst so the model endpoint sees a steady rate. All clients use DefaultAzureCredential with Data Sender or Data Receiver roles.

Receive-and-delete would lose transcripts when a worker crashes. Calling the model synchronously in the API keeps the timeouts. Putting whole transcripts in messages risks exceeding the 256 KB limit on Standard.

Check yourself

A message is received in peek-lock mode and the worker crashes before settling it. What happens?

Show answer

When the lock expires, the message becomes available again and its delivery count increases, so another receiver processes it. This is at-least-once delivery.

Exam Tips

Remember for the exam

  • Basic has queues only; topics, sessions, duplicate detection and transactions need Standard or Premium.
  • Peek-lock: complete, abandon, defer or dead-letter; an expired lock redelivers the message.
  • Default lock duration is one minute (maximum five); renew locks for long work.
  • Use Data Sender and Data Receiver roles with DefaultAzureCredential; keep large payloads in Blob Storage.