Skip to content

[Mocha] Fix saga replies being lost when the sending instance stops - #10500

Draft
tobias-tengler wants to merge 8 commits into
mainfrom
tte/saga-durable-replies
Draft

tobias-tengler wants to merge 8 commits into
mainfrom
tte/saga-durable-replies

Conversation

@tobias-tengler

@tobias-tengler tobias-tengler commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

A saga sent the replies and faults for its requests to the temporary reply queue of the instance that ran the step. If that instance stopped or crashed before the reply arrived, the queue was deleted along with the reply, and the saga stayed pending even though other instances run the same saga. A second, smaller window lost replies on a single instance: the saga dispatched the command of a transition before its state was saved, so a fast reply could be consumed, find no state, and be discarded.

Durable saga reply queue

Each saga with reply or fault transitions gets a durable reply queue ({service}.{saga}_reply) that all instances share, and the replies and faults of the saga's requests, sends and publishes are addressed to it. Like the instance reply queue, it only carries the saga's reply routes, gets no topology bindings or skipped and error queues, and discards replies no transition handles. Transports opt in through RoutingStrategy.CreateReplyEndpointConfiguration, which the InMemory, RabbitMQ, Postgres and Azure Service Bus transports implement; a transport that returns null keeps the instance reply queue. The saga resolves its reply address once per transport through a lock-free cache.

Deferred dispatch

The consumer pipeline now holds the messages a consumer publishes, sends or replies with until the consumer attempt has completed, and releases them in dispatch order. The new DeferredDispatch middleware sits after Retry, so the saga transaction and the EF UseTransaction() commit before anything leaves, and every retry attempt gets its own hold. A failed attempt discards its messages, so a handler that publishes and then throws no longer produces the event twice.

  • Capture happens at the dispatch terminal, below the outbox and scheduling middlewares. With the Postgres outbox nothing reaches the hold, and the saga state and the outbox rows still commit together. Scheduled messages keep going to the scheduling store.
  • RequestAsync is not held, so request/reply inside a handler keeps working. Dispatches outside a consumer scope, including the receive middlewares, are unchanged.
  • ImmediateDispatch on SendOptions, PublishOptions and ReplyOptions lets a single message leave at once. It also bypasses the outbox, the same semantics as NServiceBus's RequireImmediateDispatch.
  • A held message that fails to leave does so after the handler's work has committed, and the attempt is retried or faulted with that state in place. This is at-least-once delivery; the outbox stays the exactly-once answer.

Telemetry

A held dispatch is reported as a create operation when it is captured: its span under the consumer span carries the trace context that goes into the message headers and no longer counts as a sent message. The release runs under a {consumer} dispatch span with one publish span per message, so span duration, the sent-message metric and DispatchError follow the transport call. MessagingOperationType gains Create.

Also in this PR

  • The saga logs a warning when a message with a saga id finds no state, instead of discarding it silently.
  • The Azure Service Bus queue-deletion recovery test attaches the receive link before deleting the queue.
  • Docs: a "Deferred dispatch" section in the reliability page, the consumer pipeline listings, the saga intro and reply-queue paragraphs, the transport naming tables, and the observability page.

Behavior changes

  • Deferred dispatch is on for every consumer. Responses and acknowledgements arrive after the handler's transaction commits, and a handler that waits inside the same handler for a consequence of its own send times out. Use ImmediateDispatch for a message that has to leave while the handler runs.
  • Saga replies move from the instance reply queue to {service}.{saga}_reply on the four built-in transports.

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Patch coverage

97.3% of changed lines covered (284/292)

File Covered Changed Patch %
src/Mocha/src/Mocha/Transport/RoutingStrategy.cs 21 24 87.5% 🟡
…/Middlewares/Consume/DeferredDispatchConsumeMiddleware.cs 40 43 93.0% 🟡
…/src/Mocha/Middlewares/Dispatch/DeferredDispatchScope.cs 77 79 97.5% 🟡
src/Mocha/src/Mocha.Outbox/DispatchOutboxMiddleware.cs 1 1 100.0% 🟢
…/Topology/AzureServiceBusRoutingStrategy.cs 10 10 100.0% 🟢
…/Mocha.Transport.InMemory/Topology/InMemoryRoutingStrategy.cs 10 10 100.0% 🟢
…/Mocha.Transport.Postgres/Topology/PostgresRoutingStrategy.cs 10 10 100.0% 🟢
…/Mocha.Transport.RabbitMQ/Topology/RabbitMQRoutingStrategy.cs 10 10 100.0% 🟢
src/Mocha/src/Mocha/Builder/MessageBusBuilderExtensions.cs 1 1 100.0% 🟢
src/Mocha/src/Mocha/Builder/MessageBusOptions.cs 1 1 100.0% 🟢
src/Mocha/src/Mocha/Endpoints/DispatchEndpoint.cs 11 11 100.0% 🟢
src/Mocha/src/Mocha/Execution/PublishOptions.cs 1 1 100.0% 🟢
src/Mocha/src/Mocha/Execution/ReplyOptions.cs 1 1 100.0% 🟢
src/Mocha/src/Mocha/Execution/SendOptions.cs 1 1 100.0% 🟢
src/Mocha/src/Mocha/Features/DeferredDispatchFeature.cs 10 10 100.0% 🟢
src/Mocha/src/Mocha/Features/ImmediateDispatchFeature.cs 7 7 100.0% 🟢
…/Mocha/Instrumentation/ActivityMessagingDiagnosticListener.cs 27 27 100.0% 🟢
…/Mocha/src/Mocha/Middlewares/Consume/ConsumerMiddlewares.cs 2 2 100.0% 🟢
src/Mocha/src/Mocha/Middlewares/DefaultMessageBus.cs 14 14 100.0% 🟢
src/Mocha/src/Mocha/Naming/DefaultNamingConventions.cs 3 3 100.0% 🟢

+3 more changed files; see the JSON below for uncovered lines.

Uncovered changed lines (JSON)
{
  "sha": "d741bab42a0585a71e96345316a06817f8093202",
  "files": [
    { "path": "src/Mocha/src/Mocha/Transport/RoutingStrategy.cs", "ranges": [[52, 52], [216, 217]] },
    { "path": "src/Mocha/src/Mocha/Middlewares/Consume/DeferredDispatchConsumeMiddleware.cs", "ranges": [[19, 19], [21, 22]] },
    { "path": "src/Mocha/src/Mocha/Middlewares/Dispatch/DeferredDispatchScope.cs", "ranges": [[86, 87]] }
  ]
}

Project coverage: 58.7% (316082/538483 lines)

@tobias-tengler
tobias-tengler force-pushed the tte/saga-durable-replies branch from 8291ac8 to 57c6518 Compare October 8, 2026 13:31
@github-actions github-actions Bot added the 📚 documentation This issue is about working on our documentation. label Oct 8, 2026
@tobias-tengler
tobias-tengler force-pushed the tte/saga-durable-replies branch 3 times, most recently from 3dcbe7d to 3cc16e0 Compare October 12, 2026 17:52
@tobias-tengler
tobias-tengler marked this pull request as ready for review October 12, 2026 19:33
@tobias-tengler
tobias-tengler requested review from PascalSenn and a balanced review from Copilot October 12, 2026 19:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Shared reply consumption can acknowledge a reply before the originating saga transaction makes its state visible.

3 open findings
What changed in this PR

Adds durable, service-wide saga reply queues so another instance can process replies after the sending instance stops.

Changes:

  • Adds saga-specific reply endpoint discovery and routing across four transports.
  • Adds cross-instance delivery, topology, and diagnostic tests.
  • Documents saga reply queue naming and behavior.
File Description
website/​content/​docs/​mocha/​transports/​rabbitmq.md Documents RabbitMQ saga reply queues.
website/​content/​docs/​mocha/​transports/​postgres.md Documents Postgres saga reply queues.
website/​content/​docs/​mocha/​sagas.md Explains durable saga reply behavior.
website/​content/​docs/​mocha/​routing-and-endpoints.md Adds saga reply endpoint naming.
src/​Mocha/​test/​Mocha.Transport.RabbitMQ.Tests/​Topology/​__snapshots__/​RabbitMQExplicitTopologyTests.Describe_Should_OmitConventionChain_When_SagaHasOnReplyTransition.snap Records the new RabbitMQ queue.
src/​Mocha/​test/​Mocha.Transport.RabbitMQ.Tests/​Routing/​RabbitMQReceiveTopologyConventionTests.cs Tests queue durability and lifecycle.
src/​Mocha/​test/​Mocha.Transport.RabbitMQ.Tests/​Routing/​__snapshots__/​RabbitMQReceiveTopologyConventionTests.DiscoverTopology_Should_OmitConventionChain_When_RouteIsReply.snap Updates RabbitMQ topology output.
src/​Mocha/​test/​Mocha.Transport.RabbitMQ.Tests/​Descriptors/​__snapshots__/​RabbitMQUnifiedQueueTests.SagaEndpoint_Should_Describe_When_ConfiguredViaUnifiedQueue.snap Updates unified-queue topology.
src/​Mocha/​test/​Mocha.Transport.RabbitMQ.Tests/​Behaviors/​SagaReplyDeliveryTests.cs Tests cross-instance RabbitMQ delivery.
src/​Mocha/​test/​Mocha.Transport.Postgres.Tests/​Conventions/​__snapshots__/​PostgresReceiveEndpointTopologyConventionTests.DiscoverTopology_Should_OmitConventionChain_When_RouteIsReply.snap Records the Postgres saga queue.
src/​Mocha/​test/​Mocha.Transport.Postgres.Tests/​Behaviors/​SagaReplyDeliveryTests.cs Tests stop, crash, fault, and discard behavior.
src/​Mocha/​test/​Mocha.Transport.InMemory.Tests/​Topology/​__snapshots__/​InMemoryTopologyConventionTests.Topology_Should_OmitConventionBinding_When_SagaHasOnReplyTransition.snap Records the InMemory saga queue.
src/​Mocha/​test/​Mocha.Transport.AzureServiceBus.Tests/​Behaviors/​QueueDeletionRecoveryTests.cs Strengthens queue-deletion setup.
src/​Mocha/​test/​Mocha.Tests/​MessageTypes/​MessageBusConfigurationValidationTests.cs Verifies saga-specific route binding.
src/​Mocha/​test/​Mocha.Sagas.Tests/​SagaRouteConditionTests.cs Tests per-saga reply endpoints.
src/​Mocha/​test/​Mocha.Sagas.Tests/​SagaReplyEndpointTests.cs Tests routing across transports.
src/​Mocha/​test/​Mocha.Sagas.Tests/​ReplyDiagnosticsTests.cs Clarifies reply diagnostic comments.
src/​Mocha/​src/​Mocha/​Transport/​RoutingStrategy.cs Discovers and binds saga reply endpoints.
src/​Mocha/​src/​Mocha/​Sagas/​SagaEventListener.cs Clarifies reply routing comments.
src/​Mocha/​src/​Mocha/​Sagas/​Saga.cs Addresses saga sends and faults to the new endpoint.
src/​Mocha/​src/​Mocha/​Naming/​DefaultNamingConventions.cs Generates service-scoped reply names.
src/​Mocha/​src/​Mocha.Transport.RabbitMQ/​Topology/​RabbitMQRoutingStrategy.cs Creates RabbitMQ saga reply queues.
src/​Mocha/​src/​Mocha.Transport.Postgres/​Topology/​PostgresRoutingStrategy.cs Creates Postgres saga reply queues.
src/​Mocha/​src/​Mocha.Transport.InMemory/​Topology/​InMemoryRoutingStrategy.cs Creates InMemory saga reply queues.
src/​Mocha/​src/​Mocha.Transport.AzureServiceBus/​Topology/​AzureServiceBusRoutingStrategy.cs Creates Azure Service Bus saga reply queues.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

var replyEndpoint = endpoint.Transport.ReplyReceiveEndpoint?.Source.Address;
// Route replies and faults to the saga's reply endpoint, where the saga's reply routes
// correlate them by the saga header.
var replyEndpoint = GetReplyAddress(context.Runtime, endpoint.Transport);
Comment on lines +127 to +131
public override ReceiveEndpointConfiguration CreateReplyEndpointConfiguration(
IMessagingConfigurationContext context,
InboundRoute route)
{
var queueName = context.Naming.GetReceiveEndpointName(route, ReceiveEndpointKind.Reply);
Comment thread website/content/docs/mocha/sagas.md Outdated

When a saga sends a command, Mocha attaches a `saga-id` header to the outgoing message. When the reply arrives, the saga runtime reads this header to find the existing saga instance and load its persisted state.

Replies and faults to a saga's commands go to the saga's reply queue (`{service}.{saga}_reply`), a durable queue that every instance of the service consumes. A reply still reaches the saga when the instance that sent the command has stopped. A reply that none of the saga's transitions handles is discarded with a warning. Mocha creates a saga reply queue for each saga with reply or fault transitions, on every transport.
@tobias-tengler
tobias-tengler marked this pull request as draft October 13, 2026 13:05
A saga step addresses its reply to the sending instance's temporary reply queue. When that instance stops or crashes before the reply arrives, the saga never completes, even though another instance runs the same saga.
Each saga with reply or fault transitions now gets a durable reply queue ({service}.{saga}_reply) on every transport, shared by all instances. Requests, sends and publishes from the saga address their replies and faults to it, so a reply reaches the saga after the sending instance stops.

The queue behaves like the instance reply endpoint: only the saga's reply routes are bound to it, it gets no topology bindings and no skipped or error queues, and the reply consumer discards replies that no transition handles. Transports opt in through RoutingStrategy.CreateReplyEndpointConfiguration; a transport that returns null keeps the instance reply endpoint.
…pletes

A consumer that publishes or sends while its own work is uncommitted exposes
that work early: a saga could receive the reply to its command before its state
was saved, subscribers could read uncommitted rows, and a handler that threw
after publishing produced the event again on retry.

The consumer pipeline now holds publish, send and reply dispatches in a
per-attempt scope and releases them in dispatch order after the inner
middlewares, including the saga and EF transactions, have committed. A failed
attempt discards its messages. Capture happens at the dispatch terminal, so the
outbox and scheduling middlewares keep intercepting first. RequestAsync and
dispatches outside a consumer are unchanged. ImmediateDispatch on the send,
publish and reply options opts a single dispatch out.

The saga logs a warning when a message with a saga id finds no state.
…tches at release

ImmediateDispatch now marks the dispatch with an ImmediateDispatchFeature that
the outbox middleware honors, so the message goes to the transport at once
instead of waiting in the outbox table for the handler's transaction.

A held dispatch is reported as a create operation when it is captured: its span
keeps the trace context that goes into the message headers and no longer counts
as a sent message. The release reports each message as a dispatch of its own,
so the publish span, the sent-message metric and the dispatch error now follow
the transport call instead of the capture.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

📚 documentation This issue is about working on our documentation. 🌶️ mocha

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants