Rebus - a lightweight Service Bus for .NET
What it is - the "dumb pipes, smart endpoints" philosophy
Rebus is an open-source .NET library for asynchronous communication between services - conceptually in the same category as MassTransit and NServiceBus (which we mentioned with the Saga/Kafka), but designed to be much simpler and "leaner" - less magic, fewer dependencies, simpler configuration.
Rebus embodies the principle that ThoughtWorks called, in 2010, "message bus without smarts" - the library itself doesn't try to be intelligent (routing, orchestration, transformations) - it's the business logic in your handlers that is meant to be "smart", while the transport itself is meant to be as simple and predictable as possible ("dumb pipes, smart endpoints").
Basic configuration and usage
using var activator = new BuiltinHandlerActivator();
// Registering a handler - similar to a Handler in MediatR, which we discussed with CQRS
activator.Handle<OrderPlacedEvent>(async message =>
{
Console.WriteLine($"Order received: {message.OrderId}");
await ProcessOrderAsync(message);
});
Configure.With(activator)
.Transport(t => t.UseRabbitMq("amqp://localhost", "order-queue"))
.Options(o => o.SetNumberOfWorkers(5)) // the number of parallel threads processing messages
.Start();
var bus = activator.Bus;
// Publishing an event - exactly the same pattern as IEventBus from the Saga/Outbox discussion
await bus.Publish(new OrderPlacedEvent(orderId: 5));
// Sending a command to a SPECIFIC recipient (point-to-point, not broadcast)
await bus.Send(new ReserveStockCommand(orderId: 5));
Integration with a DI container (Microsoft.Extensions.DependencyInjection)
services.AddRebus(configure => configure
.Transport(t => t.UseRabbitMq("amqp://localhost", "order-queue"))
.Routing(r => r.TypeBased().Map<ReserveStockCommand>("inventory-queue"))
);
// The handler as an ordinary class resolved through DI - constructor injection, as everywhere
public class OrderPlacedHandler : IHandleMessages<OrderPlacedEvent>
{
private readonly IOrderRepository _repository;
public OrderPlacedHandler(IOrderRepository repository) => _repository = repository;
public async Task Handle(OrderPlacedEvent message)
{
await _repository.MarkAsPlacedAsync(message.OrderId);
}
}
This looks very similar to registering an IRequestHandler<T> in MediatR - IHandleMessages<T> is an analogous interface, only for messages arriving from outside (through a broker), not invoked directly in-process.
Pluggable transports - one line of configuration
Rebus's key advantage - the transport is completely swappable, and the handler logic doesn't change:
.Transport(t => t.UseRabbitMq(connectionString, "my-queue"))
.Transport(t => t.UseAzureServiceBus(connectionString, "my-queue"))
.Transport(t => t.UseSqlServer(connectionString, "my-queue")) // KOLEJKA jako tabela SQL - bez brokera!
.Transport(t => t.UseInMemoryTransport(network, "my-queue")) // for unit/integration tests
UseSqlServer as a transport is especially practical for smaller systems - it eliminates the need to deploy a separate broker (RabbitMQ/Kafka); the queue simply lives as a table in the same SQL Server database you already have. This relates to the Outbox Pattern we discussed - Rebus with the SQL Server transport in practice implements a similar idea "natively".
Built-in Saga support
This is a very practical reference to the earlier discussion of the Saga Pattern - Rebus has a native saga mechanism (Orchestration), with no need to reach for an external library:
public class OrderSaga : Saga<OrderSagaData>,
IAmInitiatedBy<OrderPlacedEvent>,
IHandleMessages<StockReservedEvent>,
IHandleMessages<PaymentFailedEvent>
{
protected override void CorrelateMessages(ICorrelationConfig<OrderSagaData> config)
{
config.Correlate<OrderPlacedEvent>(m => m.OrderId, d => d.OrderId);
config.Correlate<StockReservedEvent>(m => m.OrderId, d => d.OrderId);
config.Correlate<PaymentFailedEvent>(m => m.OrderId, d => d.OrderId);
}
public async Task Handle(OrderPlacedEvent message)
{
Data.OrderId = message.OrderId;
await Bus.Send(new ReserveStockCommand(message.OrderId));
}
public async Task Handle(StockReservedEvent message)
{
await Bus.Send(new ChargePaymentCommand(message.OrderId));
}
public async Task Handle(PaymentFailedEvent message)
{
await Bus.Send(new ReleaseStockCommand(message.OrderId)); // KOMPENSACJA
MarkAsComplete();
}
}
CorrelateMessages is the mechanism telling Rebus how to match an incoming message to a specific instance of the saga's state (by OrderId) - this is the same problem we discussed with the MassTransit State Machine (InstanceState), just named differently.
Retry and Error Queue - "out of the box"
.Options(o => o.RetryStrategy(maxDeliveryAttempts: 5, errorQueueName: "error-queue"))
If a handler throws an exception, Rebus automatically retries (according to the configured number of attempts) - and once the limit is exceeded, the message goes to a dedicated error queue, where it can later be diagnosed/processed manually, instead of being lost forever. This is a built-in equivalent of what we had to build by hand with Kafka (retry logic + idempotency in the consumer).
Rebus vs MassTransit vs NServiceBus - which one when
| Rebus | MassTransit | NServiceBus | |
|---|---|---|---|
| Philosophy | Minimalism, little "magic" | Richer, more built-in patterns | The most "enterprise", comprehensive |
| Learning curve | Lower | Medium/higher | Higher |
| Licence | Fully free (open source) | Free (some features paid in newer versions) | Paid (except for small projects) |
| Ecosystem/community | Smaller, but active | The largest in .NET, "mainstream" | Large, commercial support |
| Sagas | Built-in, simple (Saga<TState>) |
Built-in, extensive (state machine) | Built-in, very extensive |
| SQL Server transport without a broker | ✅ Yes | Limited | Limited |
When to choose Rebus in practice
Rebus makes sense when you want simplicity and predictability over a wealth of features - smaller/medium systems, teams that don't want to invest time in learning a complex framework, or situations where the SQL Server transport as a queue (without deploying RabbitMQ/Kafka) is sufficient. For large, complex microservice architectures with many teams, MassTransit usually has the edge thanks to its larger ecosystem and community - but the concept itself (publishing events, handlers, sagas, retry) is nearly identical across all three libraries, so knowing one carries over easily to the others.
Summary
Rebus is a lightweight alternative to MassTransit/NServiceBus in .NET, implementing the same fundamental patterns we discussed with the Saga and Kafka - publishing/consuming events, retry with an error queue, and built-in sagas for orchestrating distributed transactions - but with a "dumb pipes, smart endpoints" philosophy that emphasises simple configuration and a minimal number of dependencies, right down to the option of using an ordinary SQL Server table as the transport, with no need to deploy a separate message broker.
A full example - Server and Client
Below is a complete, working example: a library with shared contracts, a server (the consumer) and a client (the sender), communicating through RabbitMQ.
Shared message contracts
namespace RebusDemo.Messages;
// A command sent by the client to the server (point-to-point, via bus.Send)
public record PlaceOrderCommand(Guid OrderId, string CustomerName, decimal Amount);
// An event published by the server after processing the order (via bus.Publish)
public record OrderPlacedEvent(Guid OrderId, DateTime PlacedAtUtc);
The server (consumer) - Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Rebus.Bus;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Retry.Simple;
using Rebus.ServiceProvider;
using RebusDemo.Messages;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddRebus(configure => configure
// Transport - this queue is this server's "address"; the client sends messages HERE
.Transport(t => t.UseRabbitMq("amqp://guest:guest@localhost:5672", "orders-queue"))
.Options(o => o.SetNumberOfWorkers(4))
// Retry - after 5 failed attempts the message goes to the error queue.
// Note: the method was called SimpleRetryStrategy() up to Rebus 7.x,
// from Rebus 8.0.0 it is called RetryStrategy() (identical functionality).
.Options(o => o.RetryStrategy(errorQueueAddress: "orders-error", maxDeliveryAttempts: 5))
);
// Automatyczna rejestracja WSZYSTKICH IHandleMessages<T> znalezionych w tym assembly
builder.Services.AutoRegisterHandlersFromAssemblyOf<Program>();
var host = builder.Build();
// Rebus.ServiceProvider registers the bus as an ordinary IHostedService - you do NOT need to
// (and cannot) "start" it with any UseRebus(); host.RunAsync() below
// odpali wszystkie hosted services, w tym Rebusa, samo.
Console.WriteLine("Listening on the queue 'orders-queue'. Press Ctrl+C to exit.");
await host.RunAsync();
// The handler is invoked AUTOMATICALLY by Rebus when a PlaceOrderCommand arrives
public class PlaceOrderHandler : IHandleMessages<PlaceOrderCommand>
{
private readonly IBus _bus;
public PlaceOrderHandler(IBus bus) => _bus = bus; // ordinary DI, as everywhere
public async Task Handle(PlaceOrderCommand message)
{
Console.WriteLine($"[SERVER] Received order {message.OrderId} from '{message.CustomerName}' for {message.Amount:C}");
await Task.Delay(300); // symulacja przetwarzania (zapis do bazy, walidacja itd.)
// Publishing the event - any interested subscriber could receive it,
// exactly as with Kafka/the Saga that we discussed earlier
await _bus.Publish(new OrderPlacedEvent(message.OrderId, DateTime.UtcNow));
}
}
The client (sender) - Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Rebus.Bus;
using Rebus.Config;
using Rebus.Routing.TypeBased;
using Rebus.ServiceProvider;
using RebusDemo.Messages;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddRebus(configure => configure
// The client has NO input queue of its own - a "one-way client",
// because it only SENDS messages, it never receives them
.Transport(t => t.UseRabbitMqAsOneWayClient("amqp://guest:guest@localhost:5672"))
// Routing - we tell Rebus: "send PlaceOrderCommand to the queue 'orders-queue'"
// (i.e. to where the Server is listening)
.Routing(r => r.TypeBased().Map<PlaceOrderCommand>("orders-queue"))
);
var host = builder.Build();
// The client doesn't call host.RunAsync() (it needs an interactive loop), so
// it has to explicitly start the hosted services (including Rebus) via StartAsync(),
// and stop them with StopAsync() at the end - there is no UseRebus() here.
await host.StartAsync();
var bus = host.Services.GetRequiredService<IBus>();
Console.WriteLine("Type a customer name and press Enter to send an order (or 'exit').");
while (true)
{
Console.Write("Nazwa klienta: ");
var name = Console.ReadLine();
if (string.IsNullOrWhiteSpace(name) || name.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
var command = new PlaceOrderCommand(Guid.NewGuid(), name, Random.Shared.Next(10, 500));
// bus.Send() = a point-to-point message, goes to ONE specific queue,
// according to the Routing() mapping set up above
await bus.Send(command);
Console.WriteLine($"[CLIENT] Sent order {command.OrderId} ({command.Amount:C}) -> orders-queue");
}
await host.StopAsync(); // a clean shutdown of the hosted services (including Rebus)
What happens "under the hood"
KLIENT RabbitMQ SERWER
| bus.Send(PlaceOrderCommand) | |
|------------------------------->| kolejka "orders-queue" |
| |----------------------------->|
| | Handle(PlaceOrderCommand)
| | |
| | bus.Publish(OrderPlacedEvent)|
| |<-----------------------------|
bus.Send(command)(client) - a point-to-point message, goes to one specific queue indicated byRouting().TypeBased().Map<T>(...).bus.Publish(event)(server) - a broadcast message, goes to everyone who subscribes to it (await bus.Subscribe<OrderPlacedEvent>()in the subscriber).IHandleMessages<T>- a handler invoked automatically by Rebus; registered throughAutoRegisterHandlersFromAssemblyOf<T>().
Running it
# 1. Broker (RabbitMQ) w Dockerze
docker run -d --hostname my-rabbit --name rebus-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3-management
# 2. Serwer (pierwszy terminal)
cd RebusDemo.Server && dotnet run
# 3. Klient (drugi terminal)
cd RebusDemo.Client && dotnet run
The RabbitMQ admin panel (a live view of queues and messages) is available at http://localhost:15672 (username/password: guest/guest).