Search Sreeni's Insights

Filter by content type
cloud May 26, 2016 7 min read

Event-driven architecture with Service Bus topics

Azure Service Bus topics and subscriptions explained through fan-out messaging, SQL filters, duplicate delivery, dead-letter handling and explicit event ownership.

Share:

Event-driven architecture with Service Bus topics

An application is rarely doing only one thing when a business event occurs. When an order is created, email, reporting, risk and audit consumers may all need to react. Directly calling every consumer from the Order API is coupling the publisher to every team. In the previous article, we discussed polyglot persistence and why derived stores need a rebuild path. In this article, we are going to see how Azure Service Bus topics and subscriptions can fan out one event using SQL filters.

TL;DR Summary

  • A topic is publishing one message to many subscriptions.
  • Each subscription is giving a consumer its own retry and delivery boundary.
  • SQL filters can select messages such as Region = 'EU' or Amount > 10000.
  • The publisher should not know every subscriber implementation.
  • Consumers must handle duplicate delivery and dead-letter messages.
  • Eventual consistency must be visible to the user and support team.
  • A topic is not a database or a replacement for a transaction boundary.

Challenges

Point-to-point calls are coupling the roadmap

If the Order API directly calls Email, Reporting and Risk, adding one consumer changes the publisher. A slow reporting service also makes order creation slow. The number of synchronous dependencies grows with every new reaction, and the publisher becomes the owner of failures which belong to other teams.

Delivery is not exactly once

A consumer can process a message and fail before completing it. Service Bus can deliver the message again. This is normal distributed-system behaviour, so a consumer must use a business id or message id to make its side effect safe. Otherwise one fund order can create two notifications or two audit entries.

Filters are business rules

Region = 'EU' is not just a technical filter. It decides which reporting team sees a message. If the event does not contain a reliable region or amount, the subscription silently misses work. Filters need tests and monitoring, especially when the event contract changes.

What is an event-driven architecture?

Event-driven architecture is a style where components communicate by publishing and consuming events which describe facts that have happened.

In simple terms, the Order API is saying “an order was created” and interested services decide what they should do. A Service Bus topic is providing the fan-out channel, while a subscription is providing an independent consumer queue.

An everyday analogy is a newspaper edition. The publisher prints one edition, and different delivery routes take copies to subscribers. The publisher is not telephoning every reader to ask whether they are ready. If one route is delayed, the other routes can continue.

Why Service Bus topics are important?

Topics are important when a business fact has several independent reactions and those reactions should not make the original request wait. They support separate retry boundaries and allow a new subscriber to be added without changing the publisher. The trade-off is eventual consistency, so the user interface must explain that reporting or email can be a short time behind the order.

The following diagram depicts the Order API publishing to the orders topic inside a Service Bus namespace:

Service Bus topic and subscriptions
Service Bus topic and subscriptions

The topic has three subscriptions. All is delivering to Email Service, Region = EU is delivering to EU Reporting and Amount > 10K is delivering to Risk Check. The flow highlighted in purple is the EU Reporting path, from the topic through the filtered subscription to the reporting consumer.

Creating the topic and filters

The 2016 .NET client used the Microsoft.ServiceBus.Messaging namespace. A setup operation can create a topic and subscription with a SQL filter:

var manager = NamespaceManager.CreateFromConnectionString(serviceBusConnection);

if (!manager.TopicExists("orders"))
    manager.CreateTopic("orders");

if (!manager.SubscriptionExists("orders", "eu-reporting"))
{
    var description = new SubscriptionDescription("orders", "eu-reporting");
    manager.CreateSubscription(
        description,
        new SqlFilter("Region = 'EU'"));
}

The amount subscription is using another filter:

manager.CreateSubscription(
    new SubscriptionDescription("orders", "risk-check"),
    new SqlFilter("Amount > 10000"));

The actual filter syntax and property names are tested with the message contract. We should not publish regionCode while filtering on Region and assume that the subscription matches.

Publishing and consuming

The Order API is publishing after its local transaction has committed. A production system may use an outbox table when the database transaction and message publication must be made reliable together:

var client = TopicClient.CreateFromConnectionString(
    serviceBusConnection, "orders");

var message = new BrokeredMessage(JsonConvert.SerializeObject(new
{
    OrderId = order.Id,
    FundId = order.FundId,
    Region = order.Region,
    Amount = order.Amount
}));
message.Properties["EventType"] = "OrderCreated";

await client.SendAsync(message);

A consumer is completing only after its side effect is safe:

var receiver = SubscriptionClient.CreateFromConnectionString(
    serviceBusConnection, "orders", "eu-reporting");

receiver.OnMessageAsync(async message =>
{
    var order = JsonConvert.DeserializeObject<OrderCreated>(
        message.GetBody<string>());

    if (!await reportStore.HasProcessedAsync(order.OrderId))
    {
        await reportStore.AddAsync(order);
        await reportStore.MarkProcessedAsync(order.OrderId);
    }
});

The consumer should have a retry policy and a dead-letter review process. A poison message must not be retried forever while hiding healthy messages behind it. Logs should include OrderId, MessageId, subscription name and the exception category.

Trade-offs

ApproachProsCons
Direct HTTP calls+ Immediate response<br>+ Simple initial flow− Publisher is coupled to consumers<br>− One timeout affects the request
Service Bus topic+ Independent consumers and retries<br>+ Fan-out with filters− Eventual consistency<br>− Duplicate delivery and operations

In our case, direct calls are used when the response is required before the order is accepted. Service Bus topics are used for email, reporting and risk reactions which can progress after the order. We do not call a message “processed” until the consumer has persisted its side effect.

Failure handling and event evolution

The publisher is assigning a stable message id and an event type. A consumer is logging the message id before doing work, and it is marking the id as processed only after the report row or email request is durable. If the process is crashing after the side effect but before completion, the next delivery is finding the processed id and is not repeating the side effect.

The consumer owner reviews the dead-letter queue. A malformed message is not retried with the same payload forever. The operator identifies whether the problem is a bad producer, a temporary dependency or a poison document. A corrected message can be replayed deliberately, and the replay is recorded as an operational action.

Event contracts stay small and factual:

{
  "eventType": "OrderCreated",
  "eventVersion": 1,
  "orderId": "ORD-123",
  "fundId": "FUND-123",
  "region": "EU",
  "amount": 12500.00
}

Adding a new optional field is normally safer than changing the meaning of an existing field. A consumer which does not understand the field can continue processing. Renaming amount to value without a version plan can break the SQL filter Amount > 10000, so the subscription is treated as part of the contract.

The event is describing an accepted fact, not asking another service to perform an internal method. OrderCreated is better than CreateOrderInRiskService, because the risk consumer owns how it reacts. This is reducing coupling and allowing a new consumer to be added without changing the publisher.

The publisher also decides what happens when Service Bus is unavailable. The order transaction should not report success if the business requires the event to exist immediately. An outbox record can be committed with the order, and a separate publisher can send it later. The outbox is marked sent only after Service Bus accepts the message.

This approach is making the boundary visible to support. A customer can see an order created while EU Reporting is catching up, and the support dashboard can show the subscription age. The delay is acceptable only when the business has agreed it; a risk check which must block the order is not being moved to a best-effort subscriber.

The topic is also preventing a direct dependency on an email vendor. Email Service can change its provider or retry schedule without changing Order API. The event is carrying the fact that an order was created, and the email consumer is deciding how to format a message for the customer.

Must Do and Don’ts

  • Must Do: Give every event a stable business id, otherwise duplicate delivery cannot be detected.
  • Must Do: Keep subscription filters under contract tests, because one property rename can route no messages.
  • Must Do: Monitor queue length, age and dead-letter count, so a delayed consumer is visible.
  • Must Do: Decide whether the publisher needs an outbox, otherwise a committed order can exist without its event.
  • Don’t: put a large mutable object into every event, because consumers will become coupled to fields they do not own.
  • Don’t: retry a poison message forever, otherwise one bad document will hide the health of the subscription.

Wrap up

In this article, we have looked at Service Bus topics, subscriptions, SQL filters, TopicClient, SubscriptionClient, NamespaceManager.CreateSubscription, duplicate delivery and dead-letter handling. The topic is providing useful independence, but only when the event contract and consumer ownership are clear. Thanks for reading this article. In the next article, I will walk you through security in the cloud with NSGs, Key Vault and least privilege.

Related Posts