Akka.Persistence.Sql.Hosting 1.6.0-beta4

Prefix Reserved
This is a prerelease version of Akka.Persistence.Sql.Hosting.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Akka.Persistence.Sql.Hosting --version 1.6.0-beta4
                    
NuGet\Install-Package Akka.Persistence.Sql.Hosting -Version 1.6.0-beta4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Akka.Persistence.Sql.Hosting" Version="1.6.0-beta4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Akka.Persistence.Sql.Hosting" Version="1.6.0-beta4" />
                    
Directory.Packages.props
<PackageReference Include="Akka.Persistence.Sql.Hosting" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Akka.Persistence.Sql.Hosting --version 1.6.0-beta4
                    
#r "nuget: Akka.Persistence.Sql.Hosting, 1.6.0-beta4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Akka.Persistence.Sql.Hosting@1.6.0-beta4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Akka.Persistence.Sql.Hosting&version=1.6.0-beta4&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Akka.Persistence.Sql.Hosting&version=1.6.0-beta4&prerelease
                    
Install as a Cake Tool

Akka.Persistence.Sql

A Cross-SQL-DB Engine Akka.Persistence plugin with broad database compatibility thanks to Linq2Db.

This is a port of the amazing akka-persistence-jdbc package from Scala, with a few improvements based on C# as well as our choice of data library.

Please read the documentation carefully. Some features may have specific use case and have trade-offs (namely, compatibility modes).

If you're migrating from legacy Akka.Persistence.Sql.Common based plugins, you can read the migration guide documentation, the migration tutorial, and watch the migration tutorial video.

Table Of Content

Getting Started

The Easy Way, Using Akka.Hosting

Assuming a MS SQL Server 2019 setup:

var host = new HostBuilder()
    .ConfigureServices((context, services) => {
        services.AddAkka("my-system-name", (builder, provider) =>
        {
            builder.WithSqlPersistence(
                connectionString: _myConnectionString,
                providerName: ProviderName.SqlServer2019);
        });
    });

You can also provide your own LinqToDb.DataOptions object for a more advanced configuration. Assuming a setup with a custom NpgsqlDataSource:

NpgsqlDataSource dataSource = new NpgsqlDataSourceBuilder(_myConnectionString).Build();

DataOptions dataOptions = new DataOptions()
    .UseDataProvider(DataConnection.GetDataProvider(ProviderName.PostgreSQL, dataSource.ConnectionString) ?? throw new Exception("Could not get data provider"))
    .UseProvider(ProviderName.PostgreSQL)
    .UseConnectionFactory((opt) => dataSource.CreateConnection());
    
var host = new HostBuilder()
    .ConfigureServices((context, services) => {
        services.AddAkka("my-system-name", (builder, provider) =>
        {
            builder.WithSqlPersistence(dataOptions);
        });
    });

If dataOptions are provided, you must supply enough information for linq2db to connect to the database. This includes setting the connection string and provider name again, if necessary for your use case. Please consult the Linq2Db documentation for more details on configuring a valid DataOptions object. Note that MappingSchema and RetryPolicy will always be overridden by Akka.Persistence.Sql.

LinqToDB 6 compatibility

The dev branch uses LinqToDB 6. The custom IDataProvider interface has new required members, and several provider types moved namespaces. Custom providers and integrations using those LinqToDB 5 APIs must be migrated and rebuilt. The optional parent-insert optimization remains off by default; that setting does not opt out of the dependency upgrade.

Register interceptors through DataOptions.UseInterceptor or UseInterceptors before passing the options to the plugin. Connection clones reconstruct those registrations independently. Interceptors added or removed directly on an already constructed DataConnection are not snapshotted by AkkaDataConnection.Clone(); register them in the options instead.

The FK benchmark report retains its measured source revisions: its v1.5 baseline c8413c6 predates #580. Those historical results do not describe parent-insert availability in later v1.5 releases; check the installed plugin version when selecting settings.

Health Checks

Starting with Akka.Persistence.Sql v1.5.51 or later, you can add health checks for your persistence plugins. Akka.Persistence.Sql supports two types of health checks that integrate with Microsoft.Extensions.Diagnostics.HealthChecks and can be used with ASP.NET Core health check endpoints.

Standard Health Checks

Standard health checks monitor the persistence plugins themselves and verify that journals and snapshot stores are properly initialized and accessible.

To configure standard health checks, use the journalBuilder and snapshotBuilder parameters with the .WithHealthCheck() method:

var host = new HostBuilder()
    .ConfigureServices((context, services) => {
        services.AddAkka("my-system-name", (builder, provider) =>
        {
            builder.WithSqlPersistence(
                connectionString: _myConnectionString,
                providerName: ProviderName.SqlServer2019,
                journalBuilder: journal => journal.WithHealthCheck(HealthStatus.Degraded),
                snapshotBuilder: snapshot => snapshot.WithHealthCheck(HealthStatus.Degraded));
        });
    });

Standard health checks are tagged with akka, persistence, and either journal or snapshot-store for filtering and organization purposes.

Connectivity Health Checks (Akka.Persistence.Sql.Hosting v1.5.X+)

Connectivity health checks proactively verify database connectivity regardless of recent operation activity. This helps detect database outages during idle periods when the standard health checks might not catch issues.

Using Akka.Hosting 1.5.55.1 or later (Simplified API):

services.AddAkka("my-system-name", (builder, provider) =>
{
    builder.WithSqlPersistence(
        connectionString: connectionString,
        providerName: ProviderName.SqlServer2022,
        journalBuilder: journal =>
        {
            journal.WithHealthCheck();           // Monitor plugin status
            journal.WithConnectivityCheck();     // Verify database connectivity
        },
        snapshotBuilder: snapshot =>
        {
            snapshot.WithHealthCheck();          // Monitor plugin status
            snapshot.WithConnectivityCheck();    // Verify database connectivity
        });
});

The connectivity checks will automatically:

  • Verify connectivity to the underlying SQL database
  • Test database responsiveness with a lightweight "SELECT 1" query
  • Report Healthy when the database is accessible
  • Report Unhealthy (configurable) when the database is unreachable or unresponsive

Connectivity checks are tagged with akka, persistence, sql, and either journal or snapshot-store for filtering and organization purposes.

Exposing Health Checks via ASP.NET Core

For ASP.NET Core applications, you can expose these health checks via an endpoint:

var builder = WebApplication.CreateBuilder(args);

// Add health checks service
builder.Services.AddHealthChecks();

builder.Services.AddAkka("my-system-name", (configBuilder, provider) =>
{
    configBuilder.WithSqlPersistence(
        connectionString: _myConnectionString,
        providerName: ProviderName.SqlServer2019,
        journalBuilder: journal => journal.WithHealthCheck(),
        snapshotBuilder: snapshot => snapshot.WithHealthCheck());
});

var app = builder.Build();

// Map health check endpoint
app.MapHealthChecks("/healthz");

app.Run();
Customizing Health Check Configuration

You can customize the names, tags, and unhealthy status for both standard and connectivity health checks:

services.AddAkka("my-system-name", (builder, provider) =>
{
    builder.WithSqlPersistence(
        connectionString: connectionString,
        providerName: ProviderName.SqlServer2022,
        journalBuilder: journal =>
        {
            // Customize standard health check
            journal.WithHealthCheck(
                unHealthyStatus: HealthStatus.Degraded,
                name: "sql-journal",
                tags: new[] { "backend", "database", "sql" });

            // Customize connectivity health check
            journal.WithConnectivityCheck(
                unHealthyStatus: HealthStatus.Unhealthy,
                name: "sql-journal-connectivity",
                tags: new[] { "backend", "database", "sql", "connectivity" });
        },
        snapshotBuilder: snapshot =>
        {
            // Customize standard health check
            snapshot.WithHealthCheck(
                unHealthyStatus: HealthStatus.Degraded,
                name: "sql-snapshot",
                tags: new[] { "backend", "database", "sql" });

            // Customize connectivity health check
            snapshot.WithConnectivityCheck(
                unHealthyStatus: HealthStatus.Unhealthy,
                name: "sql-snapshot-connectivity",
                tags: new[] { "backend", "database", "sql", "connectivity" });
        });
});

Default tags when not specified:

  • Standard health checks: ["akka", "persistence", "journal"] or ["akka", "persistence", "snapshot-store"]
  • Connectivity health checks: ["akka", "persistence", "sql", "journal", "connectivity"] or ["akka", "persistence", "sql", "snapshot-store", "connectivity"]

The Classic Way, Using HOCON

These are the minimum HOCON configuration you need to start using Akka.Persistence.Sql:

akka.persistence {
    journal {
        plugin = "akka.persistence.journal.sql"
        sql {
            class = "Akka.Persistence.Sql.Journal.SqlWriteJournal, Akka.Persistence.Sql"
            connection-string = "{database-connection-string}"
            provider-name = "{provider-name}"
        }
    }
    query.journal.sql {
        class = "Akka.Persistence.Sql.Query.SqlReadJournalProvider, Akka.Persistence.Sql"
        connection-string = "{database-connection-string}"
        provider-name = "{provider-name}"
    }
    snapshot-store {
        plugin = "akka.persistence.snapshot-store.sql"
        sql {
            class = "Akka.Persistence.Sql.Snapshot.SqlSnapshotStore, Akka.Persistence.Sql"
            connection-string = "{database-connection-string}"
            provider-name = "{provider-name}"
        }
    }
}
  • database-connection-string: The proper connection string to your database of choice.
  • provider-name: A string constant defining the database type to connect to, valid values are defined inside LinqToDB.ProviderName static class. Refer to the Members of LinqToDb.ProviderName for included providers.

Note: For best performance, one should use the most specific provider name possible. i.e. LinqToDB.ProviderName.SqlServer2012 instead of LinqToDB.ProviderName.SqlServer. Otherwise certain provider detections have to run more frequently which may impair performance slightly.

Supported Database Providers

Tested Database Providers

  • Microsoft SQL Server
  • MS SQLite
  • System.Data.SQLite
  • PostgreSQL using binary payload
  • MySql

Supported By Linq2Db But Untested In Akka.Persistence

  • Firebird
  • Microsoft Access OleDB
  • Microsoft Access ODBC
  • IBM DB2
  • Informix
  • Oracle
  • Sybase
  • SAP HANA
  • ClickHouse

Sql.Common Compatibility modes

  • Delete Compatibility mode is available.
    • This mode will utilize a journal_metadata table containing the last sequence number
    • The main table delete is done the same way regardless of delete compatibility mode

Delete Compatibility mode is expensive.

  • Normal Deletes involve first marking the deleted records as deleted, and then deleting them
    • Table compatibility mode adds an additional InsertOrUpdate and Delete
  • This all happens in a transaction
    • In SQL Server this can cause issues because of page locks/etc.

DDL Scripts for Database Schema Management

Pre-generated DDL scripts are available in docs/ddl/ for creating Akka.Persistence.Sql tables through your own migrations instead of relying on automatic table creation at runtime.

Directory Structure:

The initialization SQL files are checked into this repository:

Provider Default mapping Compatibility mapping
PostgreSQL Scripts Scripts
SQL Server Scripts Scripts
MySQL Scripts Scripts
SQLite Scripts Scripts

Each directory contains SQL scripts for each supported provider (sqlserver, postgresql, mysql, sqlite):

  • journal.sql - Event journal table
  • journal-tags.sql - Tag table for TagMode.TagTable
  • snapshot.sql - Snapshot store table
  • metadata.sql - Metadata table for delete-compatibility-mode

When to use DDL scripts:

  • When using Entity Framework Core or FluentMigrator for schema management
  • When you need explicit control over database schema versioning
  • When auto-initialization is disabled (auto-initialize = false)

See the DDL documentation for detailed usage instructions and examples.

Database-Side Journal Retention

Akka.Persistence's DeleteMessagesTo deletes an entity's events and their tag rows together. If you purge old events with your own SQL instead, delete their tag rows too, or the tags table grows forever.

See the journal retention guide for the rules and example scripts for PostgreSQL, SQL Server, MySQL, and SQLite.

Optional Tag-Table Foreign Keys

The journal-to-tag foreign key (tags.ordering_id -> journal.ordering ON DELETE CASCADE) is an optional, operator-applied migration for PostgreSQL and SQL Server. Runtime auto-initialization and the base DDL scripts create tables without it. With the FK installed, deleting a journal row also removes its tag rows. Existing databases must clean up orphaned tags with 01 before installing it.

The FK adds overhead to tagged writes and especially to deletes. Review the measured FK overhead and the maintenance guide before opting in.

Tuning Akka.Persistence.Query for Low-Latency Projections

Default polling intervals cause 500-1200ms projection latency. For low-latency CQRS, tune BOTH settings together:

akka.persistence.query.journal.sql {
    refresh-interval = 10ms          # Query stream polling
    max-buffer-size = 50
    journal-sequence-retrieval {
        query-delay = 10ms           # Sequence actor polling - CRITICAL!
    }
}

Important: Tuning only refresh-interval does NOT work. The sequence actor polls independently via query-delay.

Performance Guide

Configuration Latency Database Load
Default (1s/1s) 500-1200ms Low
Balanced (50ms/50ms) 50-200ms Medium
Low latency (10ms/10ms) 20-100ms High

Trade-off: Lower = faster but higher DB load. In clusters, each node polls independently.

See persistence.conf for detailed settings documentation.

Building this solution

To run the build script associated with this solution, execute the following:

Windows

c:\> build.cmd all

Linux / OS X

c:\> build.sh all

If you need any information on the supported commands, please execute the build.[cmd|sh] help command.

This build script is powered by FAKE; please see their API documentation should you need to make any changes to the build.fsx file.

Conventions

The attached build script will automatically do the following based on the conventions of the project names added to this project:

  • Any project name ending with .Tests will automatically be treated as a XUnit2 project and will be included during the test stages of this build script;
  • Any project name ending with .Tests will automatically be treated as a NBench project and will be included during the test stages of this build script; and
  • Any project meeting neither of these conventions will be treated as a NuGet packaging target and its .nupkg file will automatically be placed in the bin\nuget folder upon running the build.[cmd|sh] all command.

Release Notes, Version Numbers, Etc

This project will automatically populate its release notes in all of its modules via the entries written inside RELEASE_NOTES.md and will automatically update the versions of all assemblies and NuGet packages via the metadata included inside Directory.Build.props.

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (4)

Showing the top 4 popular GitHub repositories that depend on Akka.Persistence.Sql.Hosting:

Repository Stars
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.
petabridge/DrawTogether.NET
Multi-player MS Paint application. Built with Akka.NET, Blazor, and .NET Aspire.
Version Downloads Last Updated
1.6.0-beta5 2,242 11/5/2026
1.6.0-beta4 84 11/2/2026
1.6.0-beta3 1,605 10/7/2026
1.6.0-beta2 117 10/6/2026
1.5.73 5,091 11/2/2026
1.5.70 92,092 7/23/2026
1.5.70-beta1 138 6/24/2026
1.5.67 41,186 4/28/2026
1.5.62 14,613 3/27/2026
1.5.60.1 18,375 2/16/2026
1.5.59 14,429 1/27/2026
1.5.55.1 25,437 10/29/2025
1.5.55 2,024 10/27/2025
1.5.53 28,919 10/14/2025
1.5.51.1 35,222 10/2/2025
1.5.51 1,202 10/1/2025
1.5.44 22,222 6/23/2025
1.5.42 6,157 5/22/2025
1.5.40.1 4,472 4/7/2025
1.5.40 11,157 3/26/2025
Loading failed

Built against Akka.NET 1.6.0-beta4.

**Breaking changes**

* [Upgrade to LinqToDB 6](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/580) - LinqToDB 6 is a major dependency upgrade: custom providers and integrations using changed LinqToDB 5 provider APIs must be migrated and rebuilt. Register interceptors with `DataOptions.UseInterceptor` / `UseInterceptors`; mutations made directly with `DataConnection.AddInterceptor` / `RemoveInterceptor` after construction are not copied by `AkkaDataConnection.Clone()`.

**New features**

* [Batched tag-table journal inserts](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/580) - New opt-in `tagtable-asqueryable-insert-mode` journal setting (`off` by default, `parameterized` or `inline`; `TagTableQueryableInsertMode` in Akka.Persistence.Sql.Hosting). When tags are stored in the tag table on SQL Server, PostgreSQL or SQLite, it writes journal rows and their tag rows in batched commands instead of one round-trip per event. Tune it with `tagtable-asqueryable-insert-sql-length-limit` and `tagtable-asqueryable-insert-max-parameters`. The older `use-tagtable-asqueryable-literal-insert` flag still works (`true` maps to `inline`).
* [Skip the batched tag-table insert when it cannot help](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/617) - Batches with no tagged events, and writes of a single tagged event, use the standard BulkCopy path even when `tagtable-asqueryable-insert-mode` is enabled, so untagged workloads get the same throughput as `off`.
* [Optional tag-table foreign key scripts](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/614) - New scripts under `scripts/TagTableForeignKey` for PostgreSQL and SQL Server to clean up orphaned tag rows and add or drop an optional foreign key from the tag table to the journal, with setup and maintenance docs.
* [Document database-side journal retention](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/618) - Guidance and example SQL for PostgreSQL, SQL Server, MySQL, and SQLite to purge old journal events with your own SQL without leaving orphaned tag rows behind.

**Bug fixes**

* [Fix SQL plugin materializer lifetime](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/601) - Journal and snapshot store stream materializers are now owned by their plugin actors, so their streams are cleaned up when the actor stops or fails initialization.
* [Rate-limit SQL initialization retries](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/603) - New `initialization-retry-delay` setting (default `1s`) for the journal and snapshot store paces restarts when the database is unavailable, instead of looping immediately and allocating heavily. Pending retry waits are cancelled when the plugin stops.
* [Complete the journal write queue on shutdown](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/607) - Pending writes no longer wait forever when the journal actor stops with writes still buffered.
* [Cancel SQL queries when journal streams stop](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/609) - Cancel in-flight database queries when a read-journal or journal-replay stream stops, including `Offset.FromEnd` and current-query boundary lookups. Preserve the configured scheduler for refresh delays.
* Concrete journal DAO `Messages` queries now start when their returned source is materialized. Database errors fail that source. Existing custom DAO overrides continue to dispatch; eager work performed before an override returns its source cannot receive stream cancellation through the existing signature.
* [Fix LinqToDB 6 provider overrides and connection cloning](https://github.com/akkadotnet/Akka.Persistence.Sql/pull/615) - Preserve tag-table fast-insert provider detection when supplied `DataOptions` override the HOCON provider name, and restore the `MySql.Official` alias using the MySql.Data driver.
* Restore independent cloned connections, detached external transactions, and current query settings after the LinqToDB 6 upgrade. Reuse resolved providers and retry policies without repeating their factories; use fluent options to avoid cross-target-framework record-setter incompatibilities.

**Other changes**

* Bump Akka.NET to 1.6.0-beta4
* Bump Akka.Hosting, Akka.Persistence.Hosting and Akka.Cluster.Hosting to 1.6.0-beta4