A source-generated mediator for .NET. Handlers are plain private methods on partial classes (static, or instance methods of a class
whose constructor takes the services), and a Roslyn generator in the
same package emits all dispatch and pipeline code at compile time: no reflection, no delegate chains, no closures, nothing allocated
per call by the mediator itself, and safe for Native AOT and trimming.
Status: early development, not yet on nuget.org. The design is recorded in ADR 0001; the decisions behind it, and any undecided points with their interim behavior, are in open-questions.md (the v1 decisions, OQ-1 to OQ-92, are archived in open-questions-v1.md); what is left before a first release is in docs/whats-left.md.
- Install
- Quick start
- Requests and handlers
- Testing handlers
- Behaviors
- Streaming
- Notifications
- Hosts
- Contracts and handler libraries
- Diagnostics
- Benchmarks
- Building
dotnet add package KeryxOne package holds everything: Keryx.dll (the public types, for netstandard2.0, net10.0 and net11.0) and the generators,
analyzers and code fixes (analyzers/dotnet/cs).
Requirements
- The .NET 10 SDK (Roslyn 5.0) or later, whatever framework your project targets. The generator does not load in older compilers.
- C# 14 or later (the .NET 10 SDK's default) in every project that references Keryx, whatever framework it targets. The package sets
LangVersiontolatestwhen your project leaves it empty; aLangVersionbelow 14 that you set yourself is error KRX022. - Requests, notifications and handler libraries may target
netstandard2.0. A host (the project with the mediator: by default an executable, test project or Android app, see Hosts) targetsnet10.0or later (KRX031); one that targets an older framework is not a host by default. - The
Keryxpackage depends onMicrosoft.Extensions.DependencyInjection.Abstractions(8.0.x fornetstandard2.0, 10.0.x fornet10.0), which the generated host code uses. Onnet11.0the assembly comes from the shared framework, so that target lists no package dependency. - Reference the
Keryxpackage directly from every project that declares requests or handlers, and from every host. A project that gets the package only transitively behaves differently by route. Through aProjectReferenceto a project that references Keryx, the generators and analyzers still run unless that reference setsPrivateAssets. Through a package that depends on Keryx, they do not flow (NuGet packs the dependency withexclude="Build,Analyzers"). In both cases the package'sbuildTransitivefiles apply the same build defaults (LangVersion,KeryxHost,KeryxInterceptCallsand, in a host, the interceptors namespace).
// Program.cs
using Keryx;
using Microsoft.Extensions.DependencyInjection;
using MyApp; // the host's root namespace, where AddKeryx() is generated
// An executable that references Keryx is a host: it gets the generated KeryxMediator and AddKeryx().
var services = new ServiceCollection();
services.AddSingleton<IOrderRepository, InMemoryOrderRepository>();
services.AddKeryx();
await using var provider = services.BuildServiceProvider();
await using var scope = provider.CreateAsyncScope();
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
Guid id = await mediator.Send(new CreateOrder.Command("apple", 3));// CreateOrder.cs
using Keryx;
namespace MyApp;
public static partial class CreateOrder
{
public sealed record Command(string Sku, int Quantity) : IRequest<Guid>;
private static async ValueTask<Guid> Handle(Command request, IOrderRepository orders, CancellationToken cancellationToken)
{
var id = Guid.NewGuid();
await orders.Add(id, request.Sku, request.Quantity, cancellationToken);
return id;
}
}CreateOrder is a static container: a static partial class that groups the request with its handler. The generator writes its
other half: a nested CreateOrder.Invoker class with a constructor that takes IOrderRepository and a public InvokeAsync that runs
the handler, and the metadata a host reads. In the host it writes KeryxMediator (with a typed Send(CreateOrder.Command) overload),
AddKeryx(), which registers the mediator, and an interceptor that sends the mediator.Send(...) call above through that typed overload
(Hosts). Neither handlers nor behaviors are registered: the mediator's pipeline contexts
resolve the services a handler injects and call it (in the host, through a generated static entry on CreateOrder, so the mediator
never constructs the Invoker), and behaviors are static methods.
A request implements exactly one of IRequest<TResponse>, IRequest (no response: Send returns a plain ValueTask; it is its
own interface, and there is no Unit type) or IStreamRequest<TItem>. A notification implements INotification. Requests may be classes, records or structs; they must not be
generic, nested in a generic type or ref structs (KRX012). A request class or record is sealed (KRX024, with a
code fix); a struct always is. A family of requests is an abstract (or C# 15 closed) base with sealed cases, and each case has its own
handler; the base has none (KRX003 for a handler that takes it):
public abstract record Command : IRequest;
public sealed record Ship(Guid Order) : Command;
public sealed record Cancel(Guid Order) : Command;Dispatch is by exact runtime type: a handler never receives another request type. A host composes only sealed request types: one that is not sealed (KRX024 turned off) is not dispatched, and a referenced one is the host error KRX038. Notifications need not be sealed (see Notifications).
A handler is a method named Handle (or HandleAsync) with the request as a parameter:
- it is
private(KRX002, with a code fix),staticor an instance method (an instance handler, below); - it returns
ValueTask<T>,Task<T>orTforIRequest<T>;ValueTask,TaskorvoidforIRequest;IAsyncEnumerable<T>forIStreamRequest<T>;ValueTaskorTaskfor a notification; - it has exactly one request or notification parameter (KRX003), at most one
CancellationTokenand noref,in,outorparamsparameters (KRX013). Every other parameter of a static handler is injected from the container; an instance handler takes none (KRX026, with a Move to the constructor code fix): its services are its class's constructor parameters.
The handler class contains exactly one handler (KRX006), is partial all the way out, and is public or internal
(KRX004, with a code fix; an internal handler class of a library stays out of IntelliSense in
the projects that reference it). Write it as a static container, a static partial class: Keryx generates a nested
Invoker class in it with a constructor for the injected parameters, a field __keryx_p_<parameterName> for each (so an injected
parameter may take any name) and InvokeAsync. A static container whose handler injects nothing gets a static InvokeAsync instead and
no Invoker. Because Keryx generates the Invoker, a static container whose handler injects services declares no member named
Invoker and is not named Invoker itself (KRX015). A non-static handler class, the shape before static containers, still
works and keeps the generated constructor, fields and InvokeAsync on itself; it declares no instance constructor and derives from
object directly, though it may implement interfaces (KRX007). Members named InvokeAsync or starting with __keryx_ are
Keryx's, so no handler class declares one or is named like one itself (KRX015). A static handler's class must not implement
IDisposable or IAsyncDisposable (KRX025): it is stateless and Keryx never disposes its object, so inject the disposable
service instead (an instance handler class, below, may be disposable). Group handlers with nested classes:
public static partial class Orders
{
public static partial class Create
{
public sealed record Command(string Sku, int Quantity) : IRequest<Guid>;
private static ValueTask<Guid> Handle(Command request, IOrderRepository orders, CancellationToken ct) => orders.Create(request, ct);
}
public static partial class Cancel
{
public sealed record Command(Guid Id) : IRequest;
private static Task Handle(Command request, IOrderRepository orders, CancellationToken ct) => orders.Cancel(request.Id, ct);
}
}An instance handler class takes its services through its constructor instead, and nests beside its request in a static container:
public static partial class ShipOrder
{
public sealed record Command(Guid Id) : IRequest;
public sealed partial class Handler(IOrderRepository orders, TimeProvider clock)
{
private ValueTask Handle(Command request, CancellationToken ct) => orders.Ship(request.Id, clock.GetUtcNow(), ct);
}
}It has exactly one non-private constructor (ordinary or primary, or none at all), public outside a host; several, a protected one,
required members, an abstract class or a positional record class are KRX007. Its constructor parameters follow the
injected-parameter rules below (KRX013, KRX016, KRX018; a CancellationToken belongs on Handle). It
may derive from a base class, as long as it inherits no member named like Keryx's generated ones (KRX015). Keryx generates
only its InvokeAsync. A host's pipeline context constructs it once per scope and pipeline, on first use, over the services it resolves
for the pipeline (shared with the behaviors, as below), and never registers it in the container; one without constructor parameters is
one instance for the whole process. A notification's instance handler is built inside the publish, the first time the publish reaches
it in the scope, so a constructor that throws fails only that handler: its exception joins the publish's AggregateException and the
other handlers run (a request's or stream request's throwing constructor fails the Send or Stream call). One instance serves every
call of its pipeline in a scope, concurrent calls included, so hold only what the constructor assigns: a non-readonly instance field or
field-like event, a property with a set accessor or a primary-constructor parameter that a member writes (outside a field or property
initializer) is warning KRX027. When two calls in
one scope first use a pipeline at the same time, its constructor can run twice (the losing instance is discarded), so a constructor
should only assign its parameters. An instance Handle in a class beside the request that omits or mistypes the request is
KRX003 (not KRX001).
An instance handler class may implement IDisposable or IAsyncDisposable. The host disposes every instance it builds with the scope
that built it, as the container disposes a service: for each one, the pipeline context resolves a small generated disposer (registered
transient by AddKeryx()) after the handler's services, so the scope disposes the handler before those services, with DisposeAsync
where the handler has it when the scope is disposed asynchronously, else with Dispose, and an instance a first-use race discarded too.
A handler that implements only IAsyncDisposable cannot be disposed by a synchronously disposed scope, which then throws
InvalidOperationException, as the container does for such a service; dispose the scope with DisposeAsync. A throwing Dispose is
handled as the container handles any service's. A disposable handler without constructor parameters is built per scope instead of
shared. A scope that builds no disposable handler pays nothing for them; one that builds one pays, on 64-bit, 24 B per instance for its
disposer and, if it is the scope's first disposable service, 88 B for the container's list of them (pinned in HostAllocationTests).
Each request has one handler in the whole application, in the request's own assembly (KRX005 within it, KRX023
elsewhere): a request without one is KRX001 in its assembly, hosts included (code fixes: add a handler stub, or add an
instance handler class Handler, in a new static container for a top-level request), and a handler of a
request declared in another assembly is KRX023. Notifications may be handled in any assembly.
Injected parameters are resolved by generated code, never by reflection:
| Parameter | Resolved with |
|---|---|
T |
GetRequiredService<T>() |
T with a default value |
GetService<T>(), falling back to the default |
[FromKeyedServices("key")] T |
GetRequiredKeyedService<T>("key"); the key is a constant (KRX018) |
IServiceProvider |
the scope's provider itself, never resolved (keyed: an ordinary keyed service) |
IMediator, ISender, IPublisher |
a new mediator over the same scope, sharing the scope's pipeline contexts |
CancellationToken |
the token of the call |
Every handler gets a public invoker, InvokeAsync, which runs the handler and nothing else: no behaviors, no container. For a
static container whose handler injects services it is on the generated Invoker; unit tests construct the Invoker with fakes and call
it:
#pragma warning disable KRX050 // a test calls the generated members directly
var invoker = new CreateOrder.Invoker(new FakeOrderRepository());
var id = await invoker.InvokeAsync(new CreateOrder.Command("apple", 3), CancellationToken.None);The members Keryx generates into a handler class (the constructor, InvokeAsync, the Invoker's constructor and InvokeAsync) are for
a host's generated code, so they carry [Experimental("KRX050")]: any other code that uses one gets the error KRX050, and
application code sends through the mediator instead. A test project that calls them suppresses it, with the #pragma above or
<NoWarn>$(NoWarn);KRX050</NoWarn>.
A non-static handler class carries the constructor and InvokeAsync itself (new CreateOrder(new FakeOrderRepository())), an instance
handler class is constructed with its own constructor (new ShipOrder.Handler(fakeOrders, fakeClock).InvokeAsync(command, ct)), and a
handler with nothing injected gets a static InvokeAsync. To test whole pipelines (behaviors, notification fan-out), reference Keryx
from the test project, which makes it a host (a test project that targets net10.0 or later is one by default), call AddKeryx() on a
ServiceCollection and send through the mediator. A test host can reference the app host.
A test swaps what a request handler does through the services it injects: it registers fakes for them (after the app's own registrations, if it reuses them: with Microsoft's container the last registration wins), and the handler's pipeline context resolves the fakes. Registering the handler class itself changes nothing: the mediator does not resolve handler classes from the container.
var services = new ServiceCollection();
services.AddKeryx();
services.AddSingleton<IOrderRepository, FakeOrderRepository>();A request handler cannot be excluded or replaced: it lives in its request's assembly, a host's handler of a referenced request is
KRX023, and ExcludeHandler naming one is KRX039. A notification handler can be dropped with
[assembly: ExcludeHandler(typeof(TheHandler))], and the test host may handle the notification with its own.
A behavior wraps a pipeline. It is a static class marked with one or more kind attributes, and for each kind it declares one
static behavior method named Handle (or HandleAsync):
| Kind attribute | Wraps | Open method's message type | next |
Returns |
|---|---|---|---|---|
[RequestBehavior] |
one Send |
TRequest : IRequest<TResponse> |
struct, INext<TResponse> |
ValueTask<TResponse> |
[StreamBehavior] |
the inner stream of one Stream (see Streaming) |
TRequest : IStreamRequest<TItem> |
struct, IStreamNext<TItem> |
IAsyncEnumerable<TItem> |
[NotificationBehavior] |
one whole Publish (see Notifications) |
TNotification : INotification |
struct, INext |
ValueTask |
[RequestBehavior]
[BehaviorOrder(Phase.Observability)]
public static class Audit
{
public static async ValueTask<TResponse> Handle<TRequest, TResponse, TNext>(
TRequest request, TNext next, IAuditLog log, CancellationToken cancellationToken)
where TRequest : IRequest<TResponse>
where TNext : struct, INext<TResponse>
{
var response = await next.InvokeAsync(cancellationToken);
log.Record(request, response);
return response;
}
}
[RequestBehavior]
[BehaviorOrder(Phase.Validation)]
public static class CheckQuantity
{
public static ValueTask<Guid> Handle<TNext>(CreateOrder.Command request, TNext next, CancellationToken cancellationToken)
where TNext : struct, INext<Guid>
=> request.Quantity > 0 ? next.InvokeAsync(cancellationToken) : throw new ArgumentOutOfRangeException(nameof(request));
}next is a generated struct, and the generated pipeline calls each behavior method directly, with explicit type arguments: no behavior
instance, no delegate, no closure and no virtual or generic virtual call per step. Because next is a struct type argument rather than
a delegate, each behavior method is compiled for its own link and the JIT can inline next.InvokeAsync. A behavior may call next more than once (retry) or
not at all (short-circuit).
Requests with no response. An IRequest has no TResponse, so its pipeline runs the request behavior methods of its own shape:
next constrained struct, INext (the non-generic one) and a ValueTask return type, open
(Handle<TRequest, TNext> with where TRequest : IRequest) or closed. You rarely write it. When a behavior class is partial and
declares only the open method with a response, Keryx generates the other one into the class from it, so one method covers both kinds of
request:
[RequestBehavior]
public static partial class Timing
{
public static async ValueTask<TResponse> Handle<TRequest, TResponse, TNext>(TRequest request, TNext next, ILogger<TRequest> logger, CancellationToken ct)
where TRequest : IRequest<TResponse>
where TNext : struct, INext<TResponse>
{
var started = Stopwatch.GetTimestamp();
var response = await next.InvokeAsync(ct);
logger.LogInformation("{Elapsed}", Stopwatch.GetElapsedTime(started));
return response;
}
// Generated, in Timing.IRequest.Keryx.g.cs:
// public static async ValueTask Handle<TRequest, TNext>(TRequest request, TNext next, ILogger<TRequest> logger, CancellationToken ct)
// where TRequest : IRequest
// where TNext : struct, INext
// {
// var started = Stopwatch.GetTimestamp();
// await next.InvokeAsync(ct);
// logger.LogInformation("{Elapsed}", Stopwatch.GetElapsedTime(started));
// return;
// }
}The generated method is the original with the response type parameter removed: ValueTask<TResponse>, Task<TResponse>,
INext<TResponse> and IRequest<TResponse> become their non-generic forms, return await next.InvokeAsync(ct); becomes the await
and a return;, and a local that only carries the response from next to a return is dropped. It keeps the method's attributes, and
is named HandleAsync (or Handle) when the class already has a method with its name and parameters, such as a notification behavior
written alike. Keryx cannot write it when the class or a type that contains it is not partial, or when the body uses the response (its
value, typeof(TResponse), a call that infers it): that is warning KRX028, and the behavior then applies only to requests
with a response. Two code fixes settle it: one makes the class partial; the other writes the method into the class, rewritten as far
as Keryx can, for you to finish where the original used the response. A method you write yourself always wins over a generated one. A
method whose constraints already limit it to requests with a response (where TResponse : struct, or a message constraint such as
ICommand<TResponse>) gets no copy and no warning.
Behavior methods. The message, next and an optional CancellationToken are found by type, in any order; every other parameter is
injected like a handler's (keyed and default-valued forms included). The host resolves those services once per scope into the
pipeline context, so no behavior instance is ever created (a [StreamBehavior] method's own iterator is still allocated per Stream
call; see Streaming). The context holds each service once, however many behavior methods and handlers of the pipeline
inject it (same type and same key; a keyed and an unkeyed IClock are two services): it is resolved as required when any of them
requires it, and otherwise once as optional, with each consumer's own default applied when it is missing. So a transient service that
several behaviors or handlers of one pipeline inject is one instance per scope and pipeline, shared by them, not one per behavior or
handler: a request's handler and its behaviors get the same instance, and so do all the handlers of a notification (owner decision 43). An unkeyed
IServiceProvider is the scope's provider itself: the context holds it in its own ServiceProvider field when a behavior method or one
of the host's own handlers (through its static entry) injects it, a referenced handler's constructor receives the context's constructor
provider directly, and otherwise the context has no such field. The
context's fields are named by service type and key, not by where they are first used, so reordering behaviors or their parameters
does not rename them. A method is either:
- open: generic in the message, its response (or item) and
TNext, with the message type parameter constrained to the kind's message interface (table above) or to an interface that derives from it:where TRequest : ICommand<TResponse>withICommand<T> : IRequest<T>counts and limits the method to commands, aswhere TNotification : IDomainEventlimits a notification behavior to domain events. Further constraints narrow where it applies. The response (or item) type parameter may be written annotated,TResponse?, innext, the return type and the message constraint: the method then fits responses that are annotated (string?), declared nullable-oblivious, or value types (int; withwhere TResponse : struct,TResponse?isNullable<TResponse>and fits onlyint?), but not a non-annotatedstring; or - closed: generic only in
TNext, over one concrete message type, withnextcarrying exactly that message's response or item type (the non-genericINext, and aValueTaskreturn type, for anIRequest).
A class that is not static or is generic, a kind attribute without a matching method, two methods of one kind, a partially open
method or one with other type parameters, an open method without the message constraint (or constrained to an unrelated interface), a
wrong next or return type, or a static
Handle/HandleAsync whose kind the class does not carry, that has no valid next, or whose next and message type belong to
different kinds is KRX019. One class may carry several kind attributes; when two of its methods would have the same parameter
list, name one Handle and the other HandleAsync. Outside a host the class and method are public; in a host internal is enough
(KRX016).
Attaching. A behavior applies through any of three scopes, and the union (without duplicates) runs. typeof(X) always names the
behavior class; in a pipeline it means X's method of that pipeline's kind.
- per target:
[Behavior(typeof(Audit))]on a request or stream handler method, or, for a[NotificationBehavior], on the notification type.[Behavior]on a notification handler method has no effect (KRX042): notification handlers have no pipelines of their own; - per assembly:
[assembly: Behavior(typeof(Transaction))]applies to every matching target in that assembly (for a notification behavior, the notification types declared there); - global:
[GlobalBehavior]on the behavior class applies each of its behaviors to every matching target in every host that references it; on a behavior method, only that method's kind is global. A host removes one with[assembly: ExcludeBehavior(typeof(Audit))], which removes the class from pipelines of every kind; Info KRX035 lists every global behavior a host applies, once per kind.
An open method applies where its constraints hold for the target's types, nullable annotations included; a closed one where its message and response (or item) types are identical to the target's. Assembly and global behaviors that do not fit are skipped; one attached explicitly that does not fit is KRX009.
Ordering. Lower runs first (further out). Behaviors sort by [BehaviorOrder(Phase)] (Outermost 0, Observability 100, Security
200, Validation 300, Default 400, Caching 450, Transaction 500, Innermost 600; any value in between works), then by its
Order, then by [RunsAfter(typeof(X))]/[RunsBefore(typeof(X))] edges, then by class name. These attributes go on the behavior class;
the same attribute on a behavior method overrides the class's for that method's kind. A cycle, or an edge that contradicts phase or
order, is KRX008.
A stream request's handler returns IAsyncEnumerable<TItem>, usually as an async iterator with [EnumeratorCancellation] on its token:
public partial class ListOrders
{
public sealed record Query : IStreamRequest<Order>;
private static async IAsyncEnumerable<Order> Handle(Query request, IOrderRepository orders, [EnumeratorCancellation] CancellationToken ct)
{
await foreach (var order in orders.All(ct))
{
yield return order;
}
}
}
await foreach (var order in mediator.Stream(new ListOrders.Query(), ct)) { /* ... */ }With no stream behaviors, Stream returns the handler's enumerable as is. A [StreamBehavior] wraps the stream: its method gets the
inner stream from next.InvokeAsync(ct) and returns the stream the caller (or the next behavior out) sees, typically by re-yielding it
from its own async iterator. It can filter, map, buffer, catch, retry by calling next again, or serve items without calling next:
[StreamBehavior]
public static class SkipNulls
{
public static async IAsyncEnumerable<TItem> Handle<TRequest, TItem, TNext>(
TRequest request, TNext next, [EnumeratorCancellation] CancellationToken cancellationToken)
where TRequest : IStreamRequest<TItem>
where TNext : struct, IStreamNext<TItem>
{
await foreach (var item in next.InvokeAsync(cancellationToken))
{
if (item is not null)
{
yield return item;
}
}
}
}Per Stream call, Keryx allocates one iterator per stream behavior (its own), nothing per item, and one linked
CancellationTokenSource only when both the Stream token and the WithCancellation token can be cancelled and differ. A null or
unknown stream request throws from the Stream() call itself, before any behavior runs.
A notification has zero or more handlers, in any assembly the host references:
public sealed record OrderPlaced(Guid Id) : INotification;
public partial class SendConfirmation
{
private static ValueTask Handle(OrderPlaced notification, IEmailSender email, CancellationToken ct) => email.Confirm(notification.Id, ct);
}
public partial class AuditEverything
{
[HandlerOrder(-10)]
private static ValueTask Handle(INotification notification, IAuditLog audit) => audit.Write(notification); // every notification
}
await mediator.Publish(new OrderPlaced(id), ct);- A handler whose parameter is a base type or interface (or
INotificationitself) receives every notification type the host knows that converts to it. A type the host does not know reaches no handler. - Handlers run in
[HandlerOrder]order (default 0), then by class name. - Publishing is sequential by default.
[PublishStrategy(PublishStrategy.Parallel)]on the notification type starts every handler before awaiting any. - Every handler runs, whatever the others do. If any fail,
Publishthrows oneAggregateExceptionwith every failure in handler order, even for a single failure. Cancelling the token does not skip handlers; each sees the cancelled token. An instance handler class is built inside the publish on its first use in the scope, so its constructor's exception is that handler's failure too. - A
[NotificationBehavior]wraps the whole publish, handlers and strategy included, once perPublish, also when there are no handlers. Attach it with[Behavior]on the notification type,[assembly: Behavior]in the notification type's assembly, or[GlobalBehavior]; itsTNotificationis the concrete published type. Handlers have no behaviors of their own: they are called directly under either strategy. - A struct notification delivered to a handler typed as an interface is boxed once per
Publish(Info KRX037).
[NotificationBehavior]
public static class CountPublishes
{
public static ValueTask Handle<TNotification, TNext>(TNotification notification, TNext next, IPublishCounter counter, CancellationToken ct)
where TNotification : INotification
where TNext : struct, INext
{
counter.Increment(typeof(TNotification).Name);
return next.InvokeAsync(ct);
}
}
[Behavior(typeof(CountPublishes))]
public sealed record OrderShipped(Guid Id) : INotification;A project is a host when its KeryxHost MSBuild property is true. The package sets it for you when the project leaves it empty:
executables (OutputType Exe or WinExe), test projects and Android apps (AndroidApplication) that target net10.0 or later are
hosts, and everything else is not: class libraries, and any project that targets an older framework (net8.0, .NET Framework). So a
net8.0 app or test project that uses a Keryx library builds without being a host, and a test project that multi-targets
net8.0;net10.0 is a host in its net10.0 build only. Set the property yourself to change that:
<PropertyGroup>
<!-- A class library that hosts the mediator; or false in an executable or test project that is not a host. -->
<KeryxHost>true</KeryxHost>
</PropertyGroup>A host needs net10.0 or later: setting <KeryxHost>true</KeryxHost> in a project below it is KRX031.
Host diagnostics about something without a source location (a referenced
type, the target framework) are reported without a location, so their severity is set for the whole project (a .globalconfig or
<NoWarn>), not in an .editorconfig section.
The host composes every pipeline at compile time from its own handlers and from the handlers, behaviors and notification types of every assembly it references, and generates, in its root namespace:
internal sealed partial class KeryxMediator : IMediator, withISender.Send,ISender.StreamandIPublisher.Publish, plus a typed overload for each request and notification (ValueTask<Guid> Send(CreateOrder.Command)), which skips type dispatch;- interceptors for the host's own calls through
IMediator,ISenderandIPublisher(KeryxInterceptors.Keryx.g.cs, below); internal static IServiceCollection AddKeryx(this IServiceCollection services), which registersKeryxMediator,IMediator,ISenderandIPublisheras transient factories that each create a mediator (sp => new KeryxMediator(sp)), a scoped state that holds the scope's pipeline contexts, with generated factories andTryAdd. It registers no handler class (owner decision 42) and no behavior: a pipeline context resolves the services the host's own handler injects and calls the handler's generatedinternal static __keryx_InvokeAsync(owner decision 44), so the mediator never constructs the host's handler classes or theirInvokers; it constructs a referenced (library) handler withnew(a static container's generatedInvoker, or a non-static handler class), once per scope and pipeline. Each pipeline context resolves a service once for all its behaviors and handlers (owner decision 43). A polymorphic notification handler gets one instance (or one set of services) per publish pipeline.
The mediator is transient and small (owner decision 46): it holds the scope's provider and, from its first call that needs a
pipeline context, the scope state, which every mediator resolved in the scope shares. So each resolve is a new mediator, but the
pipeline contexts are one per scope and pipeline, whichever mediator, or how many, the scope uses. Each pipeline context is
created once per scope, lazily, and kept in the state; it holds the services the handler injects (or a referenced handler) and the
services the pipeline's behavior methods inject, and nothing creates a behavior instance. A request or stream pipeline with a static handler whose behaviors inject nothing, and a notification type whose
handlers are all static (or that has none) and whose behaviors inject nothing, have no context at all (open-questions-v1 OQ-65 and OQ-70):
such a pipeline's entry calls the outermost behavior method, or the handler, or for a notification its static publish strategy, directly,
and each next link holds only the request or notification. A scope that uses no context resolves no state and allocates only the 32 B
mediator for Keryx. The state has one 8 B field per pipeline with a context (16 B plus 8 B per pipeline: 96 B for 10, 416 B for 50), at
any host size: owner decision 49 measured bounded layouts for hosts above 32 such pipelines, and each slowed the long-lived path
(open-questions-v1 OQ-78). From then on a Send allocates nothing. A handler's or behavior method's transient dependencies live as long as the
scope, and the behaviors and handlers of one pipeline that inject the same transient share one instance.
Singletons and hosted services that need the mediator create a scope with IServiceScopeFactory. A singleton that injects
KeryxMediator, IMediator, ISender or IPublisher passes ValidateOnBuild and is resolved (the mediator is transient), and gets a
mediator over the root provider: with ValidateScopes on, as in ASP.NET Core's Development environment, its first call that needs a
pipeline context throws ("Cannot resolve scoped service '…KeryxMediator+__KeryxScopeState' from root provider"). That is a deliberate
trade-off, like the one MediatR makes with its transient IMediator, and the generator does not warn about it (open-questions-v1 OQ-76,
decided, and "The mediator is transient over a scoped state").
The generic Send<TResponse>(IRequest<TResponse>) dispatches on the exact runtime type: a switch statement with a type pattern per
sealed request type (case Ping r: return ...;, one method-table compare each), and above 32 request types a FrozenDictionary lookup
of request.GetType() and a jump table. It never boxes the response, and every section returns its handler's pipeline as a tail call.
A struct request is boxed when sent through ISender; the typed overload avoids it (Info KRX021). An unknown request type
throws KeryxHandlerNotFoundException: dispatch never falls back to a base type's handler. Generic Stream dispatches the same way.
Generic Publish compares notification.GetType() with each notification type instead (notification types need not be sealed), so a
notification type the host does not know (even one derived from a type it does) runs nothing; polymorphic handlers receive only the
types the host knows.
A typed overload binds only when the variable is a KeryxMediator. In a host, a call through IMediator, ISender or IPublisher
whose argument is a request, stream request or notification type the host composes, such as mediator.Send(new CreateOrder.Command(...)),
skips type dispatch too: the host generator intercepts it with a
C# interceptor that calls the typed overload when the
receiver is the host's KeryxMediator, and makes the interface call as written for any other receiver (a test double, a decorator).
Results, exceptions and diagnostics are those of the generic call. Calls compiled in a library, calls whose argument is typed as
IRequest<T>, a request base or INotification (or reaches the parameter through a user-defined conversion), and calls in an
expression tree stay generic (owner decision 61; ADR 0001,
Mediator). The package's build files add the interceptors' namespace, Keryx.Generated, to
InterceptorsNamespaces in a host; to keep the calls generic:
<PropertyGroup>
<KeryxInterceptCalls>false</KeryxInterceptCalls>
</PropertyGroup>A project that sets InterceptorsNamespaces after the package's targets without Keryx.Generated gets no interceptors (and no error).
Hosts are Native AOT and trimming safe: CI publishes the sample host with PublishAot=true, fails
on any trim or AOT warning and runs it.
The generated sources are readable C#, written as text by the generators (nothing reformats them afterwards). On a host of 300 requests with five behaviors each, 30 stream requests and 30 notifications, the host generator takes about 50 ms of a build and the handler generator about 30 ms, and neither runs again on an edit that changes no handler, behavior or message type (open-questions-v1 OQ-71).
Requests, notifications and handlers can live in any project that references Keryx, including netstandard2.0 libraries. Each such
assembly carries a manifest in its metadata ([assembly: KeryxManifest] and one [KeryxHandler] attribute per public or internal
handler class, or, for a static container whose handler injects services, on its generated Invoker), which every host that references
it reads, whether the reference is a project or a package.
- A request or stream request is declared in the same assembly as its handler. KRX001 checks that every request has one there, in libraries and hosts alike, and a handler of a request from another assembly is KRX023.
- A contracts assembly declares notifications (and shared types) that other assemblies handle; a notification may be handled in any assembly. It declares no requests.
- A handler library declares its requests with their handler classes,
publicorinternal, may handle notifications declared elsewhere, and may declare[GlobalBehavior]s that every referencing host applies. - In the host,
[assembly: ExcludeHandler(typeof(X))]drops a referenced notification handler, which the host may replace with its own. It names only notification handlers: a request or stream request handler, referenced or the host's own, is KRX039 and stays (a host's handler of a referenced request would be KRX023); swap what it does through the services it injects (Testing handlers). A referenced request the host has no handler for is KRX030; a.globalconfig(or<NoWarn>) can lower KRX030 for the whole host. - A host referenced by another host (a test project referencing the app) gets only the handlers the referenced host keeps
public; the referencing host reports KRX030 for every request of the referenced host without such a handler. ExcludeHandlerandExcludeBehaviorare read only by a host; anywhere else they are KRX043.
A library's handler classes can be internal, so the projects that reference it see its requests and notifications and not their
handlers:
public static partial class CreateOrder
{
public sealed record Command(string Sku, int Quantity) : IRequest<int>;
internal sealed partial class Handler(IOrderRepository orders)
{
private ValueTask<int> Handle(Command request, CancellationToken cancellationToken) => orders.AddAsync(request, cancellationToken);
}
}The request, its response, the services the handler injects and an instance handler class's constructor stay public, since the host's
generated code names them (KRX016); only the class is hidden. The manifest lists the class as it lists a public one, and the
host generates the same pipeline. Because the host cannot name the class, it holds the handler as object and constructs and calls it
through [UnsafeAccessor] methods that name the class with [UnsafeAccessorType("Orders.CreateOrder+Handler, Orders")] (.NET 10): the
runtime binds each to the class's constructor or InvokeAsync once, and a call through one is a direct call, with no reflection, under
the JIT and NativeAOT alike (measured). Two things differ from a public handler class:
- The accessor is bound at run time, at the handler's first use. If the library loaded at run time is not the one the host was built
against and the member is gone, that use throws
MissingMethodExceptionwhere a public class would fail to load the same way. - A library that gives the host
[InternalsVisibleTo]gets no accessors: the host names the class as it names a public one.
A host's own internal handler classes work as before, and stay out of its manifest.
See samples/libraries (a handler library with the order requests, each nested in the class of its handler, the order notifications and their handlers, and a global behavior) and samples/hosts.
Every diagnostic links here. KRX005 (within one assembly), KRX008 (within one assembly) and KRX022 need the whole compilation: the IDE
shows them with full-solution analysis on, and every build reports them. KRX001 is reported live, on the request, as you type. KRX010,
KRX014 (a static handler class with injected parameters, allowed since static containers) and KRX020 are retired.
| ID | Severity | Meaning |
|---|---|---|
| KRX001 | Error | A request or stream request has no handler in its assembly (in every assembly, hosts included). Code fixes: add a handler stub (next to a nested request, or in a new static container for a top-level one), or add an instance handler class Handler (next to a nested request, or nested in a new static container for a top-level one). |
| KRX002 | Error | A handler is not private, or returns a type its request kind does not allow (including async void). Code fix: make it private, keeping it static or instance. |
| KRX003 | Error | A handler has no request or notification parameter, more than one, or a request parameter typed as IRequest<T>, an abstract or closed request base or an interface. |
| KRX004 | Error | A handler class or a containing type is not partial, is file-local, is narrower than internal (private, protected), or is not a class. Code fix: add partial (or public). |
| KRX005 | Error | A request has two handlers in one assembly. A request's handler lives in its request's assembly (KRX023), so there is no check across assemblies. |
| KRX006 | Error | A class directly contains more than one handler. |
| KRX007 | Error | A static handler's class declares an instance or primary constructor, derives from a class other than object (interfaces are fine), or has injected parameters and is abstract or declares required members. An instance handler class has no or several non-private constructors, a protected one, a non-public one outside a host, required members (declared or inherited), or is abstract or a positional record class. |
| KRX008 | Error | Behavior ordering has a cycle, or RunsAfter/RunsBefore contradicts phase or order. Reported once per pair of behavior classes (and per kind where a method overrides the class's ordering). |
| KRX009 | Error | A behavior attached with [Behavior] to a request or stream handler method or a notification type does not fit it: not a behavior class, no behavior method of the target's kind, constraints that do not hold (nullable annotations included, such as a TResponse? method against a string response), or a closed method over other types. The host reports it for behaviors a referenced handler or notification type attaches. |
| KRX011 | Error | A type implements more than one request closing, both request kinds, or a request interface and INotification. |
| KRX012 | Error | A request, stream request or notification is generic, nested in a generic type or a ref struct; or a handler class is generic. |
| KRX013 | Error | A handler or behavior method parameter, or an instance handler class's constructor parameter, is ref, in, out or params, an injected parameter is a ref struct or a pointer, there is more than one CancellationToken, or the constructor takes one. |
| KRX015 | Error | A handler class declares a member named InvokeAsync or starting with __keryx_ (the generated fields, __keryx_p_<parameter>, and static entry use it), or is itself named InvokeAsync or __keryx_...; an instance handler class inherits such a member from a base class; or a static container whose handler injects services declares a member named Invoker or is named Invoker (Keryx generates a nested Invoker there). |
| KRX016 | Error | Outside a host, a type a pipeline needs (request, response, notification, injected or constructor parameter type) or a behavior class or method is not public. In a host, one is narrower than internal or file-local. |
| KRX017 | Warning | A handler's response type differs from the request's only in nullability. |
| KRX018 | Error | A [FromKeyedServices] key on a handler or behavior method parameter, or on an instance handler class's constructor parameter, is not a compile-time constant, or uses the parameterless form. |
| KRX019 | Error | A behavior class has an unsupported shape: not static or generic, a kind attribute without a matching behavior method, two methods of one kind, a partially open method or one with other type parameters, an open method whose message type parameter lacks the kind's message constraint (directly or through a derived interface), a next without the struct and interface constraint, a wrong return type, or a static Handle/HandleAsync whose kind the class does not carry, that has no valid next, or whose next and message type belong to different kinds. |
| KRX021 | Info | A struct request is boxed when sent through ISender; the host's typed overload avoids it. |
| KRX022 | Error | The project compiles with C# below 14. Remove the LangVersion setting or set it to 14 or later. The generators emit nothing until then. |
| KRX023 | Error | A handler takes a request or stream request declared in another assembly. A request's handler lives in the request's own assembly; move the request or the handler. Notifications are not affected. |
| KRX024 | Error | A request or stream request class or record is neither sealed nor abstract (or closed). Seal it, or make it an abstract base of sealed requests. Notifications are not affected. Code fix: make it sealed. |
| KRX025 | Error | A static handler's class implements IDisposable or IAsyncDisposable (directly, or through another interface). It is stateless and Keryx never disposes its object: inject the disposable service instead, or make Handle an instance method (an instance handler class may be disposable). |
| KRX026 | Error | An instance handler method takes a parameter other than its request or notification and one CancellationToken. Its services go on its class's constructor. Code fix: move the parameter to the constructor. |
| KRX027 | Warning | An instance handler class has mutable instance state: a non-readonly instance field or field-like event, an instance property with a set accessor (init is fine) or a primary-constructor parameter that a member writes, in the class or in a base class of the same project. One instance serves every call of its pipeline in a scope (every call in the process without constructor parameters), concurrent calls included. Static members are not reported. |
| KRX028 | Warning | An open request behavior method (Handle<TRequest, TResponse, TNext>) does not apply to requests with no response (IRequest), because Keryx cannot generate its method for them: the class or a type that contains it is not partial, or the body uses the response. Code fixes: make the class partial; or write the method for requests with no response into the class, rewritten as far as Keryx can, to finish by hand. Not reported for a method whose constraints limit it to requests with a response, or when the class declares that method itself. |
| KRX030 | Error | A referenced request (including one declared in another host) has no handler in the host: a safety net for an internal handler of a referenced host, or a library built with KRX001 suppressed. The host's own requests are KRX001's. Reported without a location: change its severity in a .globalconfig or with <NoWarn>. |
| KRX031 | Error | A host (KeryxHost is true) targets a framework older than net10.0. The host generator emits nothing there. Keryx defaults KeryxHost to true only on net10.0 or later, so this means the project (or a file it imports) sets <KeryxHost>true</KeryxHost> itself (Hosts). |
| KRX032 | Error | A referenced assembly's manifest is newer than this Keryx understands. Upgrade Keryx in the host. |
| KRX033 | Warning | A referenced assembly uses Keryx but has no manifest (the generator did not run there; reference the Keryx package directly). |
| KRX034 | Error | A type a referenced manifest names, or one generated code derives from it (a handler's response or constructor parameter type, an instance handler class's base class, an injected parameter type of a referenced behavior method), cannot be resolved from the host, or a manifest entry no longer fits the types the host resolves. Reference the assembly the message names. For a behavior method it names the method and its kind; the class still applies through its other kinds. |
| KRX035 | Info | Lists each global behavior the host applies, once per kind, and the assembly it comes from. |
| KRX036 | Warning | An exclusion has no effect: ExcludeHandler names no referenced notification handler class the host would compose (a request handler is KRX039), or ExcludeBehavior names a type that is not part of any pipeline. |
| KRX037 | Info | A struct notification is delivered to a handler typed as an interface or INotification, so it is boxed once per Publish. |
| KRX038 | Error | A referenced request or stream request type is not sealed (its assembly suppressed KRX024). The host does not compose it: sending it throws KeryxHandlerNotFoundException. Seal it in its own assembly. |
| KRX039 | Error | ExcludeHandler names a request or stream request handler (referenced or the host's own). It names only notification handlers, so the handler stays in the host; swap what it does through the services it injects (Testing handlers). |
| KRX040 | Warning | [HandlerOrder] on a method that is not a notification handler. |
| KRX041 | Warning | [PublishStrategy] on a type that is not a notification. |
| KRX042 | Warning | [Behavior] where it has no effect (including on a notification handler method), or [GlobalBehavior] on a class without a behavior kind attribute or on a method that is not a behavior method. |
| KRX043 | Warning | [assembly: ExcludeHandler] or [assembly: ExcludeBehavior] in a project that is not a host (KeryxHost is not true), where it has no effect. |
| KRX050 | Error | Code uses a member Keryx generated into a handler class (its constructor, InvokeAsync, an Invoker's constructor or InvokeAsync). They are for a host's generated code: send through the mediator. Reported by the compiler, from [Experimental("KRX050")] on those members (.NET 8 and later); a test that calls them suppresses it. |
test/Keryx.Benchmarks compares Keryx with a hand-written direct call and with the other source-generated and reflection-based
mediators, each in its own small project under test/benchmark-subjects, all running the same requests, handler bodies and
behaviors. Every benchmark is one call on a mediator resolved beforehand (scoped ones from a scope that lives for the whole run), except
the real-world scope-per-request rows; behaviors complete synchronously. "Typed" is a library's per-request entry point, IMediator its
generic method; n/a marks a scenario the library has no API for. How each library is set up is in the ADR's
Benchmarks section, and the checks behind it in
open-questions-v1.md (OQ-51, and OQ-72 for the real-world scenarios).
Each cell is the mean time per call and the bytes allocated per call (exact: BenchmarkDotNet's reports round them to KB once a column
reaches 1 KB, so they are taken from its log, total bytes over operations). One local run of the whole comparison suite on 2026-11-28, at
commit bdaf06f (built from a clean git archive of it), after the scope-cost rework: owner decision 46 (a transient mediator over a
scoped state), decisions 42 and 44 (no handler registrations; the host's own handlers called through a static entry), decision 43 (a
context's handlers and behaviors share its services) and decision 41 (the publishes to 25, 50 and 100 handlers). It ran first under the
JIT and then under NativeAOT (below), with the settings below, one class at a time: each class started only after 30 s with
no build, test or benchmark busy on the machine and was watched every 3 s while it ran, to be run again if one started; none did.
"Decision 37's run" in the notes is the previous full run (2026-11-27, at 3575a50, on the same machine, before decisions 41 to 46), and
"decision 32's run" the one before it (1652e50). The dispatch-scaling tables come from a later run of those classes alone, for owner
decision 58 (below), and the NativeAOT times, in the NativeAOT tables and the
dispatch-scaling NativeAOT columns, from a NativeAOT run of every class for owner decision 62 (2026-11-29 and 30, at 68f4e36 with the
verification probe's calls removed from the benchmark builds; below).
BenchmarkDotNet v0.15.8, macOS 27.2.1 (26B131) [Darwin 27.2.0]
Apple M4 Max, 1 CPU, 16 logical and 16 physical cores
.NET SDK 11.0.100
[Host] : .NET 10.0.15 (10.0.15, 10.0.1526.53008), Arm64 RyuJIT armv8.0-a
Job-UDEAPE : .NET 10.0.15 (10.0.15, 10.0.1526.53008), Arm64 RyuJIT armv8.0-a
IterationCount=15 IterationTime=200ms LaunchCount=1 WarmupCount=5
How to read them:
- Times under about 0.5 ns are below what BenchmarkDotNet resolves: the JIT inlined the whole call, pipeline included, into the
benchmark (the direct call's synchronous
Sendat every depth and itsPublishto 1, 5, 25 and 50 handlers, Keryx's typedSendat every depth and its typedPublishto 1, 5 and 25 handlers, and Mediator singleton'sMediatorclass at depth 0). Compare those rows by order of magnitude. - With a yielding handler, the time is the thread-pool hop of
Task.Yield()and varies by a few hundred nanoseconds from run to run (804 to 1,133 ns in the table below, 1,101 to 1,771 ns in decision 37's run and 844 to 1,384 ns in decision 32's); the allocation column is the meaningful one. In this run Keryx's typed overload measured 1,064 to 1,180 ns in every yielding scenario (the six classes of the two tables), 1.11 to 1.47 times the direct call, while itsIMediatorrows measured 862 to 946 ns, with the same bytes, and a re-run of three of those classes repeated it. That is the hop too, not Keryx's code (owner decision 53, open-questions-v1 OQ-82): four interleaved rounds ofSendYieldDepth0,SendYieldDepth3andSendUnitYieldTaskat the commits before, during and after the scope-cost rework found the same generated typed path and the same JIT code of the benchmark method at every commit. Averaged over those rounds, atbdaf06fand at the latest commit the typed overload measured 895 and 904 ns at depth 0 and 930 and 944 ns at depth 3 (IMediator883 and 910 ns, 956 and 943 ns). With theasync Taskhandler it measured 1,198 and 1,195 ns, against 1,027 to 1,098 ns at the four commits before, whileIMediatormeasured 1,222 to 1,277 ns at every commit; that row moved atbdaf06f, which changed only the benchmark runner. NativeAOT did not show the pattern (typed 858 to 941 ns,IMediator845 to 914 ns, in decision 62's NativeAOT run). The tables keep this run's rows. The direct call's 112 B (averaged over thread-pool work, so it moves by a byte or two between runs) is the handler's own async state machine, so a library that shows the same adds nothing. - In the stream scenarios the direct call's 120 B is the handler's iterator. Each stream behavior adds its own iterator.
- In the real-world scenarios the handler's work (the
Pongit allocates, the log messages, the query) is in every row, the direct call included, so compare each row with the direct call rather than with zero.
| Subject | 0 behaviors | 1 behavior | 3 behaviors | 8 behaviors |
|---|---|---|---|---|
| Hand-written direct call | 0.03 ns · 0 B | 0.03 ns · 0 B | 0.02 ns · 0 B | 0.03 ns · 0 B |
| Keryx, typed overload | 0.00 ns · 0 B | 0.00 ns · 0 B | 0.00 ns · 0 B | 0.44 ns · 0 B |
Keryx, IMediator |
2.44 ns · 0 B | 2.68 ns · 0 B | 2.68 ns · 0 B | 2.68 ns · 0 B |
Keryx, IMediator intercepted in the host |
0.31 ns · 0 B | — | — | — |
Mediator 3.0.2 scoped, Mediator class |
25.4 ns · 64 B | 43.6 ns · 160 B | 63.7 ns · 352 B | 123 ns · 832 B |
Mediator 3.0.2 scoped, IMediator |
27.4 ns · 64 B | 44.3 ns · 160 B | 66.3 ns · 352 B | 119 ns · 832 B |
Mediator 3.0.2 singleton, Mediator class |
0.37 ns · 0 B | 1.42 ns · 0 B | 5.39 ns · 0 B | 13.8 ns · 0 B |
Mediator 3.0.2 singleton, IMediator |
4.10 ns · 0 B | 4.80 ns · 0 B | 8.63 ns · 0 B | 17.2 ns · 0 B |
MediatR 15.0.0, IMediator |
31.9 ns · 200 B | 68.8 ns · 440 B | 101 ns · 728 B | 186 ns · 1,448 B |
Immediate.Handlers 4.4.0, Handler class |
7.33 ns · 0 B | 8.07 ns · 0 B | 9.50 ns · 0 B | 13.8 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
10.7 ns · 0 B | 9.18 ns · 0 B | 8.37 ns · 0 B | 13.5 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
21.6 ns · 24 B | 22.0 ns · 24 B | 21.6 ns · 24 B | 24.0 ns · 24 B |
Generic dispatch tests each sealed request type with a type pattern (open-questions-v1, "Requests are sealed"): Keryx's IMediator rows
measure 2.44 to 2.68 ns here, 2.69 to 3.37 ns in decision 37's run, 2.44 to 2.74 ns in decision 32's run and 3.22 to 3.51 ns in the run
of 2026-11-26, before the type patterns (at this scale a nanosecond moves between runs).
The intercepted row (owner decision 61) is IMediator.Send on the same mediator as the IMediator row, from a call site compiled in
the Keryx host, which the host routes to the typed overload (Hosts); it is measured
with no behaviors only. It comes from two interleaved rounds on 2026-11-30 with the interceptors' fallback in a non-inlined helper (owner
decision 65, at a210ba5 with the change, against a210ba5; each case's two sides from one attempt pair in which nothing overlapped
either benchmark process): 0.31 and 0.32 ns, against 0.33 and 0.32 ns before the change, the typed overload's 0.00 ns and the IMediator
row's 2.45 and 2.48 ns in the same rounds; the table shows the first round (decision 61's three rounds measured 0.32 to 0.38 ns;
open-questions-v1, OQ-91).
| Subject | 0 behaviors | 1 behavior | 3 behaviors | 8 behaviors |
|---|---|---|---|---|
| Hand-written direct call | 931 ns · 113 B | 844 ns · 113 B | 966 ns · 112 B | 886 ns · 113 B |
| Keryx, typed overload | 1,129 ns · 112 B | 1,064 ns · 113 B | 1,069 ns · 113 B | 1,133 ns · 113 B |
Keryx, IMediator |
862 ns · 113 B | 925 ns · 113 B | 946 ns · 113 B | 878 ns · 113 B |
Mediator 3.0.2 scoped, Mediator class |
866 ns · 176 B | 838 ns · 272 B | 856 ns · 464 B | 917 ns · 944 B |
Mediator 3.0.2 scoped, IMediator |
905 ns · 177 B | 919 ns · 273 B | 948 ns · 464 B | 881 ns · 944 B |
Mediator 3.0.2 singleton, Mediator class |
856 ns · 113 B | 850 ns · 113 B | 820 ns · 113 B | 849 ns · 113 B |
Mediator 3.0.2 singleton, IMediator |
878 ns · 113 B | 852 ns · 113 B | 846 ns · 113 B | 890 ns · 113 B |
MediatR 15.0.0, IMediator |
804 ns · 232 B | 806 ns · 472 B | 842 ns · 760 B | 889 ns · 1,480 B |
Immediate.Handlers 4.4.0, Handler class |
992 ns · 371 B | 893 ns · 372 B | 1,006 ns · 372 B | 875 ns · 368 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
887 ns · 245 B | 907 ns · 244 B | 922 ns · 243 B | 919 ns · 244 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
856 ns · 279 B | 832 ns · 279 B | 968 ns · 278 B | 916 ns · 278 B |
| Subject | 0 stream behaviors | 3 stream behaviors |
|---|---|---|
| Hand-written direct call | 630 ns · 120 B | 624 ns · 120 B |
| Keryx, typed overload | 630 ns · 120 B | 2,744 ns · 648 B |
Keryx, IMediator |
630 ns · 120 B | 2,730 ns · 648 B |
Mediator 3.0.2 scoped, Mediator class |
658 ns · 184 B | 2,772 ns · 1,048 B |
Mediator 3.0.2 scoped, IMediator |
644 ns · 184 B | 2,768 ns · 1,048 B |
Mediator 3.0.2 singleton, Mediator class |
631 ns · 120 B | 2,695 ns · 696 B |
Mediator 3.0.2 singleton, IMediator |
632 ns · 120 B | 2,706 ns · 696 B |
MediatR 15.0.0, IMediator |
1,299 ns · 512 B | 7,304 ns · 2,336 B |
Immediate.Handlers 4.4.0, Handler class |
617 ns · 120 B | 2,704 ns · 672 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
637 ns · 120 B | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator |
653 ns · 144 B | n/a |
With 3 stream behaviors Keryx allocates 648 B per Stream (typed and IMediator), 32 B less than the 680 B before OQ-65: a pipeline
that resolves nothing has no pipeline context and its next links hold only the request (open-questions-v1 OQ-65). The generic Stream
slowdown with no stream behaviors that interleaved reruns found after the type patterns (20 to 60 ns, 3 to 9%; owner decision 22) does not
show in this run either: IMediator measured 630.3 ns (standard deviation 2.4 ns), the typed overload 629.5 ns (5.3 ns) and the direct
call 630.4 ns (1.7 ns), all three below the 649 to 661 ns those reruns measured before the type patterns (decision 37's run: 639.2,
648.2 and 645.8 ns). It stays on the release checklist (whats-left.md).
Beside the depth scenarios above, real-world scenarios send a Ping that a handler answers with a new Pong record, or publish a
Pinged notification, closer to what an application does (owner decision 30). The handler bodies and behaviors are the same in every
library.
Requests:
RealWorldPing: the handler alone, from the long-lived scope.RealWorldPingScopePerRequest: the same with a scope per request: the measured call creates a DI scope, resolves the mediator (or the library's entry point) from it, sends and disposes the scope, the way an ASP.NET Core request does. For Keryx this includes creating the transientKeryxMediator(and, where a pipeline has a context, resolving the scope state), which the long-lived rows hide.RealWorldBehaviors: a logging behavior (Microsoft.Extensions.Logging, two messages per request, really formatted by an in-memory provider that keeps the last 1,024) and a validation behavior (a hand-writtenIValidator<TRequest>, scoped) around a handler that injects a scoped repository doing a dictionary lookup, from the long-lived scope.RealWorldBehaviorsScopePerRequest: the same with a scope per request, so the repository, the validator and the pipeline (for Keryx, the pipeline context that holds the handler's and the behaviors' services) are created for each call.RealWorldSqlite: a handler that runs a parameterized scalar query against an in-memory SQLite database (Microsoft.Data.Sqlite), seeded once per process, on the container's singleton open connection (opened in setup), from the long-lived scope.
| Subject | Ping |
Ping, scope per request |
Behaviors | Behaviors, scope per request | SQLite query |
|---|---|---|---|---|---|
| Hand-written direct call | 2.20 ns · 32 B | 49.9 ns · 368 B | 117 ns · 520 B | 212 ns · 920 B | 1,275 ns · 1,144 B |
| Keryx, typed overload | 2.27 ns · 32 B | 29.9 ns · 192 B | 122 ns · 520 B | 268 ns · 1,048 B | 1,305 ns · 1,144 B |
Keryx, IMediator |
5.77 ns · 32 B | 34.2 ns · 192 B | 126 ns · 520 B | 269 ns · 1,048 B | 1,271 ns · 1,144 B |
Mediator 3.0.2 scoped, Mediator class |
30.6 ns · 96 B | 91.4 ns · 472 B | 195 ns · 776 B | 380 ns · 1,648 B | 1,319 ns · 1,208 B |
Mediator 3.0.2 scoped, IMediator |
30.2 ns · 96 B | 95.9 ns · 472 B | 193 ns · 776 B | 382 ns · 1,648 B | 1,321 ns · 1,208 B |
Mediator 3.0.2 singleton, Mediator class |
2.94 ns · 32 B | 24.9 ns · 160 B | n/a | n/a | 1,265 ns · 1,144 B |
Mediator 3.0.2 singleton, IMediator |
7.70 ns · 32 B | 31.9 ns · 160 B | n/a | n/a | 1,293 ns · 1,144 B |
MediatR 15.0.0, IMediator |
35.6 ns · 232 B | 73.9 ns · 432 B | 255 ns · 1,176 B | 324 ns · 1,608 B | 1,324 ns · 1,344 B |
Immediate.Handlers 4.4.0, Handler class |
11.2 ns · 32 B | 79.3 ns · 400 B | 136 ns · 520 B | 297 ns · 1,400 B | 1,298 ns · 1,144 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
19.6 ns · 32 B | n/a | n/a | n/a | 1,298 ns · 1,168 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
22.0 ns · 56 B | 50.0 ns · 208 B | 181 ns · 544 B | 250 ns · 928 B | 1,279 ns · 1,168 B |
Pingfrom the long-lived scope: Keryx's typed overload measures 2.27 ns against the direct call's 2.20 ns (the 32 B is thePong).- Scope per request: Keryx's typed overload measures 29.9 ns and allocates 192 B, against the direct call's 49.9 ns and 368 B and
ZeroAlloc.Mediator's 50.0 ns and 208 B; through
IMediator34.2 ns and 192 B. The mediator is a transient 32 B object that takes no scope entry, andPing's pipeline has no context (its handler is static), so the scope resolves no scope state (owner decision 46). In decision 37's run, with the scoped mediator, Keryx measured 55.1 and 67.9 ns and allocated 448 B. Mediator singleton is the only subject faster here (24.9 ns and 160 B), because nothing scoped is resolved. - Behaviors from the long-lived scope: Keryx's typed overload measures 122 ns against the direct call's 117 ns, with the same 520 B
(
IMediator126 ns); the other libraries measure 136 to 255 ns. - Behaviors with a scope per request: Keryx measures 268 ns typed and 269 ns through
IMediator, both 1,048 B, against the direct call's 212 ns and 920 B (decision 37's run: 328 and 339 ns, 1,408 B). The first call in a scope creates the transient mediator, resolves the scope state (96 B in this host, a field per pipeline with a context; see Benchmarks,KeryxContextPadding) and creates the pipeline context, which resolves each of the handler's and the behaviors' services once (owner decision 43) and calls the handler's static entry, so the handler class is neither registered nor constructed (owner decisions 42 and 44). ZeroAlloc.Mediator, whose behaviors resolve their services from the provider on every call, is still the fastest library here, 250 ns and 928 B (252 ns in decision 37's run), 18 ns and 120 B below Keryx; from the long-lived scope it measures 181 ns, behind Immediate.Handlers (136 ns) and Keryx (122 to 126 ns). The other libraries measure 297 to 382 ns. - The SQLite query (about 1.3 µs and 1,144 B) is most of every row in the last column.
IMediatorwith a scope per request allocates what the typed overload allocates.Pingper request measures 34.2 ns against the typed overload's 29.9 ns, about the generic dispatch (5.77 ns against 2.27 ns from the long-lived scope); in decision 37's run, whereIMediatorwas a transient forwarder resolving the scoped mediator as a second container call (open-questions-v1 OQ-74), 67.9 ns against 55.1 ns.
Notifications, each to 1 and to 5 handlers:
RealWorldPublish1ScopePerRequestandRealWorldPublish5ScopePerRequest: a publish with a scope per request; each handler looks the pong up in the scoped repository and writes a log message.RealWorldPublishBehavior1ScopePerRequestandRealWorldPublishBehavior5ScopePerRequest: the same with the logging behavior as a notification behavior (two messages per publish). Only Keryx has notification behaviors; Mediator's, MediatR's and ZeroAlloc.Mediator's behaviors wrap requests only, so they are n/a here, and the scenario is a pair of its own so the rows above compare every library on the same work.RealWorldPublishAsync1andRealWorldPublishAsync5: handlers that await the SQLite query and then log, published sequentially (each library's default) from the long-lived scope. The await is the query's, notTask.Yield's.RealWorldPublishParallel1andRealWorldPublishParallel5: the same handlers with each library's parallel strategy: Keryx's[PublishStrategy(PublishStrategy.Parallel)], Mediator'sTaskWhenAllPublisher(a generator option, so a third Mediator project, singleton, shown in the Mediator singleton rows), MediatR'sTaskWhenAllPublisher(a second container) and ZeroAlloc.Mediator's[ParallelNotification].- The same four scenarios with 25, 50 and 100 handlers (owner decision 41):
RealWorldPublish{25,50,100}ScopePerRequest,RealWorldPublishBehavior{25,50,100}ScopePerRequest,RealWorldPublishAsync{25,50,100}andRealWorldPublishParallel{25,50,100}, with the same subjects, handler bodies and n/a cells. Their notifications live in a fan-out project per library (test/benchmark-subjects/Keryx.Benchmarks.FanOut.*, written bytest/benchmark-subjects/GenerateFanOut.csso every library has the same handlers), not in the projects the other rows measure, so adding them changed none of those rows. Their tables follow the 1 and 5 handler ones.
Per request scope:
| Subject | 1 handler | 5 handlers | 1 handler + behavior | 5 handlers + behavior |
|---|---|---|---|---|
| Hand-written direct call | 122 ns · 456 B | 443 ns · 1,232 B | 200 ns · 608 B | 513 ns · 1,384 B |
| Keryx, typed overload | 144 ns · 560 B | 316 ns · 816 B | 220 ns · 704 B | 392 ns · 960 B |
Keryx, IMediator |
149 ns · 560 B | 312 ns · 816 B | 225 ns · 704 B | 392 ns · 960 B |
Mediator 3.0.2 scoped, Mediator class |
239 ns · 888 B | 675 ns · 2,104 B | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
243 ns · 888 B | 688 ns · 2,104 B | n/a | n/a |
MediatR 15.0.0, IMediator |
238 ns · 1,248 B | 658 ns · 2,496 B | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator |
126 ns · 456 B | 364 ns · 840 B | n/a | n/a |
Handlers that await the SQLite query, from the long-lived scope:
| Subject | Sequential, 1 handler | Sequential, 5 handlers | Parallel, 1 handler | Parallel, 5 handlers |
|---|---|---|---|---|
| Hand-written direct call | 1,312 ns · 1,176 B | 6,630 ns · 5,880 B | 1,325 ns · 1,176 B | 6,832 ns · 5,880 B |
| Keryx, typed overload | 1,365 ns · 1,176 B | 6,801 ns · 5,880 B | 1,358 ns · 1,176 B | 6,742 ns · 5,880 B |
Keryx, IMediator |
1,342 ns · 1,176 B | 6,620 ns · 5,880 B | 1,355 ns · 1,176 B | 6,692 ns · 5,880 B |
Mediator 3.0.2 scoped, Mediator class |
1,355 ns · 1,176 B | 6,770 ns · 5,880 B | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
1,356 ns · 1,176 B | 6,792 ns · 5,880 B | n/a | n/a |
Mediator 3.0.2 singleton, Mediator class |
1,321 ns · 1,176 B | 6,710 ns · 5,880 B | 1,339 ns · 1,176 B | 6,669 ns · 5,880 B |
Mediator 3.0.2 singleton, IMediator |
1,349 ns · 1,176 B | 6,680 ns · 5,880 B | 1,334 ns · 1,176 B | 6,778 ns · 5,880 B |
MediatR 15.0.0, IMediator |
1,507 ns · 1,952 B | 7,129 ns · 7,648 B | 1,526 ns · 2,232 B | 7,398 ns · 8,032 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
1,358 ns · 1,208 B | 6,851 ns · 6,040 B | 1,364 ns · 1,208 B | 6,895 ns · 6,040 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
1,369 ns · 1,208 B | 7,030 ns · 6,040 B | 1,389 ns · 1,208 B | 6,798 ns · 6,040 B |
Per request scope, 25, 50 and 100 handlers:
| Subject | 25 handlers | 50 handlers | 100 handlers | 25 handlers + behavior | 50 handlers + behavior | 100 handlers + behavior |
|---|---|---|---|---|---|---|
| Hand-written direct call | 1,981 ns · 5,792 B | 4,124 ns · 12,360 B | 8,586 ns · 26,280 B | 2,078 ns · 5,952 B | 4,220 ns · 12,520 B | 8,745 ns · 26,448 B |
| Keryx, typed overload | 1,136 ns · 2,112 B | 2,240 ns · 3,712 B | 4,615 ns · 6,912 B | 1,219 ns · 2,256 B | 2,329 ns · 3,856 B | 4,751 ns · 7,064 B |
Keryx, IMediator |
1,125 ns · 2,112 B | 2,222 ns · 3,712 B | 4,505 ns · 6,912 B | 1,209 ns · 2,256 B | 2,253 ns · 3,856 B | 4,655 ns · 7,064 B |
Mediator 3.0.2 scoped, Mediator class |
3,138 ns · 9,832 B | 6,799 ns · 21,152 B | 16.78 µs · 45,368 B | n/a | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
3,067 ns · 9,832 B | 6,816 ns · 21,152 B | 17.11 µs · 45,368 B | n/a | n/a | n/a |
MediatR 15.0.0, IMediator |
2,972 ns · 9,152 B | 6,244 ns · 17,480 B | 13.06 µs · 34,120 B | n/a | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator |
1,687 ns · 2,760 B | 3,322 ns · 5,160 B | 6,956 ns · 9,960 B | n/a | n/a | n/a |
Handlers that await the SQLite query, 25, 50 and 100 handlers, from the long-lived scope:
| Subject | Sequential, 25 handlers | Sequential, 50 handlers | Sequential, 100 handlers | Parallel, 25 handlers | Parallel, 50 handlers | Parallel, 100 handlers |
|---|---|---|---|---|---|---|
| Hand-written direct call | 34.46 µs · 29,400 B | 66.96 µs · 58,800 B | 136.6 µs · 117,600 B | 33.77 µs · 29,400 B | 67.40 µs · 58,800 B | 135.4 µs · 117,600 B |
| Keryx, typed overload | 33.93 µs · 29,400 B | 68.83 µs · 58,800 B | 139.8 µs · 117,600 B | 34.22 µs · 29,400 B | 68.71 µs · 58,800 B | 140.8 µs · 117,600 B |
Keryx, IMediator |
33.42 µs · 29,400 B | 67.75 µs · 58,800 B | 135.4 µs · 117,600 B | 33.59 µs · 29,400 B | 66.64 µs · 58,800 B | 134.5 µs · 117,600 B |
Mediator 3.0.2 scoped, Mediator class |
33.86 µs · 29,400 B | 67.04 µs · 58,800 B | 136.0 µs · 117,600 B | n/a | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
34.05 µs · 29,400 B | 68.17 µs · 58,800 B | 136.7 µs · 117,600 B | n/a | n/a | n/a |
Mediator 3.0.2 singleton, Mediator class |
34.75 µs · 29,400 B | 73.33 µs · 58,800 B | 134.6 µs · 117,600 B | 33.47 µs · 29,400 B | 67.24 µs · 58,800 B | 134.5 µs · 117,600 B |
Mediator 3.0.2 singleton, IMediator |
34.10 µs · 29,400 B | 68.13 µs · 58,800 B | 134.4 µs · 117,600 B | 34.53 µs · 29,400 B | 68.40 µs · 58,800 B | 135.1 µs · 117,600 B |
MediatR 15.0.0, IMediator |
35.94 µs · 36,544 B | 71.93 µs · 72,672 B | 143.7 µs · 144,912 B | 36.14 µs · 37,088 B | 72.99 µs · 73,416 B | 148.1 µs · 146,056 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
34.29 µs · 30,200 B | 69.74 µs · 60,400 B | 140.3 µs · 120,800 B | 34.49 µs · 30,200 B | 69.66 µs · 60,400 B | 139.9 µs · 120,800 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
34.67 µs · 30,200 B | 67.94 µs · 60,400 B | 136.7 µs · 120,800 B | 34.37 µs · 30,200 B | 68.10 µs · 60,400 B | 141.7 µs · 120,800 B |
- Per request scope, Keryx's typed overload measures 144 ns (1 handler) and 316 ns (5 handlers), against the direct call's 122 ns and 443 ns
and ZeroAlloc.Mediator's 126 ns and 364 ns; through
IMediator149 ns and 312 ns, with the same bytes (560 B and 816 B). With the notification behavior it measures 220 ns and 392 ns typed (225 and 392 ns throughIMediator; 704 B and 960 B), against the direct call's 200 ns and 513 ns. In decision 37's run, before the scope-cost rework, the typed overload measured 164, 570, 251 and 672 ns and allocated 560, 1,336, 712 and 1,488 B in these four columns. With 5 handlers Keryx is now below the direct call (whose handler classes are registered scoped) and ZeroAlloc.Mediator: the publish context resolves the repository and the logger once for all five handlers, and for the behavior where there is one (owner decision 43) and calls the handlers' static entries, so no handler object is registered or created (owner decisions 42 and 44). With 1 handler ZeroAlloc.Mediator and the direct call stay ahead, by 18 to 22 ns and 104 B: a Keryx scope that uses a pipeline context also creates the transient mediator and resolves the scope state (96 B in this host; open-questions-v1 OQ-78, decided: one field per pipeline at every size). - With 25, 50 and 100 handlers per request scope, Keryx measures 1,136, 2,240 and 4,615 ns typed (1,125, 2,222 and 4,505 ns through
IMediator) and allocates 2,112, 3,712 and 6,912 B, 64 B more per handler (its log message); ZeroAlloc.Mediator 1,687, 3,322 and 6,956 ns with 2,760, 5,160 and 9,960 B (96 B more per handler); the direct call 1,981, 4,124 and 8,586 ns with 5,792, 12,360 and 26,280 B, its scoped handler classes each taking a scope entry; MediatR 2,972 ns to 13.06 µs and Mediator scoped 3,067 ns to 17.11 µs. The notification behavior adds 83 to 136 ns to Keryx's typed publish (31 to 150 ns throughIMediator) and 144 to 152 B to both. - SQLite's async methods complete synchronously, so no row waits on I/O: the async and parallel rows measure each library's path for
handlers that return completed tasks, not overlapping work. Each library's parallel strategy measures within 4% of its sequential
publish at every handler count, except Mediator singleton's
Mediatorclass with 50 handlers, whose sequential publish (73.33 µs) is 9% above its parallel one and the direct call. Keryx allocates what the direct call allocates in every column (29,400, 58,800 and 117,600 B with 25, 50 and 100 handlers, as Mediator does; ZeroAlloc.Mediator 32 B more per handler, MediatR 36,544 to 146,056 B), and with 25, 50 and 100 handlers every subject's sequential publish measures within 10% of the direct call's.
Here the direct call is a hand-written handler class (or a publisher class taking the handler classes) resolved from DI that does the
same work, the behaviors' logging and validation included, so the ratio is each mediator's cost on top of that work. n/a, besides the
entry points a library does not have: Mediator singleton in the two request behavior scenarios and the per-request publish (its singleton
handlers and behaviors cannot take the scoped repository and validator); ZeroAlloc.Mediator's static Mediator in the two request
behavior scenarios (its static Send passes behaviors a null state, and the library's static-path alternative would need another
behavior body that opens a scope inside each call) and in every scope-per-request scenario (it has no scope); every library but Keryx in
the notification-behavior pair; Immediate.Handlers in every notification scenario (it has none); Mediator scoped in the parallel pair (its
parallel publisher is the singleton project's). The setup rules are in the ADR's Benchmarks
section (owner decision 33) and the check behind each n/a cell in open-questions-v1.md (OQ-72). Run them on
their own with --filter '*RealWorld*'.
Keryx accepts three handler shapes (owner decisions 69 to 81): a static Handle with injected parameters in a non-static class (the shape
every table above measures), the same Handle in a static container class, and an instance handler class whose constructor takes the
services. These scenarios measure what the shape costs on the real-world work above: RealWorldBehaviors and
RealWorldBehaviorsScopePerRequest (TypicalPing through the logging and the validation behavior to a handler that looks the pong up in
the scoped repository) and RealWorldPublish1ScopePerRequest and RealWorldPublish5ScopePerRequest (TypicalPinged1 and
TypicalPinged5, each handler looking the pong up and writing a log message), with Keryx's handlers written in each shape, synchronous
and with an async Handle that awaits a lookup that completes synchronously: HandlerShapesBehaviors,
HandlerShapesBehaviorsScopePerRequest, HandlerShapesPublish1ScopePerRequest and HandlerShapesPublish5ScopePerRequest. They come from
a Keryx host of their own, test/benchmark-subjects/Keryx.Benchmarks.HandlerShapes.KeryxHost (owner decision 83, as for the fan-out
host): adding them changed nothing in Keryx.Benchmarks.KeryxHost, whose generated mediator is byte for byte the one before (its 10
pipeline contexts, 96 B scope state and dispatch unchanged), so no row above moved under the JIT: two rounds of adjacent interleaved pairs
of the commit before and the change on RealWorldBehaviors, RealWorldBehaviorsScopePerRequest and RealWorldPublish1 and
5ScopePerRequest under the JIT measured the same bytes and Keryx's rows within -1.4% to +2.4% (the direct call within -1.8% to +3.5%).
The NativeAOT rows above were not measured again: the new host's code joins the same NativeAOT image, while Keryx.Benchmarks.KeryxHost's
generated code stays byte for byte the same. Each shape's types are nested in a class of their own with the same names
(StaticShape.TypicalPing, ContainerShape.TypicalPing, ...), so the logging behavior's messages, which carry the type's name, cost the
same in every shape. Run them with --filter '*HandlerShapes*'.
Each class has two categories, each with its static row as the baseline: the typed overloads (below) and IMediator. The host's generic
dispatch tests the types in the order of their full names, so through IMediator the shapes sit at different positions (static last), and
those rows also carry the type tests between positions; read the shapes from the typed rows.
Measured on 2026-12-03 on the machine above, with the same job, from a git worktree copy of the change (one build), twice under the JIT
and twice under NativeAOT; each cell is the first run / the second run, and the bytes were the same in both. Every run started after four
samples 10 s apart in which no developer process outside it was over 20% CPU (40% in sum), no other process over 50% and the load average
under 6, was watched every 3 s, and a class counted only from a run in which nothing overlapped any of its benchmark processes; a class
that overlapped ran again, whole, so each class's rows come from one run. The editor's C# language server woke for about three minutes
after every BenchmarkDotNet build on this machine, so each run held its first benchmark process (a discarded DispatchScale20 case) until
the quiet check passed again.
Under the JIT, typed overload:
| Shape | Behaviors | Behaviors, scope per request | Publish to 1, scope per request | Publish to 5, scope per request |
|---|---|---|---|---|
Static Handle, non-static class (today's shape) |
122 / 123 ns · 520 B | 268 / 269 ns · 1,112 B | 142 / 144 ns · 624 B | 308 / 313 ns · 880 B |
| Static container | 124 / 127 ns · 520 B | 265 / 264 ns · 1,112 B | 143 / 143 ns · 624 B | 308 / 310 ns · 880 B |
| Instance handler class | 125 / 124 ns · 520 B | 266 / 265 ns · 1,136 B | 150 / 149 ns · 664 B | 351 / 341 ns · 1,080 B |
Async static Handle, non-static class |
132 / 131 ns · 520 B | 273 / 275 ns · 1,112 B | 152 / 150 ns · 624 B | 361 / 361 ns · 880 B |
| Async static container | 131 / 135 ns · 520 B | 275 / 272 ns · 1,112 B | 151 / 150 ns · 624 B | 366 / 362 ns · 880 B |
| Async instance handler class | 130 / 134 ns · 520 B | 280 / 278 ns · 1,136 B | 154 / 155 ns · 664 B | 393 / 379 ns · 1,080 B |
Under NativeAOT, typed overload:
| Shape | Behaviors | Behaviors, scope per request | Publish to 1, scope per request | Publish to 5, scope per request |
|---|---|---|---|---|
Static Handle, non-static class (today's shape) |
149 / 148 ns · 520 B | 385 / 392 ns · 1,112 B | 226 / 228 ns · 624 B | 429 / 428 ns · 880 B |
| Static container | 150 / 148 ns · 520 B | 409 / 388 ns · 1,112 B | 228 / 229 ns · 624 B | 426 / 440 ns · 880 B |
| Instance handler class | 149 / 149 ns · 520 B | 395 / 392 ns · 1,136 B | 232 / 234 ns · 664 B | 454 / 458 ns · 1,080 B |
Async static Handle, non-static class |
160 / 158 ns · 520 B | 405 / 402 ns · 1,112 B | 235 / 235 ns · 624 B | 480 / 478 ns · 880 B |
| Async static container | 161 / 162 ns · 520 B | 401 / 399 ns · 1,112 B | 236 / 233 ns · 624 B | 484 / 481 ns · 880 B |
| Async instance handler class | 160 / 160 ns · 520 B | 404 / 402 ns · 1,136 B | 242 / 247 ns · 664 B | 499 / 494 ns · 1,080 B |
- Bytes. From the long-lived scope every shape allocates the same 520 B (the
Pongand the two log messages, as inRealWorldBehaviors), and anasyncHandlethat completes synchronously allocates nothing more in any shape. A static container costs a scope exactly what the static shape costs: the host's pipelines call the same static entry. An instance handler class costs a scope its object and the context's field that holds it, less the fields of services only its constructor takes: 24 B forTypicalPing(1,136 B against 1,112 B: a 24 B handler holding the repository, whose context field it replaces), 40 B for oneTypicalPinged1handler (664 B against 624 B: a 32 B handler holding the repository and the logger, and its field; a publish context keeps the services to build the handler on first use) and 200 B for five (1,080 B against 880 B).HostAllocationTestspins the same differences (3, 5 and 25 pointers on 64-bit). This host's scope state has 18 pipeline fields (160 B), so its scope-per-request rows allocate 64 B more than the real-world rows above (96 B, 10 fields). - Time. From the long-lived scope every synchronous shape measures the same: 122 to 127 ns under the JIT and 148 to 151 ns under
NativeAOT, typed; an
asyncHandleadds about 8 ns (JIT) and 10 ns (NativeAOT), its state machine, in every shape. With a request per scope the instance handler measures what the static shape does (JIT 265 and 266 ns against 268 and 269 ns; NativeAOT 395 and 392 ns against 385 and 392 ns; the container's 409 ns in the first NativeAOT run measured 388 ns in the second, run-to-run variation). A publish per scope to one instance handler measures 5 to 8 ns more than to a static one under the JIT and 5 to 7 ns more under NativeAOT, and to five 28 to 43 ns (JIT) and 26 to 30 ns (NativeAOT) more: each handler object is built on first use in the scope (owner decision 76). IMediator. The same bytes in every row; the times follow the typed rows plus the generic dispatch, which tests the static types last (JIT 126 to 135 ns from the long-lived scope, NativeAOT 150 to 164 ns).- Machine code. Both shapes'
InvokeAsync(the instance method, the container's static entry) are inlined into the validation behavior's code under both runtimes, and the handler'sHandleis a tail call from there, except in the JIT's Tier 1 code with Dynamic PGO, as measured, which inlinesHandletoo (and the repository's lookup behind a type guard) in every shape. The instance path's only extra is the load of the context's handler field and its null check, where the container's loads the repository's field. [MethodImpl(MethodImplOptions.AggressiveInlining)]on the generated instanceInvokeAsyncand on the host's__SendNwas tried (owner decision 81) and is not generated. On the instanceInvokeAsyncit produced the same machine code under both runtimes (every method of the shapes host and the benchmark methods compared, the JIT without Dynamic PGO so its code is deterministic), since both already inline it. On__SendNof an instance request it changed only NativeAOT's code (__SendNinlined into the typed overload's caller), and two rounds of adjacent interleaved pairs on the instance and static-container typed rows ofHandlerShapesBehaviorsandHandlerShapesBehaviorsScopePerRequestmeasured no gain: the instance rows moved by -1.0% to +3.2% (147.2 to 151.9 ns, 150.6 to 150.2 ns; per scope 387.9 to 388.9 ns, 389.7 to 391.9 ns), the static-container rows, whose code did not change, by -2.2% to +1.9%. The JIT's code (without Dynamic PGO) did not change either.
What it costs a host to reach an internal handler class of a library through [UnsafeAccessor] methods
instead of naming it. The handlers are the real-world scenarios', in a library the host references: PublicStatic is a static Handle
with injected parameters in a public handler class, constructed with new and called directly (the baseline); InternalStatic the
same handler in an internal class, constructed and called through accessors and held as object; PublicInstance and
InternalInstance the same pair for an instance handler class. Typed overloads; mean and allocated per call, measured 2026-12-03 on an
Apple M4 Max with .NET 10. Run them with --filter '*ReferencedShapes*'.
| Scenario | Runtime | PublicStatic | InternalStatic | PublicInstance | InternalInstance |
|---|---|---|---|---|---|
| Behaviors, long-lived scope | JIT | 140.7 ns · 520 B | 138.9 ns · 520 B | 139.5 ns · 520 B | 139.0 ns · 520 B |
| Behaviors, scope per request | JIT | 267.4 ns · 1,088 B | 266.3 ns · 1,088 B | 264.4 ns · 1,088 B | 261.6 ns · 1,088 B |
| Publish to 1 handler, scope per call | JIT | 145.3 ns · 600 B | 144.7 ns · 600 B | 145.8 ns · 616 B | 147.3 ns · 616 B |
| Publish to 5 handlers, scope per call | JIT | 329.0 ns · 1,016 B | 328.8 ns · 1,016 B | 351.6 ns · 1,032 B | 346.5 ns · 1,032 B |
| Behaviors, long-lived scope | NativeAOT | 149.6 ns · 520 B | 153.6 ns · 520 B | 154.3 ns · 520 B | 155.1 ns · 520 B |
| Behaviors, scope per request | NativeAOT | 407.0 ns · 1,088 B | 391.7 ns · 1,088 B | 395.5 ns · 1,088 B | 400.2 ns · 1,088 B |
| Publish to 1 handler, scope per call | NativeAOT | 242.9 ns · 600 B | 241.9 ns · 600 B | 247.6 ns · 616 B | 259.2 ns · 616 B |
| Publish to 5 handlers, scope per call | NativeAOT | 476.6 ns · 1,016 B | 502.6 ns · 1,016 B | 484.8 ns · 1,032 B | 469.5 ns · 1,032 B |
An internal class allocates exactly what its public twin does in every row, and its time is within the run's noise of it: under the JIT the largest difference between a public and an internal row is 1.5 %, with standard deviations of about 1 %; the NativeAOT rows are noisier (standard deviations of 1 % to 4 %) and differ by up to 5 % in either direction. The accessors add no measurable cost.
The handler of a request with no response returns a non-generic ValueTask or Task, and its pipeline returns that ValueTask as it is
(a Task wrapped in one): Keryx adds no async path of its own. The direct call awaits the same handler body, so its allocation is the
handler's own state machine; the Performance contract says Keryx adds 0 bytes to it in steady state. The other libraries are left out:
this checks Keryx's contract, not a comparison. The numbers below were measured when such a request responded with a Unit and the
handler's task went through an adapter (UnitAdapter.ToUnit); they have not been measured again since that adapter was removed.
| Subject | async ValueTask handler |
async Task handler |
|---|---|---|
| Hand-written direct call | 862 ns · 97 B | 796 ns · 96 B |
| Keryx, typed overload | 1,180 ns · 96 B | 1,169 ns · 96 B |
Keryx, IMediator |
897 ns · 96 B | 926 ns · 96 B |
The direct call calls the handlers in turn without an async method of its own (it only falls back to one when a handler does not
complete synchronously), so it is the floor. With one handler the JIT inlines all of it and the time is below what BenchmarkDotNet
resolves.
| Subject | 1 handler | 5 handlers |
|---|---|---|
| Hand-written direct call | 0.01 ns · 0 B | 0.64 ns · 0 B |
| Keryx, typed overload | 0.50 ns · 0 B | 0.33 ns · 0 B |
Keryx, IMediator |
3.26 ns · 0 B | 3.16 ns · 0 B |
Mediator 3.0.2 scoped, Mediator class |
16.1 ns · 0 B | 32.9 ns · 0 B |
Mediator 3.0.2 scoped, IMediator |
17.1 ns · 0 B | 25.0 ns · 0 B |
Mediator 3.0.2 singleton, Mediator class |
2.52 ns · 0 B | 14.9 ns · 0 B |
Mediator 3.0.2 singleton, IMediator |
9.00 ns · 0 B | 19.3 ns · 0 B |
MediatR 15.0.0, IMediator |
116 ns · 768 B | 290 ns · 1,728 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
11.5 ns · 0 B | 13.5 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
18.9 ns · 24 B | 55.5 ns · 120 B |
A publish whose handlers are all static and whose behaviors inject nothing (every row here) has no pipeline context and its publish
strategy is static (open-questions-v1 OQ-70): Keryx's typed overload measures 0.50 ns and 0.33 ns (0.44 and 0.48 ns in decision 37's run,
0.34 and 0.44 ns in decision 32's, 0.65 and 0.84 ns before OQ-70), inlined like the direct call, and IMediator 3.26 ns and 3.16 ns
(3.31 and 4.07 ns in decision 37's run; at this scale a nanosecond moves between runs), all 0 B.
PublishTo25, PublishTo50 and PublishTo100 (owner decision 41) publish to 25, 50 and 100 such handlers, from each library's fan-out
project (above):
| Subject | 25 handlers | 50 handlers | 100 handlers |
|---|---|---|---|
| Hand-written direct call | 0.55 ns · 0 B | 0.55 ns · 0 B | 197 ns · 0 B |
| Keryx, typed overload | 0.44 ns · 0 B | 56.6 ns · 0 B | 272 ns · 0 B |
Keryx, IMediator |
3.45 ns · 0 B | 58.0 ns · 0 B | 277 ns · 0 B |
Mediator 3.0.2 scoped, Mediator class |
101 ns · 0 B | 190 ns · 0 B | 381 ns · 0 B |
Mediator 3.0.2 scoped, IMediator |
98.4 ns · 0 B | 183 ns · 0 B | 367 ns · 0 B |
Mediator 3.0.2 singleton, Mediator class |
76.6 ns · 0 B | 164 ns · 0 B | 340 ns · 0 B |
Mediator 3.0.2 singleton, IMediator |
83.3 ns · 0 B | 167 ns · 0 B | 340 ns · 0 B |
MediatR 15.0.0, IMediator |
1,449 ns · 6,944 B | 2,898 ns · 13,472 B | 5,990 ns · 26,512 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
19.1 ns · 0 B | 93.4 ns · 0 B | 291 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
283 ns · 600 B | 619 ns · 1,200 B | 1,205 ns · 2,400 B |
With 25 handlers Keryx's typed overload and the direct call are still below a nanosecond (the handlers' bodies are empty in the builds
BenchmarkDotNet makes, decision 34). With 50 the direct call still is, and Keryx measures 56.6 ns typed and 58.0 ns through IMediator;
with 100 the direct call measures 197 ns and Keryx 272 and 277 ns, against Mediator's 340 to 381 ns and ZeroAlloc.Mediator's static
path's 291 ns. Every subject allocates 0 B except ZeroAlloc.Mediator's IMediator (600, 1,200 and 2,400 B) and MediatR (6,944, 13,472
and 26,512 B).
DispatchScale20, DispatchScale50 and DispatchScale1000 (owner decisions 54 and 68) send through each library's generic entry
point in a host with that many request types, each a sealed record with its own synchronous handler and the same handler body,
so only the dispatch differs. Requests only: no streams, notifications or behaviors. Each call sends the next of 1,024 requests from a
sequence generated in setup from a fixed seed (every type once, random picks over the types for the rest, shuffled), the same sequence
for every library at a given size, so the branch predictor cannot learn one target; the times are per call, from the long-lived scope
(Mediator singleton's from the root), and every row, the floor's included, reads its request from the sequence the same way. Each
size is a compilation of its own per library (test/benchmark-subjects/Keryx.Benchmarks.Dispatch{N}.*, written by
test/benchmark-subjects/GenerateDispatchScale.cs), since the dispatch a generator writes depends on how many requests there are:
Keryx's generic Send tests a type pattern per sealed request type up to 32 types (DispatchThreshold) and above that looks the type
up in a FrozenDictionary<Type, int> and jumps on the index, so 20 is below the threshold and 50 and 1,000 are above it. Mediator
looks the request's handler wrapper up in a FrozenDictionary<Type, object> at every size, and MediatR in a ConcurrentDictionary. The
subjects are Keryx's IMediator, Mediator's IMediator scoped and singleton and MediatR's IMediator. The floor is a hand-written
dispatch, unlike the single typed direct call in the other tables: a static Send(object) per
size that dispatches on the request's runtime type
the way Keryx's generator does at that size (a type-pattern switch at 20 types, the FrozenDictionary<Type, int> index switch above)
and calls each type's static handler directly, not inlined, as Keryx's arms are not. ZeroAlloc.Mediator and Immediate.Handlers are
n/a here: neither has a generic entry point (ZeroAlloc.Mediator's IMediator has a Send overload per request type, chosen at compile
time), so a request whose type is known only at run time, as every request of the sequence is, cannot be sent through either without a
dispatch the caller writes (owner decision 59, open-questions-v1 OQ-86).
These classes were measured in a run of their own, after the tables above, for owner decision 58 (open-questions-v1 OQ-88), which
changed Keryx's generic Send above (its null check): on 2026-11-29, from two git worktree copies of commit 990e62a on the same
machine with the same job, one as committed ("before") and one with decision 58's generator change ("after", whose --verify passed under
the JIT first), each class run on the one and then on the other before the next class, under the JIT and then under NativeAOT on its own
(--runtimes nativeaot10.0). Each run started after four samples 10 s apart showed no dotnet-related process outside it busy (language
servers, other sessions' MSBuild and compiler nodes and the MCP servers included), was watched every 3 s, and was run again when such a
process went over 20% CPU during it (the watcher also counts the Claude desktop app, which is not dotnet); most runs were repeated, up to
six times, and every number below is from a run that nothing overlapped. A burst of macOS background work (asset, suggestion and XProtect
services, a load average of 47) stopped the NativeAOT half after its first four classes; the remaining runs waited for it to end: from
then on each run also started only after no process of any kind was over 50% CPU and the load average was under 6, and a run that took
over 400 s (the machine was suspended during it) counted as overlapped. MSBuild node reuse, the MSBuild server and shared compilation were
off for the benchmark builds. No NativeAOT pilot failed, so none of these benchmarks has a fixed invocation count. The JIT columns are
that run's "after" runs, every row, since every row ran again. The NativeAOT columns are from a later run, for owner decision 62
(open-questions-v1 OQ-89), which removed the verification probe's calls from the benchmark builds: from two git worktree copies of commit
68f4e36, one as committed and one with that change, each class run on the one and then on the other under the same guard, and the
tables show the changed copy's runs. The first pairs of the 20, 50 and 1,000-type classes had measurements 39, 48 and 18 minutes apart, so
those classes ran again on the morning of 2026-11-30 as adjacent pairs, the two runs of each 3 minutes apart, and the tables show those. The
machine was in use and busy with macOS background work, so a run counted only when nothing overlapped BenchmarkDotNet's benchmark processes
(the build before them excluded). The JIT pairs of that step measured the same as before, so the JIT columns stay. Those runs also measured
a 100-type host; owner decision 68 (2026-12-01) dropped it from the suite, since Keryx measured the same there as at 50 types under both
runtimes (12.2 against 12.0 ns under the JIT, 20.6 against 20.8 ns under NativeAOT), and 1,000 types shows how the other libraries scale
more clearly.
Each cell is the mean time per call and the bytes allocated per call, from BenchmarkDotNet's GC lines (total bytes over operations); the
ratio is BenchmarkDotNet's, against the floor of the same run. Under NativeAOT the rows with 0 B have GC lines of 672 or 1,008 B over the
one iteration BenchmarkDotNet measures allocations in (2.4 to 41.8 million calls), as the floor's rows do, and those bytes are not the
benchmark's: BenchmarkDotNet's last forced collection before that iteration leaves the runtime's finalizer thread trimming each
ArrayPool<T>.Shared the process has used, 336 B a pool, while it counts every thread's allocations. BenchmarkDotNet's own code uses
two pools (672 B), and a FrozenDictionary adds a third (1,008 B): the floor's and Keryx's type table from 50 types, and Mediator's at
every size. Under the JIT the trims are done before the count starts (open-questions-v1 OQ-87). MediatR is n/a under NativeAOT, as in
every scenario (below).
20 request types (Keryx's type-pattern switch):
| Subject | JIT | Ratio | NativeAOT | Ratio |
|---|---|---|---|---|
| Hand-written dispatch (the floor) | 3.87 ns · 0 B | 1.00 | 4.03 ns · 0 B | 1.00 |
Keryx, IMediator |
4.41 ns · 0 B | 1.14 | 4.65 ns · 0 B | 1.15 |
Mediator 3.0.2 scoped, IMediator |
70.8 ns · 64 B | 18.33 | 90.7 ns · 48 B | 22.50 |
Mediator 3.0.2 singleton, IMediator |
16.4 ns · 0 B | 4.24 | 16.3 ns · 0 B | 4.06 |
MediatR 15.0.0, IMediator |
70.3 ns · 261 B | 18.18 | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator (no generic entry point) |
n/a | n/a | n/a | n/a |
50 request types (Keryx's FrozenDictionary index switch):
| Subject | JIT | Ratio | NativeAOT | Ratio |
|---|---|---|---|---|
| Hand-written dispatch (the floor) | 9.10 ns · 0 B | 1.00 | 20.9 ns · 0 B | 1.00 |
Keryx, IMediator |
12.0 ns · 0 B | 1.32 | 20.8 ns · 0 B | 0.99 |
Mediator 3.0.2 scoped, IMediator |
101 ns · 64 B | 11.10 | 99.6 ns · 48 B | 4.76 |
Mediator 3.0.2 singleton, IMediator |
17.4 ns · 0 B | 1.91 | 20.9 ns · 0 B | 1.00 |
MediatR 15.0.0, IMediator |
117 ns · 262 B | 12.90 | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator (no generic entry point) |
n/a | n/a | n/a | n/a |
1,000 request types (Keryx's FrozenDictionary index switch):
| Subject | JIT | Ratio | NativeAOT | Ratio |
|---|---|---|---|---|
| Hand-written dispatch (the floor) | 13.1 ns · 0 B | 1.00 | 24.7 ns · 0 B | 1.00 |
Keryx, IMediator |
23.1 ns · 0 B | 1.77 | 24.1 ns · 0 B | 0.98 |
Mediator 3.0.2 scoped, IMediator |
228 ns · 64 B | 17.43 | 295 ns · 48 B | 11.99 |
Mediator 3.0.2 singleton, IMediator |
32.7 ns · 0 B | 2.50 | 85.2 ns · 0 B | 3.46 |
MediatR 15.0.0, IMediator |
179 ns · 264 B | 13.69 | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator (no generic entry point) |
n/a | n/a | n/a | n/a |
- Where the threshold sits.
DispatchThresholdis 32, so the 20-type host is the type-pattern switch and the 50 and 1,000-type hosts are the index switch, for Keryx and for the floor, which has Keryx's shape at each size. From 20 types (type switch) to 50 (index switch) the floor goes from 3.87 to 9.10 ns under the JIT and from 4.03 to 20.9 ns under NativeAOT, and Keryx from 4.41 to 12.0 ns and from 4.65 to 20.8 ns. These sizes change the shape and the number of types together, so they do not show how much of the step is the shape: Mediator singleton, the sameFrozenDictionarylookup at every size, also goes from 16.4 to 17.4 ns under the JIT and from 16.3 to 20.9 ns under NativeAOT. From 50 to 1,000 types (20 times as many) the floor goes from 9.10 to 13.1 ns under the JIT and from 20.9 to 24.7 ns under NativeAOT, and Keryx from 12.0 to 23.1 ns and from 20.8 to 24.1 ns. These sizes do not show at what count between 20 and 50 the two shapes cost the same; that was not measured here. The floor's 3.87 ns at 20 types is partly the branch predictor learning the 1,024-request sequence, which repeats: with 65,536 requests over the same 20 types (a probe, OQ-88) the floor measured 9.6 ns under the JIT and 9.7 ns under NativeAOT. - Keryx allocates 0 B per call at every size under both runtimes. Under the JIT it measures 1.14 times the floor at 20 types and 1.32 at
50 (0.5 and 2.9 ns more) and 1.77 times at 1,000 types (23.1 against 13.1 ns). Under NativeAOT it measures 1.15 times the floor at 20
types (4.65 against 4.03 ns) and 0.99 and 0.98 times above the threshold. Until owner decision 62 it measured 9 to 13 ns above the floor
at every size under NativeAOT; owner decision 58 (OQ-88) looked for where that time went, with disassembly of both runtimes' code and
hand-written dispatches that add one of Keryx's steps at a time (in the same process, with the same sequence):
- The null check (changed). At 1,000 types neither the JIT nor ILC inlined
ArgumentNullException.ThrowIfNull(request)into the genericSend(at 20 and 50 types both did), so everySendcalled it. The generatedSendnow checks with anifand throws the same exception from a helper. In the interleaved run Keryx went from 27.6 to 23.1 ns under the JIT at 1,000 types (2.15 to 1.77 times the floor); the other sizes, whose machine code did not change on the path a request takes, and NativeAOT, where the call measured nothing, stayed within noise (JIT 4.92 and 10.5 ns before, 4.41 and 12.0 ns after; NativeAOT, with the probe call below still there, 13.3, 33.8 and 36.9 ns before, 13.2, 32.8 and 36.0 ns after, at 20, 50 and 1,000 types). - The interface call (outside the generated code).
IMediator.Send<TResponse>is a generic virtual method, so the caller resolves it through the runtime's cache on every call: under the JIT a helper call (the call site is not devirtualized), under NativeAOTGVMLookupForSlot. Calling the mediator's class directly instead saved 1.6 ns at 20 types and 2.4 ns at 1,000 under the JIT (24.8 against 22.4 ns), and 2.7 ns at 20 types under NativeAOT (nothing measurable at 1,000). Every library's genericIMediator.Sendis a generic virtual method too; the hand-written floor is a static method. - One more call under NativeAOT, gone since (the benchmark handlers' probe call; owner decision 62, open-questions-v1 OQ-89).
Keryx's generic
Sendcalls a non-inlined arm per request type, which keepsSend's frame from zeroing a result per type on every call (ADR 0001, Generic entry points). The JIT inlines these benchmarks' small handlers into their arms, so the arm is the only call afterSend, as the floor's handler call is. ILC does not inline a handler whose body calls another method, and these handlers called the verification probe (empty in the benchmark builds, but a call), so under NativeAOTSendcalled the arm and the arm called the handler: a hand-written dispatch with that extra hop measured 7.8 ns more than the floor at 20 types and 10 ns more at 1,000 (8.6 and 11.6 ns under the JIT). The benchmark builds now drop the probe's calls, ILC inlines every handler into its arm, and in adjacent before/after pairs Keryx went from 13.2 to 4.65 ns at 20 types and from 33.5 and 35.9 ns to 20.8 and 24.1 ns at 50 and 1,000 types (the floor 4.03, 20.9 and 24.7 ns after). A handler ILC does not inline (anasyncone, or one that does real work) still pays the arm's call. Arms written inline inSendinstead (withUnsafe.BitCast, no address-taken local) were measured and not shipped, for either runtime (owner decision 66, OQ-90): with inline sections ILC inlines each core intoSendand builds every inlined result in a stack frame ofSendthat it zeroes on every call, and in interleaved pairs the inline shape measured 4.84 ns against the arms' 4.46 and 4.49 ns at 20 types under NativeAOT, and 5.6 against 2.6 to 2.9 ns for the comparison host's genericSendinSendSyncDepth0andSendSyncDepth8there (3.9 to 4.6 against 2.5 to 3.0 ns under the JIT); at 20 types under the JIT it measured as the arms. - Code layout. At 1,000 types an exact copy of the floor's code measured 3.0 ns slower than the floor itself under the JIT (17.2 against 14.2 ns), so differences of a few nanoseconds at that size are partly where the code lands. With the 65,536-request sequence, where the predictor cannot learn the order, Keryx measured 9.4 ns under the JIT against the floor's 9.6 ns, and 20.0 ns under NativeAOT against 9.7 ns while the extra call was there (not measured since). What is left under NativeAOT at 20 types, 0.6 ns, is the interface call, as under the JIT; why Keryx measured below the floor above the threshold was not investigated (the code layout note above applies). Keryx's is the fastest generic entry point at every size under the JIT, and under NativeAOT at 20 and 1,000 types (4.65 against Mediator singleton's 16.3, 24.1 against 85.2 ns); at 50 types it measures as Mediator singleton's does (20.8 against 20.9 ns), which measured faster than Keryx's there before decision 62.
- The null check (changed). At 1,000 types neither the JIT nor ILC inlined
- Mediator 3.0.2 looks up a
FrozenDictionaryat every size. Singleton measures 16.4, 17.4 and 32.7 ns under the JIT and 16.3, 20.9 and 85.2 ns under NativeAOT (at 50 types it equals the floor there, 20.9 ns), 0 B. Scoped allocates 64 B per call under the JIT and 48 B under NativeAOT at every size and grows from 70.8 to 228 ns (JIT) and from 90.7 to 295 ns (NativeAOT) between 20 and 1,000 types. - MediatR 15.0.0 grows from 70.3 to 179 ns between 20 and 1,000 types, 12.90 to 18.18 times the floor, and allocates 260.8, 262 and 263.9 B per call at 20, 50 and 1,000 types (exact, from the GC lines).
- ZeroAlloc.Mediator 7.0.1 is n/a, as Immediate.Handlers is: it has no generic entry point (above). The run at
5d005c2(decision 54's) measured it behind the floor's hand-written dispatch, its typedIMediatoroverload in each arm; that row and its subject projects were removed afterwards (owner decision 59, OQ-86). - At 50 and 1,000 types the floor's and Keryx's rows have a standard deviation of 2.6 to 6.0% of the mean (under 2% at 20 types), and
runs of the same code move by more: under the JIT the two
DispatchScale50runs of this run measured the floor at 9.89 and 9.10 ns and Keryx at 10.5 and 12.0 ns (before and after decision 58, whose JIT code on a request's path is the same at 20 and 50 types, where it was compared). Two more interleaved pairs of that class measured Keryx at 10.4 and 11.6 ns and at 10.7 and 9.92 ns (the floor 9.10 and 9.32, 8.61 and 9.71 ns), so after the change it measured 9.92 to 12.0 ns over three runs and before it 10.4 to 10.7 ns, 0.6 ns slower on average with the same code at other addresses (OQ-88). Compare those rows to within a nanosecond or two.
Run them on their own with --filter '*Comparison.DispatchScale*' (and --runtimes nativeaot10.0 for NativeAOT); each class took about
70 s under the JIT and 120 to 130 s under NativeAOT in this run, which builds a native executable per class.
The same comparison scenarios also run with BenchmarkDotNet's NativeAOT toolchain on net10.0 (owner decision 29), each benchmark compiled
ahead of time instead of JIT-compiled with tiering and Dynamic PGO. The NativeAOT numbers below are from a later run of every comparison
class, for owner decision 62 (open-questions-v1 OQ-89), which removed the verification probe's calls from the benchmark builds: on 2026-11-29
and 30, at commit 68f4e36 with that change (a git worktree copy), with the same settings, one class at a time. Each run started after
four samples 10 s apart in which no developer process outside it (dotnet, MSBuild, compilers, language servers, MCP servers, Spotlight)
was over 20% CPU, no other process over 50% and the load average was under 6, and was watched every 3 s. The machine was in use, so a
measurement counted only when nothing overlapped the benchmark process it came from: BenchmarkDotNet runs each benchmark case in a
process of its own, and a class ran again for the cases still missing, as often as that took. Six classes
also ran as before/after pairs, on a copy of 68f4e36 as committed and on the changed copy, each pair's two runs at most 11 minutes
apart (SendSyncDepth0 and SendSyncDepth8 ran again as adjacent pairs on 2026-11-30, 3 minutes apart, since their first pairs'
measurements were up to 37 minutes and two hours apart, and the tables show those); outside the dispatch-scaling classes only the
direct call's synchronous Send, Keryx's (typed at depth 0, IMediator at depths 0 and 8) and Immediate.Handlers' moved (below). The
JIT times beside them are the third full run's (above, at bdaf06f), since that step's JIT pairs measured the same:
NativeAOT 10.0 : .NET 10.0.15, Arm64 NativeAOT armv8.0-a
Job=NativeAOT 10.0 Runtime=NativeAOT 10.0 Toolchain=Latest ILCompiler
IterationCount=15 IterationTime=200ms LaunchCount=1 WarmupCount=5
A library that cannot run under NativeAOT is n/a there, with the reason found by building and running it: MediatR 15.0.0 is n/a in
every scenario. With the suite's behaviors, AddMediatR throws at startup (AddOpenStreamBehavior: "StreamPass12 must implement MediatR.IStreamPipelineBehavior2"), and without any behaviors the container cannot construct MediatR's Mediator; MediatR.dll also
produces trim and AOT warnings (IL2104, IL3053). Every other subject runs every scenario it runs under the JIT, and --verify checks them
in a NativeAOT build of the suite (378 benchmarks pass, MediatR's 38 are listed as n/a). The setup is recorded in
open-questions-v1.md ("NativeAOT benchmark run").
Each cell is the JIT time and the NativeAOT time, then the bytes allocated (both, when they differ). Read the NativeAOT numbers with four things in mind:
- ILC inlines less into the benchmark than the JIT does. The direct call's synchronous
Sendmeasures 0.49 to 0.50 ns at every depth (its handler is inlined into the benchmark; 1.38 ns while the handlers still called the probe) and Keryx's typed overload 0.56 ns up to 3 behaviors, so these and thePublishrows of the direct call and Keryx's typed overload, which measure under a nanosecond up to 50 handlers (the direct call 0.08, 0.67, 0.68 and 0.67 ns for 1, 5, 25 and 50 handlers, Keryx 0.49, 0.72, 0.74 and 0.73 ns), are compared by order of magnitude. The direct call'sPublishto one handler is a call that returnsdefault, and BenchmarkDotNet 0.15.8 cannot measure it with the job above: its pilot stage reads 0 ns for the first 16 calls and throws. So the runner gives that one benchmark's NativeAOT job a fixed invocation count, 160,000,000 calls per iteration, which skips the pilot, the job otherwise the same (owner decision 39, open-questions-v1 OQ-77; its summary row showsInvocationCount160000000, the othersDefault, and BenchmarkDotNet flags it as indistinguishable from an empty method): 0.08 ns in this run (0.04 ns in the run that proved it, 0.06 ns in decision 37's). The direct call's publishes to 25, 50 and 100 handlers have the same shape; the third run's pilot measured them (its first 16 calls read 10 to 284 ns per call), but the runner gives their NativeAOT jobs fixed counts too, as a safeguard, 115,000,000, 115,000,000 and 1,250,000 calls per iteration, about what that pilot chose (owner decision 52, open-questions-v1 OQ-81): 0.68, 0.67 and 162 ns in this run (0.66, 0.66 and 159 ns in the run that proved it). - The builds BenchmarkDotNet makes have no verification probe, calls included (owner decisions 34 and 62, OQ-73 and OQ-89: the runner
sets
KeryxBenchmarksProbe=falsebefore they build, under which the compiler drops everyProbe.Hitcall, and every comparison benchmark's setup fails a build that still has the probe, so CI's Dry runs check it). Until decision 62 each handler and behavior still called the emptyProbe.Hit(), and under NativeAOT that call kept ILC from inlining the handler or behavior into its caller: in that step's adjacent pairs the direct call's synchronousSendwent from 1.38 to 0.49 ns at depths 0 and 8, Keryx's typed one from 1.44 to 0.56 ns at depth 0 (1.43 and 1.45 ns at depth 8) and itsIMediatorone from 3.22 to 2.73 ns at depth 0 and from 3.22 to 2.86 ns at depth 8, Immediate.Handlers from 20.8 to 18.7 ns and from 24.8 to 23.2 ns, and Keryx's dispatch-scaling rows lost their extra call (above); every other row of the six classes measured both ways (SendSyncDepth0and8,PublishTo1,RealWorldPing,RealWorldBehaviors,StreamDepth0) stayed within its run-to-run spread, for every library. Decision 32's run had the whole probe under NativeAOT: each handler and behavior call carried a field load and a branch, so Keryx's typedSendgrew from 1.59 to 2.67 ns between depth 0 and depth 8 and itsIMediatorSendfrom 3.26 to 5.19 ns. - The behaviors and the direct call read the message type's name once per type, through
MessageName<T>(owner decision 36, OQ-75). Under NativeAOTtypeof(T).Nameallocates a new string on every read (48 B forTypicalPing; nothing under the JIT), and in decision 32's run the behaviors read it for both log messages while the direct call usednameof, which put 96 B more in every library's behavior rows under NativeAOT. Since then Keryx's behavior rows allocate what they allocate under the JIT (in this run 520 B, 1,048 B per request scope, 704 B and 960 B for the notification behavior). In the scope-per-request rows, Microsoft.Extensions.DependencyInjection resolves without generated IL under NativeAOT, so every row's scope cost changes, the direct call's included. - Under NativeAOT BenchmarkDotNet's allocation count also takes in 336 B for each
ArrayPool<T>.Sharedthe benchmark process has used, 672 or 1,008 B per iteration: its last forced collection leaves the runtime's finalizer thread trimming the pools while it counts every thread's allocations (open-questions-v1 OQ-87; under the JIT the trims are done before the count starts). Divided by an iteration's calls that is under 1 B, and it moves the rounded bytes per call only at about 1,400 calls per iteration: in this run it made Mediator's four sequential publishes to 100 handlers that await the query 116,001 B and ZeroAlloc.Mediator's four publishes to 100 such handlers (static class andIMediator, sequential and parallel) 123,201 B, which the table below shows as 116,000 B and 123,200 B, the GC lines less those bytes.
Send, synchronous handler:
| Subject | 0 behaviors | 1 behavior | 3 behaviors | 8 behaviors |
|---|---|---|---|---|
| Hand-written direct call | 0.03 ns → 0.49 ns · 0 B | 0.03 ns → 0.50 ns · 0 B | 0.02 ns → 0.50 ns · 0 B | 0.03 ns → 0.49 ns · 0 B |
| Keryx, typed overload | 0.00 ns → 0.56 ns · 0 B | 0.00 ns → 0.56 ns · 0 B | 0.00 ns → 0.56 ns · 0 B | 0.44 ns → 1.45 ns · 0 B |
Keryx, IMediator |
2.44 ns → 2.73 ns · 0 B | 2.68 ns → 2.77 ns · 0 B | 2.68 ns → 2.81 ns · 0 B | 2.68 ns → 2.86 ns · 0 B |
Keryx, IMediator intercepted in the host |
0.31 ns → 1.49 ns · 0 B | — | — | — |
Mediator 3.0.2 scoped, Mediator class |
25.4 ns · 64 B → 53.5 ns · 48 B | 43.6 ns · 160 B → 80.1 ns · 128 B | 63.7 ns · 352 B → 98.3 ns · 288 B | 123 ns · 832 B → 158 ns · 688 B |
Mediator 3.0.2 scoped, IMediator |
27.4 ns · 64 B → 55.8 ns · 48 B | 44.3 ns · 160 B → 82.6 ns · 128 B | 66.3 ns · 352 B → 102 ns · 288 B | 119 ns · 832 B → 160 ns · 688 B |
Mediator 3.0.2 singleton, Mediator class |
0.37 ns → 2.01 ns · 0 B | 1.42 ns → 2.93 ns · 0 B | 5.39 ns → 5.69 ns · 0 B | 13.8 ns → 17.9 ns · 0 B |
Mediator 3.0.2 singleton, IMediator |
4.10 ns → 4.84 ns · 0 B | 4.80 ns → 5.99 ns · 0 B | 8.63 ns → 8.94 ns · 0 B | 17.2 ns → 20.6 ns · 0 B |
MediatR 15.0.0, IMediator |
31.9 ns · 200 B → n/a | 68.8 ns · 440 B → n/a | 101 ns · 728 B → n/a | 186 ns · 1,448 B → n/a |
Immediate.Handlers 4.4.0, Handler class |
7.33 ns → 18.7 ns · 0 B | 8.07 ns → 18.8 ns · 0 B | 9.50 ns → 19.9 ns · 0 B | 13.8 ns → 23.2 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
10.7 ns → 18.3 ns · 0 B | 9.18 ns → 18.6 ns · 0 B | 8.37 ns → 20.3 ns · 0 B | 13.5 ns → 25.8 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
21.6 ns → 39.2 ns · 24 B | 22.0 ns → 41.4 ns · 24 B | 21.6 ns → 43.8 ns · 24 B | 24.0 ns → 48.8 ns · 24 B |
The intercepted row is from its own interleaved runs (owner decision 65, 2026-11-30, as above; under NativeAOT two rounds, 1.49 and
1.51 ns, the table showing the first, against 1.90 and 1.89 ns before the change, the typed overload's 0.51 ns and the IMediator row's
2.68 and 2.62 ns in the same runs). With its fallback in a non-inlined helper the inlined interceptor saves no registers, but ILC still
builds the fast path's ValueTask<int> on the stack with two 8-byte zero stores and three narrower stores, then one 16-byte load, where
the typed overload's code stores and reloads only the 32-bit result; that is likely why about 1 ns stays between them. The gap is
accepted as a matter of ILC's code generation, with no generator change (open-questions-v1 OQ-91 and OQ-92, both decided).
Send, handler awaits Task.Yield() (the time is the thread-pool hop under both runtimes; compare the allocations):
| Subject | 0 behaviors | 1 behavior | 3 behaviors | 8 behaviors |
|---|---|---|---|---|
| Hand-written direct call | 931 ns → 890 ns · 113 B | 844 ns · 113 B → 863 ns · 114 B | 966 ns · 112 B → 874 ns · 113 B | 886 ns · 113 B → 890 ns · 114 B |
| Keryx, typed overload | 1,129 ns · 112 B → 862 ns · 113 B | 1,064 ns → 858 ns · 113 B | 1,069 ns → 925 ns · 113 B | 1,133 ns → 876 ns · 113 B |
Keryx, IMediator |
862 ns → 885 ns · 113 B | 925 ns → 866 ns · 113 B | 946 ns → 876 ns · 113 B | 878 ns → 845 ns · 113 B |
Mediator 3.0.2 scoped, Mediator class |
866 ns · 176 B → 868 ns · 161 B | 838 ns · 272 B → 945 ns · 240 B | 856 ns · 464 B → 968 ns · 400 B | 917 ns · 944 B → 945 ns · 800 B |
Mediator 3.0.2 scoped, IMediator |
905 ns · 177 B → 910 ns · 162 B | 919 ns · 273 B → 946 ns · 240 B | 948 ns · 464 B → 945 ns · 400 B | 881 ns · 944 B → 1,015 ns · 800 B |
Mediator 3.0.2 singleton, Mediator class |
856 ns → 880 ns · 113 B | 850 ns → 887 ns · 113 B | 820 ns → 879 ns · 113 B | 849 ns → 849 ns · 113 B |
Mediator 3.0.2 singleton, IMediator |
878 ns → 896 ns · 113 B | 852 ns · 113 B → 943 ns · 114 B | 846 ns → 879 ns · 113 B | 890 ns → 835 ns · 113 B |
MediatR 15.0.0, IMediator |
804 ns · 232 B → n/a | 806 ns · 472 B → n/a | 842 ns · 760 B → n/a | 889 ns · 1,480 B → n/a |
Immediate.Handlers 4.4.0, Handler class |
992 ns → 1,015 ns · 371 B | 893 ns · 372 B → 998 ns · 369 B | 1,006 ns · 372 B → 966 ns · 370 B | 875 ns · 368 B → 936 ns · 374 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
887 ns · 245 B → 914 ns · 246 B | 907 ns · 244 B → 966 ns · 246 B | 922 ns · 243 B → 939 ns · 247 B | 919 ns · 244 B → 903 ns · 246 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
856 ns → 951 ns · 279 B | 832 ns → 916 ns · 279 B | 968 ns · 278 B → 963 ns · 279 B | 916 ns · 278 B → 914 ns · 279 B |
Send of an IRequest, handler awaits Task.Yield() (Keryx only):
| Subject | async ValueTask handler |
async Task handler |
|---|---|---|
| Hand-written direct call | 862 ns → 861 ns · 97 B | 796 ns → 810 ns · 96 B |
| Keryx, typed overload | 1,180 ns → 941 ns · 96 B | 1,169 ns → 915 ns · 96 B |
Keryx, IMediator |
897 ns → 905 ns · 96 B | 926 ns → 914 ns · 96 B |
Stream of 100 items:
| Subject | 0 stream behaviors | 3 stream behaviors |
|---|---|---|
| Hand-written direct call | 630 ns → 913 ns · 120 B | 624 ns → 959 ns · 120 B |
| Keryx, typed overload | 630 ns → 908 ns · 120 B | 2,744 ns → 4,155 ns · 648 B |
Keryx, IMediator |
630 ns → 913 ns · 120 B | 2,730 ns → 4,167 ns · 648 B |
Mediator 3.0.2 scoped, Mediator class |
658 ns · 184 B → 970 ns · 168 B | 2,772 ns · 1,048 B → 4,418 ns · 984 B |
Mediator 3.0.2 scoped, IMediator |
644 ns · 184 B → 985 ns · 168 B | 2,768 ns · 1,048 B → 4,183 ns · 984 B |
Mediator 3.0.2 singleton, Mediator class |
631 ns → 919 ns · 120 B | 2,695 ns → 4,538 ns · 696 B |
Mediator 3.0.2 singleton, IMediator |
632 ns → 931 ns · 120 B | 2,706 ns → 4,271 ns · 696 B |
MediatR 15.0.0, IMediator |
1,299 ns · 512 B → n/a | 7,304 ns · 2,336 B → n/a |
Immediate.Handlers 4.4.0, Handler class |
617 ns → 922 ns · 120 B | 2,704 ns → 4,230 ns · 672 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
637 ns → 925 ns · 120 B | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator |
653 ns → 930 ns · 144 B | n/a |
Publish, sequential, synchronous handlers:
| Subject | 1 handler | 5 handlers |
|---|---|---|
| Hand-written direct call | 0.01 ns → 0.08 ns · 0 B | 0.64 ns → 0.67 ns · 0 B |
| Keryx, typed overload | 0.50 ns → 0.49 ns · 0 B | 0.33 ns → 0.72 ns · 0 B |
Keryx, IMediator |
3.26 ns → 6.28 ns · 0 B | 3.16 ns → 6.53 ns · 0 B |
Mediator 3.0.2 scoped, Mediator class |
16.1 ns → 43.5 ns · 0 B | 32.9 ns → 56.3 ns · 0 B |
Mediator 3.0.2 scoped, IMediator |
17.1 ns → 44.1 ns · 0 B | 25.0 ns → 59.6 ns · 0 B |
Mediator 3.0.2 singleton, Mediator class |
2.52 ns → 11.3 ns · 0 B | 14.9 ns → 21.7 ns · 0 B |
Mediator 3.0.2 singleton, IMediator |
9.00 ns → 14.8 ns · 0 B | 19.3 ns → 25.2 ns · 0 B |
MediatR 15.0.0, IMediator |
116 ns · 768 B → n/a | 290 ns · 1,728 B → n/a |
ZeroAlloc.Mediator 7.0.1, static Mediator |
11.5 ns → 16.8 ns · 0 B | 13.5 ns → 18.6 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
18.9 ns → 54.2 ns · 24 B | 55.5 ns → 165 ns · 120 B |
Publish to 25, 50 and 100 synchronous handlers:
| Subject | 25 handlers | 50 handlers | 100 handlers |
|---|---|---|---|
| Hand-written direct call | 0.55 ns → 0.68 ns · 0 B | 0.55 ns → 0.67 ns · 0 B | 197 ns → 162 ns · 0 B |
| Keryx, typed overload | 0.44 ns → 0.74 ns · 0 B | 56.6 ns → 0.73 ns · 0 B | 272 ns → 281 ns · 0 B |
Keryx, IMediator |
3.45 ns → 8.11 ns · 0 B | 58.0 ns → 8.00 ns · 0 B | 277 ns → 290 ns · 0 B |
Mediator 3.0.2 scoped, Mediator class |
101 ns → 163 ns · 0 B | 190 ns → 444 ns · 0 B | 381 ns → 2,263 ns · 0 B |
Mediator 3.0.2 scoped, IMediator |
98.4 ns → 159 ns · 0 B | 183 ns → 441 ns · 0 B | 367 ns → 2,258 ns · 0 B |
Mediator 3.0.2 singleton, Mediator class |
76.6 ns → 120 ns · 0 B | 164 ns → 403 ns · 0 B | 340 ns → 2,219 ns · 0 B |
Mediator 3.0.2 singleton, IMediator |
83.3 ns → 122 ns · 0 B | 167 ns → 403 ns · 0 B | 340 ns → 2,212 ns · 0 B |
MediatR 15.0.0, IMediator |
1,449 ns · 6,944 B → n/a | 2,898 ns · 13,472 B → n/a | 5,990 ns · 26,512 B → n/a |
ZeroAlloc.Mediator 7.0.1, static Mediator |
19.1 ns → 35.7 ns · 0 B | 93.4 ns → 90.1 ns · 0 B | 291 ns → 341 ns · 0 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
283 ns → 750 ns · 600 B | 619 ns → 1,716 ns · 1,200 B | 1,205 ns → 3,645 ns · 2,400 B |
The dispatch-scaling classes' NativeAOT rows are in their own tables, beside the JIT rows (above).
Real-world requests (Ping, from the long-lived scope and per request, the behavior pair and the SQLite query):
| Subject | Ping |
Ping, scope per request |
Behaviors | Behaviors, scope per request | SQLite query |
|---|---|---|---|---|---|
| Hand-written direct call | 2.20 ns → 3.48 ns · 32 B | 49.9 ns → 83.3 ns · 368 B | 117 ns → 139 ns · 520 B | 212 ns · 920 B → 324 ns · 968 B | 1,275 ns · 1,144 B → 1,300 ns · 1,128 B |
| Keryx, typed overload | 2.27 ns → 3.51 ns · 32 B | 29.9 ns → 54.8 ns · 192 B | 122 ns → 153 ns · 520 B | 268 ns → 399 ns · 1,048 B | 1,305 ns · 1,144 B → 1,310 ns · 1,128 B |
Keryx, IMediator |
5.77 ns → 4.92 ns · 32 B | 34.2 ns → 58.2 ns · 192 B | 126 ns → 156 ns · 520 B | 269 ns → 404 ns · 1,048 B | 1,271 ns · 1,144 B → 1,333 ns · 1,128 B |
Mediator 3.0.2 scoped, Mediator class |
30.6 ns · 96 B → 56.3 ns · 80 B | 91.4 ns · 472 B → 186 ns · 488 B | 195 ns · 776 B → 246 ns · 728 B | 380 ns · 1,648 B → 673 ns · 1,728 B | 1,319 ns · 1,208 B → 1,395 ns · 1,176 B |
Mediator 3.0.2 scoped, IMediator |
30.2 ns · 96 B → 59.7 ns · 80 B | 95.9 ns · 472 B → 193 ns · 488 B | 193 ns · 776 B → 260 ns · 728 B | 382 ns · 1,648 B → 683 ns · 1,728 B | 1,321 ns · 1,208 B → 1,435 ns · 1,176 B |
Mediator 3.0.2 singleton, Mediator class |
2.94 ns → 3.69 ns · 32 B | 24.9 ns → 39.2 ns · 160 B | n/a | n/a | 1,265 ns · 1,144 B → 1,353 ns · 1,128 B |
Mediator 3.0.2 singleton, IMediator |
7.70 ns → 6.30 ns · 32 B | 31.9 ns → 44.4 ns · 160 B | n/a | n/a | 1,293 ns · 1,144 B → 1,312 ns · 1,128 B |
MediatR 15.0.0, IMediator |
35.6 ns · 232 B → n/a | 73.9 ns · 432 B → n/a | 255 ns · 1,176 B → n/a | 324 ns · 1,608 B → n/a | 1,324 ns · 1,344 B → n/a |
Immediate.Handlers 4.4.0, Handler class |
11.2 ns → 18.8 ns · 32 B | 79.3 ns · 400 B → 138 ns · 432 B | 136 ns → 170 ns · 520 B | 297 ns · 1,400 B → 478 ns · 1,544 B | 1,298 ns · 1,144 B → 1,351 ns · 1,128 B |
ZeroAlloc.Mediator 7.0.1, static Mediator |
19.6 ns → 20.2 ns · 32 B | n/a | n/a | n/a | 1,298 ns · 1,168 B → 1,388 ns · 1,184 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
22.0 ns → 42.4 ns · 56 B | 50.0 ns · 208 B → 123 ns · 240 B | 181 ns · 544 B → 284 ns · 576 B | 250 ns · 928 B → 435 ns · 992 B | 1,279 ns · 1,168 B → 1,409 ns · 1,184 B |
Real-world publish per request scope:
| Subject | 1 handler | 5 handlers | 1 handler + behavior | 5 handlers + behavior |
|---|---|---|---|---|
| Hand-written direct call | 122 ns · 456 B → 226 ns · 528 B | 443 ns · 1,232 B → 792 ns · 1,496 B | 200 ns · 608 B → 327 ns · 688 B | 513 ns · 1,384 B → 893 ns · 1,656 B |
| Keryx, typed overload | 144 ns → 224 ns · 560 B | 316 ns → 424 ns · 816 B | 220 ns → 313 ns · 704 B | 392 ns → 518 ns · 960 B |
Keryx, IMediator |
149 ns → 232 ns · 560 B | 312 ns → 430 ns · 816 B | 225 ns → 323 ns · 704 B | 392 ns → 521 ns · 960 B |
Mediator 3.0.2 scoped, Mediator class |
239 ns · 888 B → 493 ns · 960 B | 675 ns · 2,104 B → 1,329 ns · 2,336 B | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
243 ns · 888 B → 500 ns · 960 B | 688 ns · 2,104 B → 1,347 ns · 2,336 B | n/a | n/a |
MediatR 15.0.0, IMediator |
238 ns · 1,248 B → n/a | 658 ns · 2,496 B → n/a | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator |
126 ns · 456 B → 262 ns · 528 B | 364 ns · 840 B → 788 ns · 1,072 B | n/a | n/a |
Real-world publish per request scope, 25, 50 and 100 handlers:
| Subject | 25 handlers | 50 handlers | 100 handlers | 25 handlers + behavior | 50 handlers + behavior | 100 handlers + behavior |
|---|---|---|---|---|---|---|
| Hand-written direct call | 1,981 ns · 5,792 B → 3,498 ns · 7,016 B | 4,124 ns · 12,360 B → 7,063 ns · 14,784 B | 8,586 ns · 26,280 B → 14.77 µs · 31,104 B | 2,078 ns · 5,952 B → 3,508 ns · 7,184 B | 4,220 ns · 12,520 B → 7,154 ns · 14,952 B | 8,745 ns · 26,448 B → 14.63 µs · 31,280 B |
| Keryx, typed overload | 1,136 ns → 1,400 ns · 2,112 B | 2,240 ns → 2,621 ns · 3,712 B | 4,615 ns → 5,304 ns · 6,912 B | 1,219 ns → 1,479 ns · 2,256 B | 2,329 ns → 2,767 ns · 3,856 B | 4,751 ns → 5,421 ns · 7,064 B |
Keryx, IMediator |
1,125 ns → 1,404 ns · 2,112 B | 2,222 ns → 2,621 ns · 3,712 B | 4,505 ns → 5,304 ns · 6,912 B | 1,209 ns → 1,570 ns · 2,256 B | 2,253 ns → 2,732 ns · 3,856 B | 4,655 ns → 5,343 ns · 7,064 B |
Mediator 3.0.2 scoped, Mediator class |
3,138 ns · 9,832 B → 5,793 ns · 10,865 B | 6,799 ns · 21,152 B → 12.00 µs · 23,186 B | 16.78 µs · 45,368 B → 27.60 µs · 49,405 B | n/a | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
3,067 ns · 9,832 B → 5,832 ns · 10,865 B | 6,816 ns · 21,152 B → 11.88 µs · 23,186 B | 17.11 µs · 45,368 B → 27.53 µs · 49,403 B | n/a | n/a | n/a |
MediatR 15.0.0, IMediator |
2,972 ns · 9,152 B → n/a | 6,244 ns · 17,480 B → n/a | 13.06 µs · 34,120 B → n/a | n/a | n/a | n/a |
ZeroAlloc.Mediator 7.0.1, IMediator |
1,687 ns · 2,760 B → 3,318 ns · 3,792 B | 3,322 ns · 5,160 B → 6,427 ns · 7,192 B | 6,956 ns · 9,960 B → 13.76 µs · 13,992 B | n/a | n/a | n/a |
Real-world publish to handlers that await the SQLite query:
| Subject | Sequential, 1 handler | Sequential, 5 handlers | Parallel, 1 handler | Parallel, 5 handlers |
|---|---|---|---|---|
| Hand-written direct call | 1,312 ns · 1,176 B → 1,406 ns · 1,160 B | 6,630 ns · 5,880 B → 6,909 ns · 5,800 B | 1,325 ns · 1,176 B → 1,401 ns · 1,160 B | 6,832 ns · 5,880 B → 6,885 ns · 5,800 B |
| Keryx, typed overload | 1,365 ns · 1,176 B → 1,407 ns · 1,160 B | 6,801 ns · 5,880 B → 7,015 ns · 5,800 B | 1,358 ns · 1,176 B → 1,393 ns · 1,160 B | 6,742 ns · 5,880 B → 6,970 ns · 5,800 B |
Keryx, IMediator |
1,342 ns · 1,176 B → 1,424 ns · 1,160 B | 6,620 ns · 5,880 B → 7,058 ns · 5,800 B | 1,355 ns · 1,176 B → 1,392 ns · 1,160 B | 6,692 ns · 5,880 B → 6,992 ns · 5,800 B |
Mediator 3.0.2 scoped, Mediator class |
1,355 ns · 1,176 B → 1,464 ns · 1,160 B | 6,770 ns · 5,880 B → 7,074 ns · 5,800 B | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
1,356 ns · 1,176 B → 1,473 ns · 1,160 B | 6,792 ns · 5,880 B → 7,228 ns · 5,800 B | n/a | n/a |
Mediator 3.0.2 singleton, Mediator class |
1,321 ns · 1,176 B → 1,406 ns · 1,160 B | 6,710 ns · 5,880 B → 7,166 ns · 5,800 B | 1,339 ns · 1,176 B → 1,420 ns · 1,160 B | 6,669 ns · 5,880 B → 6,964 ns · 5,800 B |
Mediator 3.0.2 singleton, IMediator |
1,349 ns · 1,176 B → 1,399 ns · 1,160 B | 6,680 ns · 5,880 B → 7,186 ns · 5,800 B | 1,334 ns · 1,176 B → 1,430 ns · 1,160 B | 6,778 ns · 5,880 B → 6,938 ns · 5,800 B |
MediatR 15.0.0, IMediator |
1,507 ns · 1,952 B → n/a | 7,129 ns · 7,648 B → n/a | 1,526 ns · 2,232 B → n/a | 7,398 ns · 8,032 B → n/a |
ZeroAlloc.Mediator 7.0.1, static Mediator |
1,358 ns · 1,208 B → 1,475 ns · 1,232 B | 6,851 ns · 6,040 B → 7,563 ns · 6,160 B | 1,364 ns · 1,208 B → 1,485 ns · 1,232 B | 6,895 ns · 6,040 B → 7,499 ns · 6,160 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
1,369 ns · 1,208 B → 1,521 ns · 1,232 B | 7,030 ns · 6,040 B → 7,550 ns · 6,160 B | 1,389 ns · 1,208 B → 1,491 ns · 1,232 B | 6,798 ns · 6,040 B → 7,490 ns · 6,160 B |
Real-world publish to 25, 50 and 100 handlers that await the SQLite query:
| Subject | Sequential, 25 handlers | Sequential, 50 handlers | Sequential, 100 handlers | Parallel, 25 handlers | Parallel, 50 handlers | Parallel, 100 handlers |
|---|---|---|---|---|---|---|
| Hand-written direct call | 34.46 µs · 29,400 B → 35.50 µs · 29,000 B | 66.96 µs · 58,800 B → 70.66 µs · 58,000 B | 136.6 µs · 117,600 B → 141.3 µs · 116,000 B | 33.77 µs · 29,400 B → 34.98 µs · 29,000 B | 67.40 µs · 58,800 B → 69.18 µs · 58,000 B | 135.4 µs · 117,600 B → 139.4 µs · 116,000 B |
| Keryx, typed overload | 33.93 µs · 29,400 B → 35.56 µs · 29,000 B | 68.83 µs · 58,800 B → 71.04 µs · 58,000 B | 139.8 µs · 117,600 B → 143.4 µs · 116,000 B | 34.22 µs · 29,400 B → 34.57 µs · 29,000 B | 68.71 µs · 58,800 B → 69.61 µs · 58,000 B | 140.8 µs · 117,600 B → 139.3 µs · 116,000 B |
Keryx, IMediator |
33.42 µs · 29,400 B → 35.49 µs · 29,000 B | 67.75 µs · 58,800 B → 71.98 µs · 58,000 B | 135.4 µs · 117,600 B → 143.5 µs · 116,000 B | 33.59 µs · 29,400 B → 35.13 µs · 29,000 B | 66.64 µs · 58,800 B → 70.41 µs · 58,000 B | 134.5 µs · 117,600 B → 141.6 µs · 116,000 B |
Mediator 3.0.2 scoped, Mediator class |
33.86 µs · 29,400 B → 35.91 µs · 29,000 B | 67.04 µs · 58,800 B → 73.72 µs · 58,000 B | 136.0 µs · 117,600 B → 148.5 µs · 116,000 B | n/a | n/a | n/a |
Mediator 3.0.2 scoped, IMediator |
34.05 µs · 29,400 B → 36.29 µs · 29,000 B | 68.17 µs · 58,800 B → 71.56 µs · 58,000 B | 136.7 µs · 117,600 B → 147.0 µs · 116,000 B | n/a | n/a | n/a |
Mediator 3.0.2 singleton, Mediator class |
34.75 µs · 29,400 B → 35.76 µs · 29,000 B | 73.33 µs · 58,800 B → 71.51 µs · 58,000 B | 134.6 µs · 117,600 B → 145.5 µs · 116,000 B | 33.47 µs · 29,400 B → 35.35 µs · 29,000 B | 67.24 µs · 58,800 B → 70.90 µs · 58,000 B | 134.5 µs · 117,600 B → 146.4 µs · 116,000 B |
Mediator 3.0.2 singleton, IMediator |
34.10 µs · 29,400 B → 35.36 µs · 29,000 B | 68.13 µs · 58,800 B → 72.63 µs · 58,000 B | 134.4 µs · 117,600 B → 144.2 µs · 116,000 B | 34.53 µs · 29,400 B → 35.11 µs · 29,000 B | 68.40 µs · 58,800 B → 71.33 µs · 58,000 B | 135.1 µs · 117,600 B → 144.9 µs · 116,000 B |
MediatR 15.0.0, IMediator |
35.94 µs · 36,544 B → n/a | 71.93 µs · 72,672 B → n/a | 143.7 µs · 144,912 B → n/a | 36.14 µs · 37,088 B → n/a | 72.99 µs · 73,416 B → n/a | 148.1 µs · 146,056 B → n/a |
ZeroAlloc.Mediator 7.0.1, static Mediator |
34.29 µs · 30,200 B → 38.28 µs · 30,800 B | 69.74 µs · 60,400 B → 76.36 µs · 61,600 B | 140.3 µs · 120,800 B → 153.9 µs · 123,200 B | 34.49 µs · 30,200 B → 37.97 µs · 30,800 B | 69.66 µs · 60,400 B → 74.07 µs · 61,600 B | 139.9 µs · 120,800 B → 156.1 µs · 123,200 B |
ZeroAlloc.Mediator 7.0.1, IMediator |
34.67 µs · 30,200 B → 38.19 µs · 30,800 B | 67.94 µs · 60,400 B → 75.50 µs · 61,600 B | 136.7 µs · 120,800 B → 151.1 µs · 123,200 B | 34.37 µs · 30,200 B → 37.80 µs · 30,800 B | 68.10 µs · 60,400 B → 72.77 µs · 61,600 B | 141.7 µs · 120,800 B → 150.5 µs · 123,200 B |
- Without behaviors, Keryx's typed overload stays at the direct call's floor: 0.56 ns against 0.49 ns at depth 0, 0.72 ns against
0.67 ns for a publish to 5 handlers, and 3.51 ns against 3.48 ns for the real-world
Ping. One and three behaviors add nothing measurable (0.56 ns); at depth 8 ILC no longer inlines the whole pipeline into the benchmark, and it measures 1.45 ns, still 0 B. Mediator singleton measures 2.01 to 20.6 ns over the same depths (class andIMediator), the other libraries 18.3 to 160 ns. - Outside the yielding scenarios, Keryx allocates exactly what it allocates under the JIT, the behavior and fan-out rows included, except in the SQLite and async-handler rows (16 B less per query), where the direct call's allocations change by the same amount.
- Per request scope, Keryx's typed overload measures 54.8 ns for
Ping(the direct call 83.3 ns, ZeroAlloc.Mediator 123 ns, Mediator singleton 39.2 ns), 399 ns for the behaviors (the direct call 324 ns, ZeroAlloc.Mediator 435 ns, the other libraries 478 to 683 ns), and 224 ns and 424 ns for a publish to 1 and 5 handlers (the direct call 226 ns and 792 ns, ZeroAlloc.Mediator 262 ns and 788 ns). Decision 37's run, before the scope-cost rework, measured 84.3 ns, 445 ns, 252 ns and 876 ns. ItsIMediatorrows allocate what the typed rows allocate and measure 58.2, 404, 232 and 430 ns (110, 471, 281 and 920 ns in decision 37's run). - With 25, 50 and 100 handlers per request scope Keryx measures 1,400, 2,621 and 5,304 ns typed, against ZeroAlloc.Mediator's 3,318 ns, 6,427 ns and 13.76 µs and the direct call's 3,498 ns, 7,063 ns and 14.77 µs; Mediator scoped measures 5,793 ns to 27.60 µs. The synchronous publish to 100 handlers measures 281 ns for Keryx's typed overload, 162 ns for the direct call, 341 ns for ZeroAlloc.Mediator's static path and 2,212 to 2,263 ns for Mediator (340 to 381 ns under the JIT).
- In the
Sendyield table every subject measured 835 to 1,015 ns under NativeAOT. Keryx allocates 113 B, as the direct call does (113 to 114 B). Mediator scoped allocates less than under the JIT (161 to 162, 240, 400 and 800 B at depths 0, 1, 3 and 8, against 176 to 177, 272 to 273, 464 and 944 B), as in its synchronous rows; Mediator singleton, Immediate.Handlers and ZeroAlloc.Mediator stay within 5 B of their JIT allocations. With anIRequesthandler (810 to 941 ns) Keryx allocates 96 B, as the direct call does (96 to 97 B). - Streams cost 42 to 68% more for every subject (the direct call 630 ns under the JIT, 913 ns under NativeAOT); Keryx's allocations do not change.
- The real-world behavior rows from the long-lived scope: Keryx's typed overload measures 153 ns (the direct call 139 ns); the other libraries 170 to 284 ns.
Run them yourself (the third run, one class at a time, took 51 minutes of runs under the JIT, 352 benchmarks, and 70 minutes under
NativeAOT, 317 benchmarks, building a NativeAOT executable per class; decision 32's whole-suite runs, before the fan-out classes, took
25 and 22 minutes; --verify checks
that every library really runs each scenario's handlers and behaviors, with a call counter that the benchmark runs compile out, calls
included: the runner sets the MSBuild property KeryxBenchmarksProbe=false in its environment before BenchmarkDotNet builds):
cd test/Keryx.Benchmarks
dotnet run -c Release -f net10.0 -- --verify
dotnet run -c Release -f net10.0 -- --filter '*Comparison*' --launchCount 1 --warmupCount 5 --iterationCount 15 --iterationTime 200Under NativeAOT (the ILCompiler needs the platform's native toolchain: Xcode command line tools on macOS, clang and zlib1g-dev on
Ubuntu), publish the suite with NativeAOT and run --verify in that binary, then run it with --runtimes nativeaot10.0 (MediatR's
benchmarks and the JIT-only pipeline prototype are left out of the NativeAOT job):
dotnet publish -c Release -f net10.0 --use-current-runtime -p:KeryxBenchmarksNativeAot=true -o aot
aot/Keryx.Benchmarks --verify
dotnet run -c Release -f net10.0 -- --filter '*Comparison*' --runtimes nativeaot10.0 --launchCount 1 --warmupCount 5 --iterationCount 15 --iterationTime 200That run measures every benchmark and needs no separate step: the runner itself gives the direct call's Publish to 1, 25, 50 and 100
handlers fixed invocation counts under NativeAOT (see above; Comparison/FixedInvocationCount.cs), and leaves every other benchmark,
every JIT job, the Dry job and an explicit --invocationCount as they are.
Run it on its own: --runtimes net10.0 nativeaot10.0 runs both in one summary, but BenchmarkDotNet then takes the JIT job's Baseline
as the only baseline, so the NativeAOT rows have no ratios (?).
The Keryx subject has fewer than 32 request, stream request and notification types, so its Keryx_Generic rows measure the linear type
compares. With the environment variable KeryxDispatchPadding=true (an MSBuild property, so BenchmarkDotNet's own build sees it too),
it compiles 32 more of each (Padding.cs), and the same rows measure the FrozenDictionary lookup and jump table above the threshold:
KeryxDispatchPadding=true dotnet run -c Release -f net10.0 -- --filter '*Comparison*Keryx_Generic*'The Keryx subject has 10 pipelines with a context, so its scope state is 96 B. With KeryxContextPadding=true it compiles 40 more, each
with a handler that injects one service (ContextPadding.cs; 50 in all, every kind still below 32 types, so the dispatch is unchanged),
and a scope that uses a context resolves a 416 B state: the scope-per-request Keryx rows allocate 320 B more (for example 1,368 B for
RealWorldBehaviorsScopePerRequest). The long-lived typed rows do not change; the generic ones compare the runtime type with
14 more request types (RealWorldPing 7.95 ns through IMediator). Owner decision 49 (open-questions-v1 OQ-78) measured bounded
layouts on this host against the per-field one, three to six interleaved rounds on the machine above. A read of slot 0 only made every
other pipeline's long-lived call 0.6 to 1.2 ns slower (typed Publish of a pipeline with a context 0.75 to 1.53 ns). Pages of 16 fields
allocated on first use left the typed calls as they were and allocated 224 B less in a scope whose contexts share a page (560 B against
784 B), up to 64 B more in one that touches every page, but made the long-lived generic Send 0.35 to 0.5 ns slower (4.21 to 4.56 ns).
So the state keeps one field per pipeline:
KeryxContextPadding=true dotnet run -c Release -f net10.0 -- --filter '*RealWorldBehaviors*'--filter '*PipelinePrototype*' runs the hand-written struct pipeline the generated code follows (static behavior methods, struct
next links) against nested direct calls at depths 1, 3 and 8: 0 B at every depth, and 0.66x the nested calls' time at depth 3 on the
machine above. On macOS, --prototype-disasm runs the same pipelines to Tier 1 for a DOTNET_JitDisasm listing (see Program.cs).
CI builds the suite, runs --verify, runs every benchmark (the real-world scenarios included) once with --job Dry, does the same under
NativeAOT on Linux (publish with NativeAOT and --verify in that binary, then --job Dry --runtimes nativeaot10.0, owner decision 31),
and runs the pipeline prototype on Linux with BenchmarkDotNet's DisassemblyDiagnoser, uploading the disassembly as a build artifact.
Numbers from shared runners are never published.
mise run buildor, without mise:
dotnet build Keryx.slnx
dotnet test --solution Keryx.slnxWarnings are errors everywhere. The allocation tests measure with GC.GetAllocatedBytesForCurrentThread inside compiled test hosts
and run alone. The ones that measure what a scope costs run windows of 1,000 scopes until two consecutive windows allocate the same, so
a first window that pays the container's one-time cost of a new call site is not the one compared, and fail with the last two windows'
bytes if 100 windows never agree (open-questions-v1 OQ-80). A test that compares scenarios shows each compared scenario's windows in its
failure message, for example windows of 1,000 scopes: publish: two mediators: 480,000 B, 480,000 B; publish: KeryxMediator: 448,040 B, 448,000 B, 448,000 B (open-questions-v1 OQ-85).