Azure Service Bus is Microsoft’s enterprise messaging service. But should you use queues or topics? Here’s the difference and when to use each.
Queues: Point-to-Point
Queues deliver messages to a single receiver. First-in, first-out. Perfect for work distribution:
// Send to queue
var client = new QueueClient(connectionString, "orders");
var message = new Message(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(order)));
await client.SendAsync(message);
// Receive from queue (competing consumers)
client.RegisterMessageHandler(async (message, token) =>
{
var order = JsonSerializer.Deserialize<Order>(message.Body);
await ProcessOrder(order);
await client.CompleteAsync(message.SystemProperties.LockToken);
},
new MessageHandlerOptions(ExceptionHandler));
Topics: Publish-Subscribe
Topics deliver messages to multiple subscribers. Each subscriber has its own subscription:
// Publish to topic
var topicClient = new TopicClient(connectionString, "orders");
await topicClient.SendAsync(message);
// Subscribe
var subClient = new SubscriptionClient(connectionString, "orders", "email-notifications");
subClient.RegisterMessageHandler(async (msg, token) =>
{
await SendEmailNotification(msg);
await subClient.CompleteAsync(msg.SystemProperties.LockToken);
}, options);
When to Use Which
- Queue: Work items processed by one consumer (order processing, job queue)
- Topic: Events consumed by multiple systems (order placed → notify, invoice, inventory)
Subscription Filters
Topics support filtering—subscribers only get messages they care about:
// SQL filter
var rule = new RuleDescription("HighValueOrders", new SqlFilter("Amount > 1000"));
await subscriptionClient.AddRuleAsync(rule);
Key Features
- Dead-letter queue: Failed messages go here for inspection
- Sessions: Ordered processing for related messages
- Scheduled messages: Deliver at a future time
- Duplicate detection: Automatic deduplication
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.