Azure Service Bus: decouple agents with business events

Azure Service Bus: decouple agents with business events

The agent finished a tool call and reported that the order was completed. The backend committed the change, but the process crashed before notifying the next service. Or the notification arrived, the consumer did its work, and the acknowledgment was lost. Repeating the call can duplicate the effect; not repeating it can leave the workflow incomplete. The problem is not writing a better response: it is separating what the agent proposed, what the business confirmed, and what each consumer actually did. Between those three things sit two local transactions and a network — and no single point that by itself authorizes the sentence order completed.

Leia em português: Versão em português.

The fact before the message

Scope and evidence: documentation checked on November 8, 2026. The scenario and data are synthetic; the example ran locally in Python/SQLite. Nothing ran in Azure, a Service Bus broker, a real agent, or a Foundry project. The architecture is an application integration proposal, not a native Foundry Service Bus tool.

What is Azure Service Bus in this architecture?

It is the broker between services that do not need to be available at the same time. The official definition is straightforward: “Azure Service Bus is a fully managed enterprise message broker with message queues and publish-subscribe topics.”

Use a queue when competing instances of a consumer share the work. Use a topic with subscriptions when independent services need their own copies, possibly filtered. Two instances of the same subscription compete for that subscription’s work; two subscriptions represent independent destinations.

The choice is less about technology than about tomorrow: if a second service comes to need the same fact, a topic saves you from reopening the producer to add it. Inside a subscription, rules decide what gets in — the reference describes the mechanism: “A subscription rule has a filter to define a condition for the message to be copied into the subscription and an optional action that can modify message metadata.” Filter on envelope properties, not on the body, and treat the filter as routing rather than authorization: it reduces traffic, it does not grant permission. Remember too that a subscription created after the fact does not receive the past; it applies from the next messages onward.

The broker transports messages. An event gets its meaning from the application contract. ConfirmOrder is a command: it requests a change and can be rejected. OrderStateChanged is an event: it reports a change already confirmed. Wrapping model output in JSON does not turn an intention into a fact.

In the Agent Framework design, the question is how agents work together. In A2A, it is how they delegate across boundaries. The scope here is asynchronous integration with business services, not a delegation protocol or agent memory.

The problem it solves

Without that separation, a tool must know every downstream service, wait for every response, and decide what to do when execution stops halfway through. Event-driven architecture separates producers and consumers: “Producers are decoupled from consumers, which means that a producer doesn’t know which consumers are listening.”

Decoupling availability does not eliminate accountability. Define who can confirm the fact, who publishes it, who processes it, and where to query the result. A queue does not invent that contract or automatically compensate for an external action.

A second assumption reshapes the whole design: enterprise brokers deliver at least once. The Idempotent Consumer guidance does not soften it: “It’s impractical to guarantee exactly-once delivery across a distributed system.” The way out is to invert the goal — instead of chasing single delivery, make reprocessing harmless: “When you combine at-least-once delivery with a consumer that ignores duplicates, you achieve effectively-once processing.” Promising that nothing repeats is different from guaranteeing that repeating changes nothing. Only the second promise survives production.

Illustrative scenario: an order moves from confirmed to completed. An authorized service records these states; another maintains a query projection. The agent requests the operation and queries its status. It is not allowed to announce a confirmed event merely because it decided that the operation should happen.

Architecture in five lanes: agent and backend, outbox and Service Bus transport, consumer with inbox and projection, status query, and dead-letter recovery. Arrows distinguish local calls and responsibility boundaries; two local transactions do not form a global transaction.
From command to fact and from fact to consumer. Dashed arrows cross components; they do not represent a global transaction. Tap the diagram to enlarge it.

How it works — step by step

  1. Validate the proposal in the backend. Obtain identity from an authenticated session, apply authorization and domain rules, and check the expected version. An approval field supplied by the model is not authorization. If the agent repeats the same call, a stable command identifier should return the previous result instead of creating a second fact.
  2. Commit the fact and outbox together. Persist the change and its outbound event in the same local transaction. If either write fails, both must roll back. Serialize the final body here: what goes out later is that text, not a fresh assembly at send time.
  3. Publish through a relay. Read pending events, send to the allowed destination, and mark the send only after broker acceptance. Preserve the ID and content on the next attempt. Because two instances can see the same row, protect the read with a row lock, a lease, or partitioning by aggregate — and assume that this send is, by design, at least once.
  4. Receive with PeekLock. Validate the contract and channel provenance. Commit the consumer change and its inbox in the same local transaction. The alternative mode, ReceiveAndDelete, treats the message as settled the moment it leaves the broker: it saves a round trip and loses the message if the transfer fails.
  5. Settle after the commit. Call Complete while the receiver remains open — the guidance is literal: “Settle a message while the receiver and its connection are still open.” If acknowledgment is lost, the next delivery must recognize the work already persisted.
  6. Respond by querying state. Distinguish the source-confirmed operation, message acceptance, and each destination’s processing. One updated consumer does not prove that every subscription has finished. Expose the applied version per consumer: that is what lets you answer already reflected in the projection instead of a generic sent.

Three confirmations, two local transactions

The most expensive mistake is calling three different things success:

Confirmation What it proves What it does not prove
Business commit The change and its event are persisted at the source That the broker received it or the destination did its work
Send acceptance The broker accepted the message That a consumer completed an effect
Consumer commit The local effect and inbox are persisted That settlement reached the broker

The Outbox pattern puts the object and event in the database together; a separate worker handles sending. This closes the window between confirming the business change and losing the notification. The reference sums up the gain: “When you save the business object and its events within the same database transaction, the system guarantees no data loss.” Read that sentence inside its scope: it is atomicity between object and event, not database availability, not a global transaction, and not proof that anyone processed it. It does not close the window between sending and recording acceptance. The relay can resend, and the consumer must be prepared.

At the other end, Idempotent Consumer makes the order explicit: “If the key doesn’t yet exist in the store, process the message and record the key in a single atomic operation, and then acknowledge the message.”

In production there is still the race between concurrent instances. Checking whether the key exists and then writing it is not enough: “Both instances can pass the existence check before either instance commits, so the check alone doesn’t prevent double processing.” Let the database arbitrate with a uniqueness constraint on the inbox key; whichever transaction loses the conflict treats the message as a duplicate, with no extra effect.

That atomicity covers the effect that participates in the local database. The Service Bus transactions page warns that processing code “doesn’t automatically enlist those downstream resources into the same transactional scope”. An external call needs destination-side idempotency or a reconciliation protocol. Uncertainty does not become success, and recording a key before a call does not prove that the call finished.

For the effect that cannot join the transaction — a third-party payment, an email, a file — use two phases: record the key as in progress, perform the action, and update it to completed with the outcome. On redelivery, completed says skip; in progress requires reconciliation before settling, because the previous attempt may have succeeded without being able to report back.

The message contract

My design choice is an explicit envelope, with the minimum information needed to interpret and trace the fact:

Field Responsibility
event_id Stable identity of this occurrence; maps to MessageId
event_type and schema_version Contract type and version
aggregate_id and aggregate_version Business object and order of its changes
occurred_at Fact timestamp, preserved across retries
correlation_id and causation_id Related journey and cause of this occurrence
payload Required data, without copying conversation or credentials

Correlation is not deduplication. Several events in the same journey share CorrelationId. Each consumer needs its own processing record; if several subscriptions share an inbox, include the consumer identity in the key.

Separate transport properties from business data. MessageId, CorrelationId, SessionId, and application properties serve identity, tracing, and routing; the payload holds the fact. Because subscription filters read properties rather than the body, promote to the envelope only the few fields used for routing — type and version usually suffice.

Version the contract from day one. An additive change, with a new optional field, keeps schema_version; a change that breaks older readers requires a new version, a coexistence period, and consumers that explicitly reject what they cannot interpret. A consumer that silently ignores unknown fields trades a visible error for a silent divergence.

In the Python SDK, the mapping can look like this:

import json
from azure.servicebus import ServiceBusMessage


def send_to_service_bus(sender, body, event_id):
    event = json.loads(body)
    message = ServiceBusMessage(
        body,
        message_id=event_id,
        correlation_id=event["correlation_id"],
        subject=event["event_type"],
        content_type="application/json",
        application_properties={
            "schema_version": event["schema_version"],
            "aggregate_version": event["aggregate_version"],
        },
    )
    sender.send_messages(message)

Integration snippet not executed: the sender must already exist, authenticated and authorized for an allowed topic. This snippet does not configure infrastructure or identity. It assumes an entity without mandatory sessions; with sessions, also set session_id and use a session receiver. The application properties carry routing metadata only, checked against the constructor signature in the SDK reference; sensitive data stays out of the envelope. Do not copy it into an incompatible entity.

Deduplication, ordering, and recovery

Duplicate detection acts on sending, within a window. The default is 10 minutes, configurable from 20 seconds to 7 days, in Standard/Premium; Basic does not support it. The source stresses: “No other parts of the message other than the MessageId are considered.” With partitioning, uniqueness uses MessageId+PartitionKey; with sessions, partition key and session ID must match.

Therefore, resending the same ID with different content is not an update: it can be discarded. A new delivery after a failed Complete is not a new send that this window will solve — not least because settlement itself can fail: “The Complete, DeadLetter, or RenewLock operations might fail due to network issues”. At that moment the work is already written in the consumer database, and the next delivery has to recognize it. The inbox is still necessary.

Ordering requires choosing a boundary. Sessions coordinate related messages: “Only one receiver can have a lock on a session.” Use a SessionId per business sequence, not a global session that serializes everything. Sessions are Standard/Premium and do not repair a producer that published versions in the wrong order. DLQ resubmission also disturbs order: “If a dead-lettered message is later moved back to the original queue for reprocessing, the original ordering relative to other session messages is lost because the resubmitted message receives a new enqueue time and sequence number.” That is why the domain version travels inside the event and is checked at the consumer.

Failed deliveries have a budget. The DLQ resource page records the limit: “There’s a limit on the number of attempts to deliver messages for Service Bus queues and subscriptions. The default value is 10.” Every explicit abandon or expired lock increments that count and, once exceeded, the message moves to dead-letter with reason MaxDeliveryCountExceeded. A defect that prevents Complete does not spin forever: it becomes DLQ — and the inbox is what keeps ten attempts from becoming ten effects.

The lock clock is short for anyone reasoning in minutes of conversation: “The default value for the lock duration is 1 minute.” You can renew it, including automatically, but the configurable ceiling is five minutes. Processing that waits on human approval or one more agent turn does not fit that interval: receive it, persist the request as state, and release the lock.

For transient errors, define an attempt budget, deadline, and recovery policy. For an invalid contract or unrecoverable failure, use dead-letter, with a sanitized reason and a named recovery owner. The same page states: “There’s no automatic cleanup of the DLQ.” Removing messages without fixing the cause only restarts the incident.

Documentation discrepancy: the locks/settlement page says the subqueue exists “only when you enable the dead-letter feature”; the DLQ resource page says it does not need to be explicitly created. I follow the resource-specific definition: the DLQ accompanies the queue/subscription. Enabling dead-letter on expiration is a separate configuration, not a generic switch to create that subqueue.

Service Bus is not a permanent archive for new consumers to recover the entire history, either. Retention, settlement, and a separate event archive must be part of the decision.

In practice: fail without repeating the effect

The package includes exemplo_service_bus.py and nine tests. It uses two separate SQLite databases, one for business/outbox and another for inbox/projection. The local relay keeps the entry pending when the send function raises an exception:

def relay_one(db, send):
    row = db.execute("SELECT event_id, body FROM outbox WHERE sent=0 ORDER BY rowid LIMIT 1").fetchone()
    if row is None:
        return False
    event_id, body = row
    send(body, event_id)
    with db:
        db.execute("UPDATE outbox SET sent=1 WHERE event_id=?", (event_id,))
    return True

The consumer validates the event, atomically commits inbox and projection in apply_event, and only then settles the delivery. The atomicity comes from the database, not from the code: the transaction opens with BEGIN IMMEDIATE, and the inbox primary key is the uniqueness constraint that settles ties — here with a single process; in production, between concurrent consumers.

def process_delivery(db, body, settle):
    try:
        event = json.loads(body)
    except (TypeError, ValueError) as error:
        raise ContractError("Invalid JSON") from error
    outcome = apply_event(db, event)
    settle()
    return outcome

Run in the package directory, without installing an SDK or supplying credentials:

python .\exemplo_service_bus.py
python -m unittest -v test_exemplo_service_bus

The failure test injects send acceptance without acknowledgment, commit without settlement, and consumer restart. It delivers version 2 before version 1. The executed output was:

{
  "source_events": 2,
  "send_attempts": 3,
  "simulated_broker_copies": 3,
  "delivery_attempts": 4,
  "outcomes": [
    "settlement_unknown",
    "duplicate",
    "stale",
    "duplicate"
  ],
  "projection_rows": 1,
  "projection_version": 2,
  "projection_status": "completed",
  "inbox_entries": 2
}

These are two events, not three facts because there were three send attempts. The consumer finds its commit after restarting and does not reapply the duplicate. It records the older version as seen without regressing the projection.

Each label maps to a concrete failure: settlement_unknown is the Complete that never came back; the following duplicate is the same message redelivered after the restart; stale is version 1 arriving late and being recorded without knocking down the already applied version 2; the final duplicate closes the cycle by showing that reprocessing does not move the projection. Four deliveries, two inbox rows, one projection row.

The inbox stores event_id plus a fingerprint of the canonical body. If the same identity comes back with different content, the consumer does not pick a winner: it raises a contract error and leaves the case for the DLQ. That covers exactly the blind spot of broker deduplication, which looks only at MessageId.

This works here because events carry complete snapshots — event-carried state transfer, in the literature: the consumer applies the absolute state as an upsert instead of adding a delta. Do not discard intermediate versions of deltas, postings, or increments with this logic: a gap may require waiting, rebuilding, or intervention.

Laboratory limits: it does not emulate Azure AMQP, locks, sessions, TTL, DLQ, or duplicate detection. It does not implement authentication, multiple relay workers, or external effects. The timestamp is synthetic. Tests verify application contracts and failure handling, not the service’s operational guarantees.

Production best practices

  • Separate roles. The agent proposes; the backend confirms; the relay publishes; the consumer records its effect. Send permission is not business authorization.
  • Use an appropriate identity. In Azure compute, prefer managed identity and Data Sender/Data Receiver roles at the narrowest scope. The official guidance is “Grant only the narrowest possible scope.”
  • Protect concurrency and retries. Use a unique inbox key, effects in the same transaction, and relay coordination. For key retention, the rule is explicit: “Retain each record at least as long as the broker can still redeliver the original message.” Include manual DLQ resubmissions in that budget, since they arrive long after the normal window.
  • Version and validate the contract at the edge. An unknown envelope, an unsupported version, or a malformed payload are contract failures: they go to dead-letter with a sanitized reason, not into an infinite retry.
  • Propagate idempotency outward. When the consumer calls another service, pass the idempotency key along and treat an ambiguous response as a pending reconciliation, never as success.
  • Measure the whole path. Outbox age, each subscription’s backlog, applied version, settlement failures, duplicate rate, and DLQ age. An empty queue is not proof of business completion; a rising duplicate rate usually means a short lock or a slow consumer.
  • Bound time holding locks. Do not keep a message locked while a human decides or an agent converses. Model long waits as persisted state.
  • Test the failure, not just the happy path. Acceptance without acknowledgment, commit without settlement, duplicates, out-of-order events, and consumer restart are automated test cases — they run in seconds and spare you from learning the rule in production.
  • Plan resubmission and audit. Define who handles the DLQ, what can be resubmitted, and how to preserve identity/versioning without repeating sensitive effects.

Frequently asked questions (FAQ)

Must every tool call go into a queue?

No. A quick read or an operation that needs an immediate response can remain synchronous. Messaging makes sense when independent availability, asynchronous work, or multiple consumers justify the additional contract. The cost of the queue is not the queue: it is the outbox, the inbox, the versioning, and operating the DLQ.

Does duplicate detection eliminate the inbox?

No. It reduces duplicate submissions within a window; it neither proves that the consumer effect occurred nor prevents redelivery after lost settlement. They are different layers: one trims repeated sends, the other keeps repetition from becoming an effect.

Do sessions guarantee business order?

They coordinate related processing in the broker. You still need to publish in the correct order, control handler concurrency, and check versions, including during resubmissions. Without aggregate_version in the event, a late message looks like news again.

Can an event trigger another agent?

Yes, through application code. That consumer needs the same identity, authorization, and retry contract. Receiving an event does not give an agent freedom to execute any next tool, and chaining agents without an inbox turns an ordinary redelivery into two model runs with real effects.

Can I say the order finished when sending returns?

Only if the completion being reported is message acceptance. For a business statement, query the corresponding authorized state and make clear which stage is complete. When in doubt, prefer the answer that separates what was confirmed from what is still being processed.

Conclusion

Decoupling an agent is not replacing an HTTP call with a message. It is taking away the model’s responsibility to declare effects that only authorized systems can confirm.

Outbox protects the passage from fact to send. Inbox protects against repeating the local effect. Service Bus transports and coordinates the message. The application connects those boundaries, handles uncertainty, and queries the result before responding. The queue makes the workflow more independent; the contract makes that independence reliable.

If you take a single question into your next architecture review, take this one: when the process dies between two steps, which record will prove what already happened? If the answer depends on the text the agent wrote, the boundary does not exist yet.

Official references

Overview · Event-driven architecture · Transactions · Transactional Outbox · Duplicate detection · Locks and settlement · Sessions · Dead-letter queues · Managed identity · Python SDK · Idempotent Consumer.

👉 If you are connecting agents to business systems — especially when failures and retries must not repeat effects — start with the confirmation boundaries.
Want to discuss this architecture? Reach out on LinkedIn.

Leave a Reply