# Topic-Routed Channels Service Bus with Outbox and Inbox

> Build an in-memory .NET 11 pub/sub bus on System.Threading.Channels with O(1) topic routing, sub-10ms outbox wakeup, and idempotent inbox replay.

Kind: Lab · Reviewed: 2026-12-02 · Author: Milan Jovanović
Canonical: https://modularmonolith.com/guides/channels-outbox-idempotency/
Reference Repository: https://github.com/m-jovanovic/modular-monolith/tree/3c8d0cf5601d287b645c1ca59b7b3e811659ec74

`Orbit.Common.EventBus` builds a topic-routed publish-subscribe bus on `System.Threading.Channels` using an immutable `FrozenDictionary<Type, ImmutableArray<SubscriptionChannel>>`. Paired with PostgreSQL Outbox wakeup signals and idempotent `inbox_message_consumers` receipts, it delivers sub-10ms local latency with crash-safe at-least-once guarantees.

## Why naive in-memory event buses break at scale

Most sample modular monoliths wire `System.Threading.Channels` in one of two flawed ways:

| Bus Pattern | Routing Cost | Failure & Backpressure Behavior |
| --- | --- | --- |
| **Single Shared `Channel<object>`** | Sequential queue | Slow `Shipments` handler blocks `Users` and `Inventory` events (head-of-line blocking). |
| **Broadcast Fan-Out (` MediatR` / all-to-all)** | $O(N)$ per event | Every consumer inspects and discards unrelated events; retries re-trigger healthy handlers. |
| **`Orbit.Common.EventBus` (Topic-Routed)** | **$O(1)$ `FrozenDictionary`** | Dedicated bounded `Channel` per `(topic, subscriber)`, isolated retries, per-consumer dead-letter replay. |

## Test topic isolation and dead-letter replay

Run the unit test suite in `Orbit.UnitTests` to verify both `O(1)` topic isolation and per-subscriber dead-letter recovery:

```sh
dotnet test tests/Orbit.UnitTests/Orbit.UnitTests.csproj \
  --filter FullyQualifiedName~ChannelEventBusPubSubTests
```

When `FlakyAlphaConsumer` throws twice on `AlphaTopicIntegrationEvent`, healthy `AlphaConsumerOne` and `AlphaConsumerTwo` execute **exactly once** and never re-run. The failing consumer's envelope lands in `DeadLetters` (`Attempts = 2`), and calling `ReplayDeadLetterAsync(deadLetter.Id)` re-delivers it solely to `alpha.flaky`.

## Guarantee exactly-once business effects with the Inbox decorator

Because `ModuleOutboxProcessor` guarantees *at-least-once* delivery across process restarts, every integration event consumer is wrapped in `IdempotentIntegrationEventHandler<TEvent, THandler, TDbContext>`. Before running business logic, it checks `<schema>.inbox_message_consumers` for `(InboxMessageId, ConsumerName)` and commits the consumer receipt in the **same PostgreSQL transaction** as the handler's state changes.

## Summary

- Freeze topic routes into a `FrozenDictionary` at startup and allocate one bounded `Channel<IntegrationEventEnvelope>` (`BoundedChannelFullMode.Wait`) per subscriber.
- Pair PostgreSQL Outbox durability with `OutboxWakeupSignal<TDbContext>` so local dev and production enjoy sub-10ms dispatch without tight SQL polling.
- Commit `<schema>.inbox_message_consumers` receipts inside the consumer's database transaction so crash retries are strictly idempotent.

## Frequently asked questions

### Why not use a single System.Threading.Channel<IIntegrationEvent> for the whole monolith?

A single shared channel introduces head-of-line blocking: one slow or failing subscriber stalls unrelated modules, and retry loops re-execute sibling handlers that already succeeded. Orbit allocates a dedicated bounded channel per (topic, subscription).

### How does Orbit avoid polling latency in its PostgreSQL Transactional Outbox?

InsertOutboxMessagesInterceptor pulses OutboxWakeupSignal<TDbContext> in SavedChangesAsync immediately after the transaction commits, waking the outbox worker in under 10 milliseconds while keeping a 2-second fallback poll.

### What happens when a subscriber throws an exception after exhausting retries?

ChannelSubscriptionHostedService moves the failed envelope into ChannelEventBus's dead-letter store without affecting healthy sibling subscribers on the same topic, allowing operators or agents to inspect and replay it.

