Akka.Hosting
1.6.0-beta8
Prefix Reserved
dotnet add package Akka.Hosting --version 1.6.0-beta8
NuGet\Install-Package Akka.Hosting -Version 1.6.0-beta8
<PackageReference Include="Akka.Hosting" Version="1.6.0-beta8" />
<PackageVersion Include="Akka.Hosting" Version="1.6.0-beta8" />
<PackageReference Include="Akka.Hosting" />
paket add Akka.Hosting --version 1.6.0-beta8
#r "nuget: Akka.Hosting, 1.6.0-beta8"
#:package Akka.Hosting@1.6.0-beta8
#addin nuget:?package=Akka.Hosting&version=1.6.0-beta8&prerelease
#tool nuget:?package=Akka.Hosting&version=1.6.0-beta8&prerelease
<a id="akkahosting"></a>
Akka.Hosting
HOCON-less configuration, application lifecycle management, ActorSystem startup, and actor instantiation for Akka.NET.
See the "Introduction to Akka.Hosting - HOCON-less, "Pit of Success" Akka.NET Runtime and Configuration" video for a walkthrough of the library and how it can save you a tremendous amount of time and trouble.
Table Of Content
- Supported Packages
- Summary
- Dependency Injection Outside and Inside Akka.NET
- Microsoft.Extensions.Configuration Integration
- Microsoft.Extensions.Logging Integration
- OpenTelemetry Trace Correlation
- Microsoft.Extensions.Diagnostics.HealthChecks Integration
- Dependency Injected Health Checks
- Built-in HealthChecks <a id="supported-packages"></a>
Supported Packages
<a id="akkanet-core-packages"></a>
Akka.NET Core Packages
Akka.Hosting- the coreAkka.Hostingpackage, needed for everythingAkka.Remote.Hosting- enables Akka.Remote configuration. Documentation can be read hereAkka.Cluster.Hosting- used for Akka.Cluster, Akka.Cluster.Sharding, and Akka.Cluster.Tools. Documentation can be read hereAkka.Persistence.Hosting- used for adding persistence functionality to perform local database-less testing. Documentation can be read here
<a id="akka-persistence-plugins"></a>
Akka Persistence Plugins
Akka.Persistence.SqlServer.Hosting- used for Akka.Persistence.SqlServer support. Documentation can be read hereAkka.Persistence.PostgreSql.Hosting- used for Akka.Persistence.PostgreSql support. Documentation can be read hereAkka.Persistence.Azure.Hosting- used for Akka.Persistence.Azure support. Documentation can be read here
<a id="akkamanagement-plugins"></a>
Akka.Management Plugins
Useful tools for managing Akka.NET clusters running inside containerized or cloud based environment. Akka.Hosting is embedded in each of its packages.
<a id="akkamanagement-core-package"></a>
Akka.Management Core Package
Akka.Management- core module of the management utilities which provides a central HTTP endpoint for Akka management extensions. Documentation can be read hereAkka.Management.Cluster.Bootstrap- used to bootstrap a cluster formation inside dynamic deployment environments. Documentation can be read hereNOTE
As of version 1.0.0, cluster bootstrap came bundled inside the core
Akka.ManagementNuGet package and are part of the default HTTP endpoint forAkka.Management. AllAkka.Management.Cluster.BootstrapNuGet package versions below 1.0.0 should now be considered deprecated.
<a id="akkadiscovery-plugins"></a>
Akka.Discovery Plugins
Akka.Discovery.AwsApi- provides dynamic node discovery service for AWS EC2 environment. Documentation can be read hereAkka.Discovery.Azure- provides a dynamic node discovery service for Azure PaaS ecosystem. Documentation can be read hereAkka.Discovery.KubernetesApi- provides a dynamic node discovery service for Kubernetes clusters. Documentation can be read here
<a id="akkacoordination-plugins"></a>
Akka.Coordination Plugins
Akka.Coordination.KubernetesApi- provides a lease-based distributed lock mechanism backed by Kubernetes CRD for Akka.NET Split Brain Resolver, Akka.Cluster.Sharding, and Akka.Cluster.Singleton. Documentation can be read hereAkka.Coordination.Azure- provides a lease-based distributed lock mechanism backed by Microsoft Azure Blob Storage for Akka.NET Split Brain Resolver, Akka.Cluster.Sharding, and Akka.Cluster.Singleton. Documentation can be read here
<a id="summary"></a>
Summary
We want to make Akka.NET something that can be instantiated more typically per the patterns often used with the Microsoft.Extensions.Hosting APIs that are common throughout .NET.
using Akka.Hosting;
using Akka.Actor;
using Akka.Actor.Dsl;
using Akka.Cluster.Hosting;
using Akka.Remote.Hosting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.WithRemoting("localhost", 8110)
.WithClustering(new ClusterOptions(){ Roles = new[]{ "myRole" },
SeedNodes = new[]{ Address.Parse("akka.tcp://MyActorSystem@localhost:8110")}})
.WithActors((system, registry) =>
{
var echo = system.ActorOf(act =>
{
act.ReceiveAny((o, context) =>
{
context.Sender.Tell($"{context.Self} rcv {o}");
});
}, "echo");
registry.TryRegister<Echo>(echo); // register for DI
});
});
var app = builder.Build();
app.MapGet("/", async (context) =>
{
var echo = context.RequestServices.GetRequiredService<ActorRegistry>().Get<Echo>();
var body = await echo.Ask<string>(context.TraceIdentifier, context.RequestAborted).ConfigureAwait(false);
await context.Response.WriteAsync(body);
});
app.Run();
No HOCON. Automatically runs all Akka.NET application lifecycle best practices behind the scene. Automatically binds the ActorSystem and the ActorRegistry, another new 1.5 feature, to the IServiceCollection so they can be safely consumed via both actors and non-Akka.NET parts of users' .NET applications.
This should be open to extension in other child plugins, such as Akka.Persistence.SqlServer:
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.WithRemoting("localhost", 8110)
.WithClustering(new ClusterOptions()
{
Roles = new[] { "myRole" },
SeedNodes = new[] { Address.Parse("akka.tcp://MyActorSystem@localhost:8110") }
})
.WithSqlServerPersistence(builder.Configuration.GetConnectionString("sqlServerLocal"))
.WithShardRegion<UserActionsEntity>("userActions", s => UserActionsEntity.Props(s),
new UserMessageExtractor(),
new ShardOptions(){ StateStoreMode = StateStoreMode.DData, Role = "myRole"})
.WithActors((system, registry) =>
{
var userActionsShard = registry.Get<UserActionsEntity>();
var indexer = system.ActorOf(Props.Create(() => new Indexer(userActionsShard)), "index");
registry.TryRegister<Index>(indexer); // register for DI
});
})
<a id="dependency-injection-outside-and-inside-akkanet"></a>
Dependency Injection Outside and Inside Akka.NET
One of the other design goals of Akka.Hosting is to make the dependency injection experience with Akka.NET as seamless as any other .NET technology. We accomplish this through two new APIs:
- The
ActorRegistry, a DI container that is designed to be populated withTypes for keys andIActorRefs for values, just like theIServiceCollectiondoes for ASP.NET services. - The
IRequiredActor<TKey>- you can place this type the constructor of any dependency injected resource and it will automatically resolve a reference to the actor stored inside theActorRegistrywithTKey. This is how we inject actors into ASP.NET, SignalR, gRPC, and other Akka.NET actors!
N.B. The
ActorRegistryand theActorSystemare automatically registered with theIServiceCollection/IServiceProviderassociated with your application.
<a id="registering-actors-with-the-actorregistry"></a>
Registering Actors with the ActorRegistry
As part of Akka.Hosting, we need to provide a means of making it easy to pass around top-level IActorRefs via dependency injection both within the ActorSystem and outside of it.
The ActorRegistry will fulfill this role through a set of generic, typed methods that make storage and retrieval of long-lived IActorRefs easy and coherent:
- Fetch ActorRegistry from ActorSystem manually
var registry = ActorRegistry.For(myActorSystem);
- Provided by the actor builder
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.WithActors((system, actorRegistry) =>
{
var actor = system.ActorOf(Props.Create(() => new MyActor));
actorRegistry.TryRegister<MyActor>(actor); // register actor for DI
});
});
- Obtaining the
IActorRefmanually
var registry = ActorRegistry.For(myActorSystem);
registry.Get<Index>(); // use in DI
<a id="injecting-actors-with-irequiredactortkey"></a>
Injecting Actors with IRequiredActor<TKey>
Suppose we have a class that depends on having a reference to a top-level actor, a router, a ShardRegion, or perhaps a ClusterSingleton (common types of actors that often interface with non-Akka.NET parts of a .NET application):
public sealed class MyConsumer
{
private readonly IActorRef _actor;
public MyConsumer(IRequiredActor<MyActorType> actor)
{
_actor = actor.ActorRef;
}
public async Task<string> Say(string word)
{
return await _actor.Ask<string>(word, TimeSpan.FromSeconds(3));
}
}
The IRequiredActor<MyActorType> will cause the Microsoft.Extensions.DependencyInjection mechanism to resolve MyActorType from the ActorRegistry and inject it into the IRequired<Actor<MyActorType> instance passed into MyConsumer.
The IRequiredActor<TActor> exposes a single property:
public interface IRequiredActor<TActor>
{
/// <summary>
/// The underlying actor resolved via <see cref="ActorRegistry"/> using the given <see cref="TActor"/> key.
/// </summary>
IActorRef ActorRef { get; }
}
By default, you can automatically resolve any actors registered with the ActorRegistry without having to declare anything special on your IServiceCollection:
using var host = new HostBuilder()
.ConfigureServices(services =>
{
services.AddAkka("MySys", (builder, provider) =>
{
builder.WithActors((system, registry) =>
{
var actor = system.ActorOf(Props.Create(() => new MyActorType()), "myactor");
registry.Register<MyActorType>(actor);
});
});
services.AddScoped<MyConsumer>();
})
.Build();
await host.StartAsync();
Adding your actor and your type key into the ActorRegistry is sufficient - no additional DI registration is required to access the IRequiredActor<TActor> for that type.
<a id="resolving-irequiredactortkey-within-akkanet"></a>
Resolving IRequiredActor<TKey> within Akka.NET
Akka.NET does not use dependency injection to start actors by default primarily because actor lifetime is unbounded by default - this means reasoning about the scope of injected dependencies isn't trivial. ASP.NET, by contrast, is trivial: all HTTP requests are request-scoped and all web socket connections are connection-scoped - these are objects have bounded and typically short lifetimes.
Therefore, users have to explicitly signal when they want to use Microsoft.Extensions.DependencyInjection via the IDependencyResolver interface in Akka.DependencyInjection - which is easy to do in most of the Akka.Hosting APIs for starting actors:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IReplyGenerator, DefaultReplyGenerator>();
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.WithRemoting(hostname: "localhost", port: 8110)
.WithClustering(new ClusterOptions{SeedNodes = new []{ "akka.tcp://MyActorSystem@localhost:8110", }})
.WithShardRegion<Echo>(
typeName: "myRegion",
entityPropsFactory: (_, _, resolver) =>
{
// uses DI to inject `IReplyGenerator` into EchoActor
return s => resolver.Props<EchoActor>(s);
},
extractEntityId: ExtractEntityId,
extractShardId: ExtractShardId,
shardOptions: new ShardOptions());
});
The dependencyResolver.Props<MySingletonDiActor>() call will leverage the ActorSystem's built-in IDependencyResolver to instantiate the MySingletonDiActor and inject it with all of the necessary dependencies, including IRequiredActor<TKey>.
<a id="microsoftextensionsconfiguration-integration"></a>
Microsoft.Extensions.Configuration Integration
<a id="iconfiguration-to-hocon-adapter"></a>
IConfiguration To HOCON Adapter
The AddHocon extension method can convert Microsoft.Extensions.Configuration IConfiguration into HOCON Config instance and adds it to the ActorSystem being configured.
- Unlike
IConfiguration, all HOCON key names are case sensitive. - Unless enclosed inside double quotes, all "." (period) in the
IConfigurationkey will be treated as a HOCON object key separator IConfigurationdoes not support object composition, if you declare the same key multiple times inside multiple configuration providers (JSON/environment variables/etc), only the last one declared will take effect.- For environment variable configuration provider:
- "__" (double underline) will be converted to "." (period).
- "_" (single underline) will be converted to "-" (dash).
- If all keys are composed of integer parseable keys, the whole object is treated as an array
Example:
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"akka": {
"cluster": {
"roles": [ "front-end", "back-end" ],
"min-nr-of-members": 3,
"log-info": true
}
}
}
Environment variables:
AKKA__ACTOR__TELEMETRY__ENABLE=true
AKKA__CLUSTER__SEED_NODES__0=akka.tcp//mySystem@localhost:4055
AKKA__CLUSTER__SEED_NODES__1=akka.tcp//mySystem@localhost:4056
AKKA__CLUSTER__SEED_NODE_TIMEOUT=00:00:05
Note the integer parseable key inside the seed-nodes configuration, seed-nodes will be parsed as an array. These environment variables will be parsed as HOCON settings:
akka {
actor {
telemetry.enabled: on
}
cluster {
seed-nodes: [
"akka.tcp//mySystem@localhost:4055",
"akka.tcp//mySystem@localhost:4056"
]
seed-node-timeout: 5s
}
}
Example code:
/*
Both appsettings.json and environment variables are combined
into HOCON configuration:
akka {
actor.telemetry.enabled: on
cluster {
roles: [ "front-end", "back-end" ]
seed-nodes: [
"akka.tcp//mySystem@localhost:4055",
"akka.tcp//mySystem@localhost:4056"
]
min-nr-of-members: 3
seed-node-timeout: 5s
log-info: true
}
}
*/
var host = new HostBuilder()
.ConfigureHostConfiguration(builder =>
{
// Setup IConfiguration to load from appsettings.json and
// environment variables
builder
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
})
.ConfigureServices((context, services) =>
{
services.AddAkka("mySystem", (builder, provider) =>
{
// convert IConfiguration to HOCON
var akkaConfig = context.Configuration.GetSection("akka");
builder.AddHocon(akkaConfig, HoconAddMode.Prepend);
});
});
Special Characters And Case Sensitivity
This advanced usage of the IConfiguration adapter is solely used for edge cases where HOCON key capitalization needs to be preserved, such as declaring serialization binding. Note that when you're using this feature, none of the keys are normalized, you will have to write all of your keys in a HOCON compatible way.
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"akka": {
"\"Key.With.Dots\"": "Key Value",
"cluster": {
"roles": [ "front-end", "back-end" ],
"min-nr-of-members": 3,
"log-info": true
}
}
}
Note that "Key.With.Dots" needs to be inside escaped double quotes, this is a HOCON requirement that preserves the "." (period) inside HOCON property names.
Environment variables:
PS C:/> [Environment]::SetEnvironmentVariable('akka__actor__telemetry__enabled', 'true')
PS C:/> [Environment]::SetEnvironmentVariable('akka__actor__serialization_bindings__"System.Object"', 'hyperion')
PS C:/> [Environment]::SetEnvironmentVariable('akka__cluster__seed_nodes__0', 'akka.tcp//mySystem@localhost:4055')
PS C:/> [Environment]::SetEnvironmentVariable('akka__cluster__seed_nodes__1', 'akka.tcp//mySystem@localhost:4056')
PS C:/> [Environment]::SetEnvironmentVariable('akka__cluster__seed_node_timeout', '00:00:05')
Note that:
- All of the environment variable names are in lower case, except "System.Object" where it needs to preserve name capitalization.
- To set serialization binding via environment variable, you have to use "." (period) instead of "__" (double underscore), this might be problematic for some shell scripts and there is no way of getting around this.
Example code:
/*
Both appsettings.json and environment variables are combined
into HOCON configuration:
akka {
"Key.With.Dots": Key Value
actor {
telemetry.enabled: on
serialization-bindings {
"System.Object" = hyperion
}
}
cluster {
roles: [ "front-end", "back-end" ]
seed-nodes: [
"akka.tcp//mySystem@localhost:4055",
"akka.tcp//mySystem@localhost:4056"
]
min-nr-of-members: 3
seed-node-timeout: 5s
log-info: true
}
}
*/
var host = new HostBuilder()
.ConfigureHostConfiguration(builder =>
{
// Setup IConfiguration to load from appsettings.json and
// environment variables
builder
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
})
.ConfigureServices((context, services) =>
{
services.AddAkka("mySystem", (builder, provider) =>
{
// convert IConfiguration to HOCON
var akkaConfig = context.Configuration.GetSection("akka");
// Note the last method argument is set to false
builder.AddHocon(akkaConfig, HoconAddMode.Prepend, false);
});
});
<a id="microsoftextensionslogging-integration"></a>
Microsoft.Extensions.Logging Integration
<a id="logger-configuration-support"></a>
Logger Configuration Support
You can use AkkaConfigurationBuilder extension method called ConfigureLoggers(Action<LoggerConfigBuilder>) to configure how Akka.NET logger behave.
Example:
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.ConfigureLoggers(setup =>
{
// Example: This sets the minimum log level
setup.LogLevel = LogLevel.DebugLevel;
// Example: Clear all loggers
setup.ClearLoggers();
// Example: Add the default logger
// NOTE: You can also use setup.AddLogger<DefaultLogger>();
setup.AddDefaultLogger();
// Example: Add the ILoggerFactory logger
// NOTE:
// - You can also use setup.AddLogger<LoggerFactoryLogger>();
// - To use a specific ILoggerFactory instance, you can use setup.AddLoggerFactory(myILoggerFactory);
setup.AddLoggerFactory();
// Example: Adding a serilog logger
setup.AddLogger<SerilogLogger>();
})
.WithActors((system, registry) =>
{
var echo = system.ActorOf(act =>
{
act.ReceiveAny((o, context) =>
{
Logging.GetLogger(context.System, "echo").Info($"Actor received {o}");
context.Sender.Tell($"{context.Self} rcv {o}");
});
}, "echo");
registry.TryRegister<Echo>(echo); // register for DI
});
});
A complete code sample can be viewed here.
Exposed properties are:
LogLevel: Configure the Akka.NET minimum log level filter, defaults toInfoLevelLogConfigOnStart: When set to true, Akka.NET will log the complete HOCON settings it is using at start up, this can then be used for debugging purposes.
Currently supported logger methods:
ClearLoggers(): Clear all registered logger types.AddLogger<TLogger>(): Add a logger type by providing its class type.AddDefaultLogger(): Add the default Akka.NET console logger.AddLoggerFactory(): Add the newILoggerFactorylogger.
<a id="microsoftextensionsloggingiloggerfactory-logging-support"></a>
Microsoft.Extensions.Logging.ILoggerFactory Logging Support
You can now use ILoggerFactory from Microsoft.Extensions.Logging as one of the sinks for Akka.NET logger. This logger will use the ILoggerFactory service set up inside the dependency injection ServiceProvider as its sink.
<a id="serilog-support"></a>
Serilog Message Formatting Support
If you're interested in using Akka.Logger.Serilog, you can set Akka.NET's default logger and log message formatter to allow for Serilog's semantic logging to be enabled by default:
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.ConfigureLoggers(setup =>
{
// Example: This sets the minimum log level
setup.LogLevel = LogLevel.DebugLevel;
// Example: Clear all loggers
setup.ClearLoggers();
// Add Serilog
setup.AddLogger<SerilogLogger>();
// use the default SerilogFormatter everywhere
setup.WithDefaultLogMessageFormatter<SerilogLogMessageFormatter>();
})
.WithActors((system, registry) =>
{
var echo = system.ActorOf(act =>
{
act.ReceiveAny((o, context) =>
{
Logging.GetLogger(context.System, "echo").Info($"Actor received {o}");
context.Sender.Tell($"{context.Self} rcv {o}");
});
}, "echo");
registry.TryRegister<Echo>(echo); // register for DI
});
});
This will eliminate the need to have to do Context.GetLogger<SerilogLoggingAdapter>() everywhere you want to use it.
<a id="microsoftextensionslogging-log-event-filtering"></a>
Microsoft.Extensions.Logging Log Event Filtering
There will be two log event filters acting on the final log input, the Akka.NET akka.loglevel setting and the Microsoft.Extensions.Logging settings, make sure that both are set correctly or some log messages will be missing.
To set up the Microsoft.Extensions.Logging log filtering, you will need to edit the appsettings.json file. Note that we also set the Akka namespace to be filtered at debug level in the example below.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Akka": "Debug"
}
}
}
<a id="opentelemetry-trace-correlation"></a>
OpenTelemetry Trace Correlation
Akka.NET processes log events asynchronously, which means Activity.Current does not flow across actor mailbox boundaries. To preserve trace correlation, Akka.Hosting captures the ActivityContext at log creation time and includes it in the log state. The AkkaTraceContextProcessor then applies that context to OpenTelemetry LogRecords so exporters can correlate logs with traces.
Minimal setup:
using Akka.Hosting;
using Akka.Hosting.Logging;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;
builder.Logging.AddOpenTelemetry(options =>
{
options.SetResourceBuilder(ResourceBuilder.CreateDefault()
.AddService("my-service"));
// Register before exporters
options.AddAkkaTraceCorrelation();
// Add OTLP exporter if you have not configured it elsewhere.
// Your mileage may vary; use the OpenTelemetry configuration that fits your app.
options.AddOtlpExporter();
});
builder.Services.AddAkka("MySystem", configBuilder =>
{
configBuilder.ConfigureLoggers(setup =>
{
setup.ClearLoggers();
setup.AddLoggerFactory();
});
});
See the demo in src/Examples/Akka.Hosting.OpenTelemetry.AppHost and src/Examples/Akka.Hosting.OpenTelemetry.Demo for a working Aspire setup.
<a id="filtering-logs"></a>
Filtering Logs In Akka.NET
In Akka.NET 1.5.21, we introduced log filtering for log messages based on the LogSource or the content of a log message. Depending on your coding style, you can use this feature in Akka.Hosting in several ways.
Using The
LoggerConfigBuilder.WithLogFilter()method.The
LoggerConfigBuilder.WithLogFilter()method lets you set up theLogFilterBuilderbuilder.Services.AddAkka("MyActorSystem", configurationBuilder => { configurationBuilder .ConfigureLoggers(loggerConfigBuilder => { loggerConfigBuilder.WithLogFilter(filterBuilder => { filterBuilder.ExcludeMessageContaining("Test"); }); }); });Setting the
loggerConfigBuilder.LogFilterBuilderproperty directly.builder.Services.AddAkka("MyActorSystem", configurationBuilder => { configurationBuilder .ConfigureLoggers(loggerConfigBuilder => { loggerConfigBuilder.LogFilterBuilder = new LogFilterBuilder(); loggerConfigBuilder.LogFilterBuilder.ExcludeMessageContaining("Test"); }); });
<a id="healthchecks"></a>
Microsoft.Extensions.Diagnostics.HealthChecks Integration
We've recently deprecated Akka.HealthChecks in favor of a simpler, more configurable solution that is built directly into Akka.Hosting: IAkkaHealthCheck and WithAkkaHealthCheck:
builder
.WithActorSystemLivenessCheck() // have to opt-in to the built-in health check
.WithHealthCheck("FooActor alive", async (system, registry, cancellationToken) =>
{
/*
* N.B. CancellationToken is set by the call to MSFT.EXT.DIAGNOSTICS.HEALTHCHECK,
* so that value could be "infinite" by default.
*
* Therefore, it might be a really, really good idea to guard this with a non-infinite
* timeout via a LinkedCancellationToken here.
*/
try
{
var fooActor = await registry.GetAsync<FooActor>(cancellationToken);
try
{
var r = await fooActor.Ask<ActorIdentity>(new Identify("foo"), cancellationToken: cancellationToken);
if (r.Subject.IsNobody())
return HealthCheckResult.Unhealthy("FooActor was alive but is now dead");
}
catch (Exception e)
{
return HealthCheckResult.Degraded("FooActor found but non-responsive", e);
}
}
catch (Exception e2)
{
return HealthCheckResult.Unhealthy("FooActor not found in registry", e2);
}
return HealthCheckResult.Healthy("fooActor found and responsive");
});
These health checks and any other you register using one of the WithHealthCheck overloads on the AkkaConfigurationBuilder will automatically be registered with the Microsoft.Extensions.Diagnostics.HealthCheckService and will be called just like any other ASP.NET Core, Entity Framework, etc health check.
<a id="healthcheck-di"></a>
Dependency Injected Health Checks
As of version 1.5.51, Akka.Hosting supports dependency injection for health checks. You can create custom health check classes that implement IAkkaHealthCheck and have dependencies injected from the DI container:
// Define a custom health check with DI support
public class MyHealthCheckWithDependencies : IAkkaHealthCheck
{
private readonly ILogger<MyHealthCheckWithDependencies> _logger;
private readonly IMyService _myService;
public MyHealthCheckWithDependencies(
ILogger<MyHealthCheckWithDependencies> logger,
IMyService myService)
{
_logger = logger;
_myService = myService;
}
public async Task<HealthCheckResult> CheckHealthAsync(
AkkaHealthCheckContext context,
CancellationToken cancellationToken = default)
{
try
{
_logger.LogInformation("Running health check with DI");
var isHealthy = await _myService.CheckServiceHealthAsync(cancellationToken);
return isHealthy
? HealthCheckResult.Healthy("Service is healthy")
: HealthCheckResult.Unhealthy("Service is not healthy");
}
catch (Exception ex)
{
_logger.LogError(ex, "Health check failed");
return HealthCheckResult.Unhealthy($"Health check failed: {ex.Message}");
}
}
}
// Register the health check using the generic WithHealthCheck<T>() method
builder
.WithActorSystemLivenessCheck()
.WithHealthCheck<MyHealthCheckWithDependencies>(
name: "MyServiceHealth",
failureStatus: HealthStatus.Degraded,
tags: new[] { "ready", "service" },
timeout: TimeSpan.FromSeconds(5));
The health check type will be resolved from the DI container when the health check is executed, allowing you to leverage constructor injection for any dependencies your health check needs. The health check instance itself doesn't need to be registered in DI - Akka.Hosting will automatically resolve it using ActivatorUtilities.GetServiceOrCreateInstance<T>().
<a id="healthcheck-builtin"></a>
Built-in Health Checks
![NOTE] All Akka.NET health checks will be tagged with the
akkatag, so they can easily be filtered via the health check endpoints.
Akka.Hosting and its other packages ship with some built-in health checks:
WithActorSystemLivenessCheck()- a liveness probe that will fail if theActorSystemis terminated. Generally, Akka.Hosting will try to shut down your process anyway if theActorSystemdies.WithAkkaClusterReadinessCheck- if you are an Akka.Cluster user, this health check will returnHealthStatus.Unhealthyuntil you successfully join a cluster - that way you can stop load-balancers and other devices from routing traffic to this node until it has access to the cluster. This readiness check is also tagged with thereadytag for filtering purposes.- Akka.Persistence Health Checks - verify that persistence plugins (journals and snapshot stores) are properly initialized and accessible. These health checks use the built-in Akka.Persistence health check APIs to validate plugin connectivity and functionality. Health checks are tagged with
akka,persistence, and eitherjournalorsnapshot-storefor filtering purposes.
Configuring Persistence Health Checks
You can add health checks for your persistence plugins using the .WithHealthCheck() method when configuring journals and snapshot stores:
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
// Journal with health check
.WithJournal(
new SqlServerJournalOptions
{
ConnectionString = "...",
IsDefaultPlugin = true
},
journal => journal
.AddWriteEventAdapter<MyAdapter>("adapter", new[] { typeof(MyEvent) })
.WithHealthCheck(
unHealthyStatus: HealthStatus.Degraded,
name: "sql-journal"))
// Snapshot store with health check
.WithSnapshot(
new SqlServerSnapshotOptions
{
ConnectionString = "...",
IsDefaultPlugin = true
},
snapshot => snapshot
.WithHealthCheck(
unHealthyStatus: HealthStatus.Degraded,
name: "sql-snapshot"));
});
You can also configure both journal and snapshot health checks together:
builder.Services.AddAkka("MyActorSystem", configurationBuilder =>
{
configurationBuilder
.WithJournalAndSnapshot(
new SqlServerJournalOptions
{
ConnectionString = "...",
IsDefaultPlugin = true
},
new SqlServerSnapshotOptions
{
ConnectionString = "...",
IsDefaultPlugin = true
},
journal => journal.WithHealthCheck(),
snapshot => snapshot.WithHealthCheck());
});
The health checks will automatically:
- Verify the persistence plugin is configured correctly
- Test connectivity to the underlying storage (database, cloud storage, etc.)
- Report
Healthywhen the plugin is operational - Report
DegradedorUnhealthy(configurable) when issues are detected
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Akka.DependencyInjection (>= 1.6.0-beta8)
- Akka.Streams (>= 1.6.0-beta8)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 10.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.0)
- OpenTelemetry (>= 1.15.3)
NuGet packages (36)
Showing the top 5 NuGet packages that depend on Akka.Hosting:
| Package | Downloads |
|---|---|
|
Akka.Logger.Serilog
Serilog logging adapter for Akka.NET. |
|
|
Akka.Persistence.Hosting
Akka.Persistence Microsoft.Extensions.Hosting support. |
|
|
Akka.Remote.Hosting
Akka.Remote Microsoft.Extensions.Hosting support. |
|
|
Petabridge.Cmd.Host
Host engine for the Petabridge.Cmd CLI for managing Akka.NET apps and clusters. Used to load available commands into the cluster itself. |
|
|
Akka.Management
Akka cluster management module for Akka.NET |
GitHub repositories (7)
Showing the top 7 popular GitHub repositories that depend on Akka.Hosting:
| Repository | Stars |
|---|---|
|
petabridge/akka-bootcamp
Self-paced training course to learn Akka.NET fundamentals from scratch
|
|
|
petabridge/akkadotnet-code-samples
Akka.NET professional reference code samples
|
|
|
petabridge/memorizer
Vector-search powered agent memory MCP server
|
|
|
netclaw-dev/netclaw
Simple, secure, reliable agents. Self-hosted. Open source. Built with .NET.
|
|
|
Aaronontheweb/mssql-mcp
MSSQL Server MCP implementation written in C#
|
|
|
petabridge/TurboMqtt
The fastest Message Queue Telemetry Transport (MQTT) client for .NET.
|
|
|
rudzen/ChessLib
C# chess library containing a complete data structure and move generation.
|
| Version | Downloads | Last Updated |
|---|---|---|
| 1.6.0-beta8 | 10 | 11/18/2026 |
| 1.6.0-beta7 | 1,806 | 11/10/2026 |
| 1.6.0-beta6 | 411 | 11/7/2026 |
| 1.6.0-beta5 | 1,540 | 11/4/2026 |
| 1.6.0-beta4 | 448 | 10/28/2026 |
| 1.6.0-beta3 | 2,666 | 10/7/2026 |
| 1.6.0-beta2 | 271 | 10/6/2026 |
| 1.6.0-beta1 | 1,280 | 10/2/2026 |
| 1.5.75 | 955 | 11/16/2026 |
| 1.5.74 | 19,311 | 11/5/2026 |
| 1.5.73 | 87,700 | 10/5/2026 |
| 1.5.72 | 9,664 | 10/3/2026 |
| 1.5.71 | 89,938 | 8/27/2026 |
| 1.5.70 | 164,778 | 7/3/2026 |
| 1.5.69 | 188,555 | 6/15/2026 |
| 1.5.68 | 185,649 | 5/19/2026 |
| 1.5.67 | 149,544 | 4/26/2026 |
| 1.5.65 | 29,733 | 4/10/2026 |
| 1.5.64 | 14,046 | 3/31/2026 |
| 1.5.63 | 46,151 | 3/23/2026 |
Akka.NET 1.6.0-beta8 adds TLS certificate rotation without a restart on both DotNetty and Artery, brings Akka.Reminders into the repository, and fixes a PersistAll completion bug plus two recurring-reminder ordering bugs. Read the [v1.6 getting started guide](https://github.com/akkadotnet/akka.net/blob/dev/GETTING_STARTED_V1.6.md) for the full upgrade path.
**Akka.IO / TLS**
* `TlsCertificateSource` picks the certificate a node presents from a folder, a certificate store by common name, or a callback, and picks up a renewed certificate without a restart. A folder or store source is re-read in the background at most once every 10 seconds and the result is reused in between; a callback is called every time. Startup waits for the first look-up, and a source with nothing usable throws `ConfigurationException` so the node never binds. A connection that cannot get a certificate fails alone and the node stays up. ([#8966](https://github.com/akkadotnet/akka.net/pull/8966), relates to [#7663](https://github.com/akkadotnet/akka.net/issues/7663))
* Certificate errors are logged at most once a minute per cause, so one bad certificate does not log a Warning for every connection. DotNetty and Artery now share `Akka.IO.TlsCertificateRotation` for that limiter, the startup check and the one-minute poll interval, but each transport keeps its own instance so one transport never hides another's errors. ([#8982](https://github.com/akkadotnet/akka.net/pull/8982))
* On Artery's provider path, a failed certificate look-up now surfaces as an internal `TlsCertificateUnavailableException` that wraps the original cause, instead of writing a flag into the caller's own exception object. The only visible difference is one more `--->` level in the stack trace of Akka.Streams' "Restarting graph due to failure." warning. Fixed-certificate TLS and DotNetty are unaffected. ([#8982](https://github.com/akkadotnet/akka.net/pull/8982))
**Akka.Remote / DotNetty**
* DotNetty TLS certificates now rotate without a restart. `DotNettySslSetup.FromSource`, the HOCON keys `certificate.common-name` and `certificate.path` (a folder), `SslOptions.CertificateSource` and `SslCertificateOptions.CommonName` wire a `TlsCertificateSource` into the transport and Akka.Hosting. ([#8967](https://github.com/akkadotnet/akka.net/pull/8967))
* Artery rotates TLS certificates through the same `TlsCertificateSource`. Three new factories on `ArteryTlsSettings` - `Mutual(TlsCertificateSource, TlsPeerPolicy)`, a two-policy `Mutual` overload, and `ServerOnly(TlsCertificateSource, TlsPeerPolicy)` - take a source, and the node asks it for a certificate each time it builds a connection. Akka.Remote.Hosting needs no new API: `ArteryRemoteOptions.Tls` takes the profile. A startup look-up with nothing usable throws `ConfigurationException` and the node never binds, and a connection that cannot get a certificate fails alone while the node stays up. ([#8979](https://github.com/akkadotnet/akka.net/pull/8979), relates to [#7663](https://github.com/akkadotnet/akka.net/issues/7663))
* **Behavior change:** `SslOptions.CustomValidator` now runs when the certificate comes from `SslOptions.CertificateOptions` (a file `Path` or a `Thumbprint`). It used to run only with `SslOptions.X509Certificate`; with the other two it was silently ignored, so a security check you configured never ran. A validator that was ignored can now fail a TLS handshake, and on the dialing side a failed handshake shuts the `ActorSystem` down. With `EnableSsl = true`, a `CustomValidator` and no certificate in the options, `WithRemoting` now throws `ConfigurationException`. The certificate also loads when `WithRemoting` runs rather than when the `ActorSystem` starts, so a missing file or thumbprint fails earlier. See the [v1.6 breaking-change ledger](https://github.com/akkadotnet/akka.net/blob/dev/BREAKING_CHANGES_V1.6.md). ([#8964](https://github.com/akkadotnet/akka.net/pull/8964))
**Akka.Reminders (new module)**
* Akka.Reminders now ships from this repository as `Akka.Reminders` and its storage packages, replacing the standalone `Aaron.Akka.Reminders` packages. It provides durable, re-entrant reminders for Akka.Cluster.Sharding with SQL Server, PostgreSQL, SQLite and in-memory storage, a cluster-singleton scheduler, and Akka.Hosting integration. **Migration:** the package ID changed, so update your `PackageReference` and namespaces. ([#8946](https://github.com/akkadotnet/akka.net/pull/8946))
* Opt-in retry-until-acknowledged delivery: a reminder can require an explicit acknowledgement before it counts as delivered, with exponential backoff between attempts. The policy is persisted in all four storage backends, and existing signatures and default-policy wire layouts are unchanged. Opted-in schedules, responses and listings use versioned manifests, so **upgrade every potential scheduler host and policy-message reader before enabling the feature** - older schedulers must not take over while opted-in rows exist. Manual migration scripts for each provider live in `src/contrib/reminders/docs/migrations/retry-policy/`, and every provider and potential scheduler host must be recreated after migrating because schema capabilities are cached. ([#8973](https://github.com/akkadotnet/akka.net/pull/8973))
* An early send of a recurring reminder now ends every older live occurrence atomically with the newer delivery, suppresses those rows for the rest of the fetch pass, and prevents a stale row from writing them back as Pending. Previously only the previous occurrence was ended, so a series with an interval below `MaxSlippage` could deliver stale occurrences after a newer one during a shard-region outage. ([#8971](https://github.com/akkadotnet/akka.net/pull/8971), [#8976](https://github.com/akkadotnet/akka.net/pull/8976), fixes [#8965](https://github.com/akkadotnet/akka.net/issues/8965))
* That cleanup is capped at 256 older occurrences per send, nearest first. A 1 ms interval would otherwise put thousands of expiries in one commit, and a sub-millisecond interval could put millions into the scheduler's memory. Below roughly a 20 ms interval at the default 5 s `MaxSlippage`, an older occurrence more than 256 intervals back can still be delivered after a newer one during a shard-region outage. ([#8975](https://github.com/akkadotnet/akka.net/pull/8975), [#8976](https://github.com/akkadotnet/akka.net/pull/8976))
**Akka**
* `Unwatch` now clears the sole watcher from an optimized actor state. `DefaultActorState.RemoveWatchedBy` never cleared its optimized slot, so a target kept a reference to an actor that had unwatched it. `FullActorState` already removed watchers correctly. No public API or wire-format change. ([#8936](https://github.com/akkadotnet/akka.net/pull/8936))
**Akka.Persistence**
* The `PersistAll` completion callback no longer runs when the journal rejects the batch. `OnPersistRejected` fired for each event and then the completion callback ran anyway, so a handler saw a completion for a batch that was never persisted. This affected all eight `PersistAll`/`PersistAllAsync` overloads. Journal write failures are unchanged: the actor stops before the completion's message is processed. ([#8949](https://github.com/akkadotnet/akka.net/pull/8949), fixes [#8948](https://github.com/akkadotnet/akka.net/issues/8948))
**Akka.Remote / Artery**
* Artery's inbound stage now reports a framing error when a peer closes after a partial connection preamble, frame length or frame body, instead of silently completing the connection. Empty connections and complete frame boundaries still close cleanly, and cancellation and upstream failure keep their existing semantics. Artery is new in v1.6, so this changes unreleased behavior only. ([#8956](https://github.com/akkadotnet/akka.net/pull/8956))
**Serialization**
* Native module replacements can preserve legacy serializer type names through an optional type-alias map, so a ported serializer keeps reading data written under the original assembly-qualified name. Each declared name resolves to an existing module row using the declared type's assembly simple name and the existing strict name-matching rules; subclasses are not matched. Missing or ambiguous aliases, non-serializer types and conflicting registrations are rejected. No serializer rows, ids or configuration switches are added. ([#8920](https://github.com/akkadotnet/akka.net/pull/8920))
**Akka.Hosting**
* `Akka.Hosting`, `Akka.Cluster.Hosting`, `Akka.Remote.Hosting`, `Akka.Persistence.Hosting` and `Akka.Persistence.Embedded.Hosting` now ship their own module READMEs on nuget.org instead of the generic Akka.NET one. Relative links were rewritten to absolute GitHub permalinks because nuget.org cannot resolve relative paths. ([#8945](https://github.com/akkadotnet/akka.net/pull/8945))
**Docs**
* New [TLS certificate rotation](https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/remoting/certificate-rotation.md) article covers folder, store and callback sources, when a renewed certificate is used, what happens when a look-up finds nothing usable, and the error-logging behavior. Both the DotNetty transport and Artery rotate certificates the same way. ([#8968](https://github.com/akkadotnet/akka.net/pull/8968), relates to [#7663](https://github.com/akkadotnet/akka.net/issues/7663))
**Internal**
* `MultiNodeSpec` now terminates a replacement actor system when initialization fails, including on caller cancellation, and preserves the original exception. ([#8955](https://github.com/akkadotnet/akka.net/pull/8955))
* `RemotePingPong` validates delivery and compares authenticated TCP, and measures latency at a scheduled offered load with per-run reporting that separates generator lateness, dispatch delay, send-to-echo and scheduled-to-echo latency. ([#8953](https://github.com/akkadotnet/akka.net/pull/8953), [#8957](https://github.com/akkadotnet/akka.net/pull/8957))
* Artery's DeathWatch ACK-loss test now witnesses TCP system-message retries by counting dropped ACKs per peer UID and cumulative sequence. ([#8954](https://github.com/akkadotnet/akka.net/pull/8954))
* `ShardedDaemonProcessSpecs` waits for sharded daemon restarts with one overall deadline instead of back-to-back 3-second waits, fixing a Windows CI timeout. ([#8981](https://github.com/akkadotnet/akka.net/pull/8981))
* Slopwatch upgraded to 0.5.0 with a regenerated schema-v2 baseline. ([#8980](https://github.com/akkadotnet/akka.net/pull/8980))
* The Serialization V2 port-comparison test kit now compares the root message's members in its structural fallback and checks the exact runtime type before the equality fast path, and supports shared system names. Test-only; no production API, bindings or wire bytes change. ([#8916](https://github.com/akkadotnet/akka.net/pull/8916))
1 contributor since release 1.6.0-beta7
| COMMITS | LOC+ | LOC- | AUTHOR |
|---------|------|------|-----------------|
| 22 | 44500 | 1088 | Aaron Stannard |