With MediatR's default notification publisher, what happens when one of three OrderPlaced handlers throws, and how does TaskWhenAllPublisher change that?
answer
- sequential by default
- ForeachAwaitPublisher: first throw ends the loop
- TaskWhenAllPublisher: all start, await rethrows one
- the rest sit in Task.Exception
- one scope, one DbContext, concurrent use
basics
~20 sWith the default ForeachAwaitPublisher, handlers run one after another; the first exception stops the remaining handlers and propagates out of Publish. TaskWhenAllPublisher starts every handler, so all of them run, and Publish then faults with their failures.
solid answer
~40 sIn MediatR 14.2 the default `INotificationPublisher` is `ForeachAwaitPublisher`: it awaits each `INotificationHandler<OrderPlaced>` in turn, in the order the container returns them. If the second throws, the first has already done its work (nothing is rolled back), the third never runs, and the exception surfaces from `await Publish`, and from the `Send` that published it, so the endpoint can return 500 for an order that was saved. `TaskWhenAllPublisher` invokes every handler and awaits `Task.WhenAll`, so all three run; `await` rethrows the first failure and the others stay on the task's `Exception.InnerExceptions`. The price is concurrency: handlers resolved from one request scope share its `DbContext`, which does not allow concurrent operations. Switch with `cfg.NotificationPublisher` or `cfg.NotificationPublisherType`, or write your own `INotificationPublisher` to isolate failures.
code
csharp · 5 linesbuilder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<PlaceOrderHandler>();
cfg.NotificationPublisher = new TaskWhenAllPublisher(); // default: ForeachAwaitPublisher
});go deeper
Recall that by default notification handlers run one after another and that an exception from one handler reaches the code that called Publish.
Explain both built-in strategies: ForeachAwaitPublisher stops at the first failure, TaskWhenAllPublisher runs all handlers and rethrows the first failure when awaited.
Show the production consequences: a 500 for a saved order, shared DbContext concurrency under TaskWhenAllPublisher, unspecified handler order, and a custom INotificationPublisher to isolate optional reactions.
Argue where in-process notifications stop being adequate: when a reaction must survive crashes or retries, move it to a durable channel and keep Publish for optional, local reactions.
## What Publish does When you call `IPublisher.Publish(new OrderPlaced(orderId, restaurantId), ct)`, MediatR: 1. resolves every `INotificationHandler<OrderPlaced>` from the service provider the mediator was built with; 2. removes duplicates of the same handler class, keeping the first; 3. wraps each handler in a `NotificationHandlerExecutor` (the instance plus a callback); 4. hands the executors to the configured **`INotificationPublisher`**, whose `Publish` method decides how they are run. The strategy is set on `MediatRServiceConfiguration.NotificationPublisher`, whose default is `new ForeachAwaitPublisher()`, or by type with `NotificationPublisherType`, which overrides it and is resolved from the container. `Mediator` also exposes `protected virtual PublishCore` for subclasses. ## ForeachAwaitPublisher: sequential, stop at the first failure Its whole body is a `foreach` that awaits `handler.HandlerCallback(notification, cancellationToken)` for each executor. With three handlers (print the kitchen ticket, dispatch a courier, award loyalty points) and the courier handler throwing: - the kitchen ticket has **already printed**; MediatR has no compensation step; - the loyalty handler **never runs**; - the courier exception propagates **unchanged** out of `Publish`, and out of the `PlaceOrderHandler` that called it, after `SaveChangesAsync` committed the order. Order follows registration order, which for scanned handlers is the order the scan meets the types. MediatR does not sort them, so treat order as unspecified. ## TaskWhenAllPublisher: everyone runs, the caller sees a failure It projects every executor to a task (`Select(...).ToArray()`) and returns `Task.WhenAll(tasks)`. So: - every handler is **started**, and a failing one does not stop the others; - `await mediator.Publish(...)` rethrows the **first** failed task's exception, unwrapped; **all** failures are on the returned task's `Exception` (an `AggregateException`) for code that inspects it; - handlers **overlap in time**: each runs synchronously until its first `await`, then the next one starts. One edge: a handler written without `async` that throws *before* returning its `Task` throws out of the projection itself, and the handlers after it are never started. An `async` method never does this, because its exception is captured in the task. ## Comparison | | `ForeachAwaitPublisher` (default) | `TaskWhenAllPublisher` | |---|---|---| | Execution | one after another | started together, overlapping | | After a failure | later handlers skipped | all handlers still run | | What `await Publish` throws | that handler's exception | the first failure; the rest on `Task.Exception` | | Shared scoped services | safe, one at a time | concurrent use of e.g. one `DbContext` | | Latency | sum of the handlers | roughly the slowest handler | ## Why the caller sees a 500 for a saved order Trace the takeaway flow under the default strategy. The endpoint calls `sender.Send(new PlaceOrder(...))`; `PlaceOrderHandler` calls `SaveChangesAsync`, which commits the order, and then `await publisher.Publish(new OrderPlaced(...))`. When the courier-dispatch handler throws, that exception travels up through `Publish`, out of `PlaceOrderHandler.Handle`, out of `Send`, and into the endpoint, where the exception handler turns it into a 500 response. The customer retries, and now there are two orders. Two remedies are common: publish only reactions that may fail independently and make them catch their own errors, or have the handler return the confirmation and move must-happen reactions to a durable mechanism. Switching to `TaskWhenAllPublisher` alone does not fix it: all handlers run, but `Publish` still faults and the endpoint still returns 500. ## The DbContext trap `Mediator` resolves handlers from its own `IServiceProvider`. Injected into an endpoint, that is the request scope, so every handler that takes `TakeawayDbContext` gets the **same instance**. Under `TaskWhenAllPublisher`, two handlers querying at once trigger EF Core's `InvalidOperationException`: "A second operation was started on this context instance before a previous operation completed." Keep the sequential publisher, or have such handlers create their own context through `IDbContextFactory<TContext>`. ## Making failures explicit - **Custom publisher.** Implement `INotificationPublisher`, wrap each `HandlerCallback` in `try/catch`, log, and continue, so one optional reaction cannot fail the order. - **Catch inside optional handlers.** A handler whose failure must not affect the caller should handle its own exceptions. - **Do not mistake either strategy for delivery guarantees.** Both run in-process inside the caller's `await`, with no persistence and no retry; a crash after `SaveChangesAsync` loses the reactions. Effects that must happen belong in a durable mechanism, such as an outbox row written in the same transaction or a background job.
- In what order does ForeachAwaitPublisher run MediatR's notification handlers?In the order the container returns them from `GetServices`, which is registration order; for scanned handlers that is the order the scan meets the types. MediatR does not sort them, and duplicate registrations of one class collapse to one. If one reaction must follow another, make that explicit instead of relying on order.
- Why can switching to TaskWhenAllPublisher break handlers that use EF Core?The handlers are resolved from the mediator's scope, so in a web request they share the request's scoped `DbContext`. Running concurrently, two of them can issue queries on the same context at once, which EF Core rejects with an `InvalidOperationException`. Keep the sequential publisher, or let those handlers create their own context from `IDbContextFactory<TContext>`.
- Does either MediatR publisher make the order's side effects reliable?No. Both run in-process inside the caller's `await`, with no persistence and no retry, so a crash or deployment between `SaveChangesAsync` and the handlers loses the reactions. Effects that must happen need a durable mechanism, such as an outbox row in the same transaction or a queued background job.
ForeachAwaitPublisher is one runner carrying the 'order placed' slip to the kitchen, the courier desk and the loyalty desk in turn: if he is stopped at the courier desk, the loyalty desk never hears. TaskWhenAllPublisher sends three runners at once, so every desk hears, and the manager is told about the first runner who came back with bad news.
- MediatR runs notification handlers in parallel by default.
- With ForeachAwaitPublisher, the remaining handlers still run after one throws.
- TaskWhenAllPublisher stops the other handlers at the first exception.
- Publish swallows handler exceptions, so the caller never sees them.
- Awaiting a TaskWhenAllPublisher publish throws an AggregateException.
- MediatR rolls back earlier handlers when a later handler throws.
Assumes MediatR 14.2: ForeachAwaitPublisher is the default NotificationPublisher, and TaskWhenAllPublisher is the built-in concurrent alternative.