FIELD NOTESAZURE · ARCHITECTURE

The transactional outbox on Azure: Cosmos DB batches and the change feed

An API that saves to Cosmos DB and then sends to Service Bus will one day do only the first. Save the event in the same transactional batch and relay it from the change feed, unless a Service Bus message started the work.

By Glorb4 min readPublished
ON THIS PAGE
An orders API writes an order and its OrderPlaced event to one Cosmos DB partition in one batch. A change feed relay function checkpoints in a lease container and sends to a Service Bus topic with duplicate detection, whose session subscriptions feed invoicing and shipping. Drawn in archhy.

An API that saves an order to Cosmos DB and then sends OrderPlaced to Service Bus will one day crash between the two calls. The transactional outbox closes that gap: save the order and its event as two documents in one transactional batch, and let a relay send the event from the change feed. Build it when the work starts from an HTTP request, or anything else that will not come back. When a Service Bus message starts the work, an idempotent write and duplicate detection usually do the job with less to run.

Which work needs an outbox#

Ask what happens after a crash between the save and the send. A handler fed by a Service Bus message had not completed that message, so its lock expires and it comes back. The second attempt finds the order saved (its create fails with 409), sends the event again, and if the first send had landed after all, duplicate detection drops the copy, because both carry the same MessageId. The incoming message was the outbox. That holds only if the ID comes from the business (order number and event name) and the duplicate window outlasts your redeliveries.

An HTTP handler has no second chance: the caller saw a timeout, and nothing durable records that an event is owed. Service Bus transactions cannot help, because a Cosmos DB write never joins them. That is the outbox's case, as is an entity written concurrently whose events must arrive in commit order: the change feed keeps that order, and racing sends do not. Event-driven architecture on Azure places it among the other patterns.

Two documents, one partition#

A transactional batch is ACID only within one logical partition of one container, and holds at most 100 operations and 2 MB. So the event document sits beside the order, under its partition key, marked by a type field:

Python
container.execute_item_batch(batch_operations=[
    ("create", (order,), {}),
    ("create", ({"id": event_id, "pk": order["pk"], "type": "event",
                 "name": "OrderPlaced", "seq": 1, "data": summary,
                 "ttl": 10 * 86400},), {}),
], partition_key=order["pk"])

Three details matter:

  • Write a new document per event; never publish the order's own changes. In the default latest-version mode, the feed shows only an item's newest version, so two quick updates can surface as one. An event document is written once, so every one appears.
  • The event's ttl does nothing until the container has a default TTL. Set that to -1 (on, never expiring). The TTL is also your recovery window: events a stalled relay has not read by then are gone. Microsoft suggests days, such as ten; the 120 seconds in its sample is not a production value.
  • The partition key is the boundary. An action spanning two customers' documents cannot be one batch; that is a saga.

The relay, and the trap in the easy one#

Microsoft offers two relays: an Azure Functions trigger on the change feed, the least code, and the change feed processor library in a worker you host. They fail differently. When its handler throws, the processor restarts from the last checkpoint in its lease container and redelivers the batch until the handler succeeds. The Functions trigger, by default, does not retry: if the send to Service Bus throws, those events never leave the container. Give the function a retry policy; a maximum count of -1 reruns the batch until Service Bus answers.

Python
@app.cosmos_db_trigger(arg_name="docs", connection="COSMOS",
    database_name="shop", container_name="orders",
    lease_container_name="leases")
@app.retry(strategy="exponential_backoff", max_retry_count="-1",
    minimum_interval="00:00:05", maximum_interval="00:05:00")
def relay(docs: func.DocumentList) -> None:
    events = sorted((d for d in docs if d.get("type") == "event"),
                    key=lambda d: (d["pk"], d["seq"]))
    sender.send_messages([ServiceBusMessage(json.dumps(d["data"]),
        message_id=d["id"], session_id=d["pk"]) for d in events])

An event that can never be sent, too large or malformed, then stalls the relay for good, so catch those and park them in another container. Send with the Service Bus SDK, not an output binding, so that you set both IDs and handle a failed send in your own code. Set StartFromBeginning too: it only matters when no leases exist, which is exactly when the default, starting from now, would skip whatever was waiting.

Order and duplicates downstream#

The change feed keeps order within a partition key, and a SessionId equal to that key carries it into a session-enabled subscription. Documents from one batch, though, share a modification time and can leave the feed in any order: hence seq, and the sort.

With MessageId set to the event's ID, duplicate detection drops whatever a retried batch sends twice. It can only be enabled when the topic is created, and Microsoft advises against combining it with batched sends to a partitioned entity, which its own outbox sample does; use an unpartitioned topic. The window is seven days at most, and a subscriber whose lock expires still sees a message twice, so consumers stay idempotent: see idempotent consumers on Service Bus.

On AWS and Google Cloud#

On AWS the same shape is a DynamoDB transaction, its stream and an EventBridge Pipe. The transaction spans up to 100 items across tables, but the stream keeps records for 24 hours, where a Cosmos DB event stays readable until its TTL. On Google Cloud it is a Spanner transaction read through a change stream, with a Dataflow template that writes the records to Pub/Sub. Neither has Service Bus's configurable duplicate window: SQS FIFO's is five minutes, and Pub/Sub's exactly-once delivery still lets publish-side duplicates through.

The diagram#

The API writes order and event in one batch; a relay function reads the change feed, checkpoints in a lease container and sends to a topic feeding invoicing and shipping. Open it in archhy and press Make a copy to adapt it.

Reference documentation: Transactional Outbox with Azure Cosmos DB, change feed, Functions trigger troubleshooting, Service Bus duplicate detection.