Migrate from MassTransit

Mocha and MassTransit share most of their concepts: a bus that publishes events and sends commands over a broker, consumers that handle them, request/reply, retries and redelivery, a transactional outbox, and state machine sagas. Most of a migration is renaming. The part that needs planning is that a Mocha service and a MassTransit service cannot exchange messages with each other.

This guide maps MassTransit concepts to Mocha and walks you through migrating a service. For a side-by-side overview, including licensing, see Mocha vs. MassTransit.

Migrate with a coding agent#

To let a coding agent such as Claude Code, Codex, or GitHub Copilot do the migration, copy this prompt into it. The prompt points the agent to this guide and has it check with you before it changes code.

Migration prompt
Migrate this codebase from MassTransit to Mocha, the MIT-licensed .NET message
bus from ChilliCream.

Follow the migration guide:
https://chillicream.com/docs/mocha/migration/coming-from-masstransit.md
Look up Mocha APIs in https://chillicream.com/docs/mocha/llms.txt instead of
guessing them.

1. Inventory the MassTransit usage: transports, consumers, message types,
   publish, send, and request client calls, retry and redelivery settings, the
   outbox and inbox, sagas, scheduled messages, and the test harness. If the
   codebase uses something the guide does not cover, stop and ask me how to
   proceed.
2. Propose a plan that moves the services by message flow, as the guide
   describes, and wait for my approval.
3. Migrate one message flow at a time, moving communicating services together
   or keeping both libraries registered until the flow has moved. Build after
   each coherent batch and keep message contracts unchanged unless the guide
   says otherwise. Publish reply-producing saga triggers from the initial
   transition in the same transaction as the saga state.
4. Build, run the tests, fix every diagnostic the Mocha source generator
   reports, and start the services to check that every message flow still
   works.
5. Remove MassTransit once nothing references it. Summarize what changed, what
   behaves differently, and anything you could not migrate.

Plan the migration by message flow#

Mocha and MassTransit use different message envelopes and different exchange and queue names, so a Mocha service cannot consume what a MassTransit service publishes, and the other way around. Migrate the services that exchange a message together, or move one message flow at a time and keep both buses registered in a service until all its flows have moved. The two libraries register separate services, so they can run in the same application.

Concept mapping#

MassTransitMochaKey difference
AddMassTransit(x => ...)AddMessageBus()Configuration is a chain of builder calls instead of one callback.
x.AddConsumers(assembly).Add{Module}()Generated at build time from the handlers in the project.
x.UsingRabbitMq(...), x.UsingAzureServiceBus(...).AddRabbitMQ(), .AddAzureServiceBus(...)RabbitMQ reads the IConnectionFactory from dependency injection.
IConsumer<T> for an eventIEventHandler<T>HandleAsync(message, cancellationToken) receives the message, not a context.
IConsumer<T> for a commandIEventRequestHandler<T>Commands are sent to one queue, named after the message type.
IConsumer<T> that calls RespondAsyncIEventRequestHandler<TRequest, TResponse>The handler returns the response. The request implements IEventRequest<TResponse>.
IConsumer<T> that reads headers or the contextIConsumer<T>ConsumeAsync(IConsumeContext<T>) gives access to headers and message metadata.
IPublishEndpoint.PublishIMessageBus.PublishAsyncSame concept.
ISendEndpointProvider.GetSendEndpoint(uri) and SendIMessageBus.SendAsyncThe destination comes from the message type, a configured route, or SendOptions.
IRequestClient<T>.GetResponse<TResponse>IMessageBus.RequestAsyncReturns the response message directly. One response type per request.
UseMessageRetryAddResilience(policy => policy.Default().Retry(...))Exception policies choose retry, redelivery, dead letter, or discard per exception type.
UseDelayedRedelivery, UseScheduledRedelivery.ThenRedeliver(...)Same concept.
{queue}_error and {queue}_skipped queues{endpoint}_error and {endpoint}_skipped endpointsSame naming pattern.
AddEntityFrameworkOutbox<TContext> with UseBusOutboxAddEntityFramework<TContext>(p => { p.UsePostgresOutbox(); p.UseTransaction(); })Uses your Entity Framework Core DbContext.
The inbox in the Entity Framework outboxp.UsePostgresInbox()Deduplicates by message ID and consumer.
MassTransitStateMachine<TInstance>Saga<TState>States are strings, transitions are configured in Configure.
CorrelateById, CorrelateByThe saga ID, from the saga-id header or ICorrelatable.CorrelationIdMocha correlates by saga ID only. The state factory can set the ID.
IMessageScheduler.SchedulePublishIMessageBus.SchedulePublishAsyncReturns a token to cancel the scheduled message.
AddMassTransitTestHarnessThe in-memory transportRun the bus in memory and assert on the effects.

Migrate step by step#

1. Install the packages#

Bash
dotnet add package Mocha
dotnet add package Mocha.Analyzers
dotnet add package Mocha.Transport.RabbitMQ

Use Mocha.Transport.AzureServiceBus for Azure Service Bus. Mocha.Analyzers contains the source generator that writes the registration method. Add it to every project that contains handlers. Mocha targets .NET 8 and later.

2. Register the bus#

C#
// MassTransit
builder.Services.AddMassTransit(x =>
{
    x.AddConsumers(typeof(Program).Assembly);
    x.UsingRabbitMq((context, cfg) =>
    {
        cfg.Host("localhost", "/", h =>
        {
            h.Username("guest");
            h.Password("guest");
        });
        cfg.ConfigureEndpoints(context);
    });
});

// Mocha
builder.Services.AddSingleton<IConnectionFactory>(_ =>
    new ConnectionFactory
    {
        HostName = "localhost",
        VirtualHost = "/",
        UserName = "guest",
        Password = "guest"
    });

builder.Services
    .AddMessageBus()
    .AddOrdering()
    .AddRabbitMQ();

The generator names the registration method after the last segment of the assembly name, so handlers in MyApp.Ordering are registered with AddOrdering(). With Aspire, builder.AddRabbitMQClient("rabbitmq") registers the connection factory for you. See RabbitMQ and Azure Service Bus for the transport options.

Mocha creates exchanges and queues at startup from naming conventions, like ConfigureEndpoints does. The names differ from MassTransit's. Routing and endpoints explains the conventions and how to override them.

3. Turn consumers into handlers#

Pick the handler interface by what the consumer does. Most consumers only need the message, so HandleAsync receives the message and a cancellation token instead of a context.

C#
// MassTransit
public class OrderPlacedConsumer(ILogger<OrderPlacedConsumer> logger) : IConsumer<OrderPlaced>
{
    public Task Consume(ConsumeContext<OrderPlaced> context)
    {
        logger.LogInformation("Order {OrderId} placed", context.Message.OrderId);
        return Task.CompletedTask;
    }
}

// Mocha: an event
public class OrderPlacedHandler(ILogger<OrderPlacedHandler> logger) : IEventHandler<OrderPlaced>
{
    public ValueTask HandleAsync(OrderPlaced message, CancellationToken cancellationToken)
    {
        logger.LogInformation("Order {OrderId} placed", message.OrderId);
        return ValueTask.CompletedTask;
    }
}

A consumer of a command becomes an IEventRequestHandler<TCommand>. A consumer that responds becomes an IEventRequestHandler<TRequest, TResponse> and returns the response:

C#
// MassTransit
public record CheckOrderStatus(Guid OrderId);
public record OrderStatus(Guid OrderId, string Status);

public class CheckOrderStatusConsumer : IConsumer<CheckOrderStatus>
{
    public Task Consume(ConsumeContext<CheckOrderStatus> context)
        => context.RespondAsync(new OrderStatus(context.Message.OrderId, "Shipped"));
}

// Mocha
public record CheckOrderStatus(Guid OrderId) : IEventRequest<OrderStatus>;
public record OrderStatus(Guid OrderId, string Status);

public class CheckOrderStatusHandler : IEventRequestHandler<CheckOrderStatus, OrderStatus>
{
    public ValueTask<OrderStatus> HandleAsync(CheckOrderStatus request, CancellationToken cancellationToken)
        => ValueTask.FromResult(new OrderStatus(request.OrderId, "Shipped"));
}

When a consumer reads headers or message metadata, implement Mocha's IConsumer<T> instead. Its ConsumeAsync method receives an IConsumeContext<T>. See Handlers and consumers.

4. Update publish, send, and request call sites#

C#
// MassTransit
await publishEndpoint.Publish(new OrderPlaced(orderId), cancellationToken);

var endpoint = await sendEndpointProvider.GetSendEndpoint(new Uri("queue:reserve-inventory"));
await endpoint.Send(new ReserveInventory(orderId), cancellationToken);

var response = await client.GetResponse<OrderStatus>(new CheckOrderStatus(orderId), cancellationToken);
var status = response.Message;

// Mocha
await bus.PublishAsync(new OrderPlaced(orderId), cancellationToken);

await bus.SendAsync(new ReserveInventory(orderId), cancellationToken);

var status = await bus.RequestAsync(new CheckOrderStatus(orderId), cancellationToken);

bus is an IMessageBus. SendAsync sends to the queue of the message type's handler by convention. To send somewhere else, configure a route with AddMessage<T>(m => m.Send(r => r.ToQueue("..."))) or set SendOptions.Endpoint on the call.

RequestAsync waits up to two minutes for a response. A failing handler surfaces as a RemoteErrorException, a missing response as a ResponseTimeoutException. To give up sooner, pass a cancellation token that is canceled after your timeout.

5. Replace retries and redelivery#

MassTransit configures retries as middleware on the endpoint. Mocha configures them as exception policies, on the bus, a transport, or a single receive endpoint.

C#
// MassTransit
x.AddConfigureEndpointsCallback((context, name, cfg) =>
{
    cfg.UseDelayedRedelivery(r => r.Intervals(
        TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(30)));
    cfg.UseMessageRetry(r => r.Immediate(3));
});

// Mocha
builder.Services
    .AddMessageBus()
    .AddResilience(policy =>
    {
        policy.On<ValidationException>().DeadLetter();

        policy.Default()
            .Retry()
            .ThenRedeliver();
    })
    .AddOrdering()
    .AddRabbitMQ();

Retry() retries three times with exponential backoff. ThenRedeliver() redelivers after 5, 15, and 30 minutes. Both take arguments to change the counts and delays. After retries and redeliveries are exhausted, the fault pipeline routes the message to the error endpoint. Delayed redelivery needs a scheduling store. RabbitMQ has none of its own, so register the PostgreSQL scheduling store, otherwise Mocha redelivers immediately. See Exception policies and Scheduling.

6. Move the outbox and inbox#

Mocha's outbox and inbox use Entity Framework Core with PostgreSQL. Map the entities in your DbContext and register them on the bus:

C#
// MassTransit
x.AddEntityFrameworkOutbox<AppDbContext>(o =>
{
    o.UsePostgres();
    o.UseBusOutbox();
});

// Mocha
builder.Services
    .AddMessageBus()
    .AddOrdering()
    .AddEntityFramework<AppDbContext>(p =>
    {
        p.UsePostgresOutbox();
        p.UseTransaction();
        p.UsePostgresInbox();
    })
    .AddRabbitMQ();

The outbox and inbox are in the Mocha.EntityFrameworkCore.Postgres package. Import Mocha.EntityFrameworkCore, Mocha.Inbox, and Mocha.Outbox for the registration and model extensions. In OnModelCreating, replace MassTransit's AddInboxStateEntity(), AddOutboxMessageEntity(), and AddOutboxStateEntity() with modelBuilder.AddPostgresOutbox() and modelBuilder.AddPostgresInbox(), then add a database migration. Drain MassTransit's outbox before you switch, because Mocha does not read MassTransit's outbox tables.

For a publish or send outside a consumer, begin a transaction on the same DbContext, publish or send, save changes, and commit. If an EF Core retrying execution strategy is enabled, execute the entire explicit transaction through that strategy. Aspire enables EF connection retries by default, so verify that the execution strategy supports the transactions used by the outbox and consumer middleware. If you disable EF retries, account for the change in database connection resilience. See Reliability.

7. Rewrite sagas#

A MassTransit state machine and a Mocha saga describe the same thing: states, the events that move between them, and the actions that run on each transition. In the Mocha example, OrderSubmitted starts the saga and its initial transition publishes OrderPlaced, which another service can answer with OrderAccepted.

C#
// MassTransit
public class OrderState : SagaStateMachineInstance
{
    public Guid CorrelationId { get; set; }
    public string CurrentState { get; set; } = null!;
}

public class OrderStateMachine : MassTransitStateMachine<OrderState>
{
    public State Submitted { get; private set; } = null!;
    public Event<OrderSubmitted> OrderSubmitted { get; private set; } = null!;
    public Event<OrderAccepted> OrderAccepted { get; private set; } = null!;

    public OrderStateMachine()
    {
        InstanceState(x => x.CurrentState);
        Event(() => OrderSubmitted, x => x.CorrelateById(m => m.Message.OrderId));
        Event(() => OrderAccepted, x => x.CorrelateById(m => m.Message.OrderId));

        Initially(
            When(OrderSubmitted)
                .TransitionTo(Submitted));

        During(Submitted,
            When(OrderAccepted)
                .Finalize());
    }
}

// Mocha
public class OrderState : SagaStateBase
{
}

public record OrderSubmitted(Guid OrderId);
public record OrderPlaced(Guid OrderId);

public record OrderAccepted(Guid OrderId) : ICorrelatable
{
    public Guid? CorrelationId => OrderId;
}

public sealed class OrderSaga : Saga<OrderState>
{
    private const string Submitted = nameof(Submitted);
    private const string Accepted = nameof(Accepted);

    protected override void Configure(ISagaDescriptor<OrderState> descriptor)
    {
        descriptor
            .Initially()
            .OnEvent<OrderSubmitted>()
            .StateFactory(e => new OrderState { Id = e.OrderId })
            .Publish((_, state) => new OrderPlaced(state.Id))
            .TransitionTo(Submitted);

        descriptor
            .During(Submitted)
            .OnEvent<OrderAccepted>()
            .TransitionTo(Accepted);

        descriptor.Finally(Accepted);
    }
}

The main differences:

  • Correlation. MassTransit correlates by any message property. Mocha correlates by the saga's ID. Set the ID in the state factory, here to the order ID, and let later events return it from ICorrelatable.CorrelationId. Replies to commands the saga sent carry the ID in the saga-id header. The message that starts a saga must not return an ICorrelatable.CorrelationId or carry a saga-id header, because Mocha then looks for an existing instance instead of creating one.
  • Ordering. Mocha ignores a correlated event when its saga instance does not exist. Publish a message that can produce a correlated reply from the initial transition, as above, and commit the saga state and outgoing message together using the transactional outbox.
  • Completion. Every saga needs a final state, and every state must be able to reach one. Entering a final state deletes the persisted saga state. If completed status must remain queryable, persist it separately as business data.
  • Persistence. The generated registration method registers the saga, so call .AddSaga<OrderSaga>() only when you register handlers by hand. Store saga state in PostgreSQL with AddEntityFramework<AppDbContext>(p => p.AddPostgresSagas()) and modelBuilder.AddPostgresSagas(), or in memory with services.AddInMemorySagas() for tests. Import Mocha.Sagas for saga registration and Mocha.Sagas.EfCore for the model extension. A project declaring an ICorrelatable message must reference Mocha and import Mocha.Sagas; implement CorrelationId explicitly if it must not be serialized.
  • Requests. OnRequest<T>() starts a saga from a request and .Respond(...) on a final state answers it, like a MassTransit saga that responds to its initiating request.
  • Timeouts. Timeout(TimeSpan) on the descriptor schedules a timeout for the whole saga, and OnTimeout() handles it.

Sagas covers state, transitions, faults, compensation, and timeouts.

8. Move scheduled messages#

C#
// MassTransit
await scheduler.SchedulePublish(DateTime.UtcNow.AddMinutes(30), new SendReminder(orderId));

// Mocha
var result = await bus.SchedulePublishAsync(
    new SendReminder(orderId),
    DateTimeOffset.UtcNow.AddMinutes(30),
    cancellationToken);

result.Token cancels the message with bus.CancelScheduledMessageAsync. Azure Service Bus and the PostgreSQL transport schedule natively. RabbitMQ needs the PostgreSQL scheduling store: register it with p.UsePostgresScheduling() in AddEntityFramework, add modelBuilder.AddPostgresScheduledMessages() in OnModelCreating, and add a database migration. See Scheduling.

9. Update observability and tests#

Mocha emits OpenTelemetry traces and metrics after you call .AddInstrumentation() on the bus. Subscribe to the Mocha activity source and meter instead of MassTransit. See Observability.

Tests that used the MassTransit test harness can run the bus with the in-memory transport instead: register .AddInMemory() from the Mocha.Transport.InMemory package in place of the broker and assert on the effects of your handlers.

Next steps#

Edit this page on GitHub
Maintained by ChilliCream. Last updated on by PascalSenn