Service Bus queues and topics

Microsoft Azure · Practical · 14 min

Service Bus is the reliable backbone for commands and business events between services.

Azure Service Bus is a fully managed message broker. A namespace contains:

  • Queues: point-to-point; competing consumers each take different messages.
  • Topics with subscriptions (Standard tier and up): publish once, every subscription gets a copy, optionally filtered with SQL or correlation filters.

Receiving uses peek-lock by default: the message is locked for the consumer, which then completes it (removes), abandons it (makes it available again) or dead-letters it. If the lock expires, it is redelivered. After MaxDeliveryCount (default 10) failed deliveries, the broker moves it to the dead-letter queue (DLQ), a sub-queue you must monitor and drain.

Other features that set it apart from Queue Storage:

  • Sessions: messages with the same SessionId are delivered in order to one consumer at a time (FIFO per key).
  • Duplicate detection by MessageId within a time window.
  • Scheduled messages, deferral, and transactions across operations in one namespace.
  • Larger messages: 256 KB in Standard, up to 100 MB in Premium. Premium also adds dedicated capacity, VNet/private endpoints and zone redundancy.

Use Service Bus for commands and high-value events where ordering, exactly-what-happened tracking and retries matter.

Example

# pip install azure-servicebus azure-identity
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient, ServiceBusMessage

ns = "sb-orders.servicebus.windows.net"
with ServiceBusClient(ns, DefaultAzureCredential()) as client:
    with client.get_queue_sender("orders") as sender:
        sender.send_messages(ServiceBusMessage('{"id": "o-1001"}', message_id="o-1001",
                                               session_id="c-42"))

    with client.get_queue_receiver("orders", session_id="c-42", max_wait_time=5) as rx:
        for msg in rx:
            try:
                print("handling", str(msg))
                rx.complete_message(msg)
            except ValueError:
                rx.dead_letter_message(msg, reason="bad-payload")

Remember

  • Queues for point-to-point, topics + subscriptions for pub/sub
  • Peek-lock: complete, abandon or dead-letter
  • Monitor the DLQ: failed messages wait there forever
  • Sessions give ordered processing per key

Watch out for

  • Never reading the dead-letter queue, so failed orders silently pile up.

Check yourself

  1. You need all messages for the same customer processed in order. Which feature do you use?
  2. What happens after a message fails delivery more than MaxDeliveryCount times?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview