Aaron.Akka.Durable.TestKit
0.1.0-alpha.6
dotnet add package Aaron.Akka.Durable.TestKit --version 0.1.0-alpha.6
NuGet\Install-Package Aaron.Akka.Durable.TestKit -Version 0.1.0-alpha.6
<PackageReference Include="Aaron.Akka.Durable.TestKit" Version="0.1.0-alpha.6" />
<PackageVersion Include="Aaron.Akka.Durable.TestKit" Version="0.1.0-alpha.6" />
<PackageReference Include="Aaron.Akka.Durable.TestKit" />
paket add Aaron.Akka.Durable.TestKit --version 0.1.0-alpha.6
#r "nuget: Aaron.Akka.Durable.TestKit, 0.1.0-alpha.6"
#:package Aaron.Akka.Durable.TestKit@0.1.0-alpha.6
#addin nuget:?package=Aaron.Akka.Durable.TestKit&version=0.1.0-alpha.6&prerelease
#tool nuget:?package=Aaron.Akka.Durable.TestKit&version=0.1.0-alpha.6&prerelease
Akka.Durable
Akka.Durable is a proof of concept, not an official Akka.NET project. It is published as Aaron.Akka.Durable because the Akka.* NuGet prefix is reserved for official Akka.NET packages. Expect breaking changes between releases.
Akka.Durable gives you event-sourced entities on Akka.NET. Define their behavior with pure Decide and Evolve functions, keep the impure work in effect handlers, then send commands through typed references. The runtime handles persistence, recovery, and routing in local or clustered deployments. Callers can wait for an entity's state, or watch it, without polling.
Inject it. Send a message.
Entity reference factories are .NET DI services. Call AddDurableEntities() at startup, then inject IEntityRefs<InvoiceCommand> into any controller, hosted service, or application service:
public sealed class BillingService(IEntityRefs<InvoiceCommand> invoices)
{
public Task<IssueReply> IssueAsync(EntityId id, CancellationToken ct) =>
invoices.Get(id).Ask(new IssueInvoice(250m, "billing@example.com"), ct);
public void Remind(EntityId id) =>
invoices.Get(id).Tell(new SendReminder());
}
That's the caller API: choose an ID, send a command, get its declared reply type. The first message creates or recovers the entity. The same calls work with local hosting and Cluster Sharding. Register and host the entity once at startup.
Define its behavior
Here is the Invoice behind those calls. Decide produces events and effects; Evolve computes the state from each persisted event. Issuing an invoice needs an answer from a recipient directory, so Decide records that verification started and issues a VerifyRecipient effect. The directory's answer comes back as a command, RecipientVerified or RecipientRejected, and a second arm finishes the job.
using InvoiceContext = DecisionContext<InvoiceState, InvoiceCommand, InvoiceEvent>;
public static class Invoice
{
public static readonly EntityDefinition<InvoiceState, InvoiceCommand, InvoiceEvent> Definition =
new(new EntityTypeName("invoices"), _ => new Draft(), Decide, Evolve);
public static Decision<InvoiceCommand, InvoiceEvent> Decide(
InvoiceState state,
InvoiceCommand command,
InvoiceContext ctx) =>
(state, command) switch
{
// Needs an outside answer: remember that we asked, then ask.
(Draft, IssueInvoice c) when c.Total > 0 =>
ctx.Persist(new VerificationStarted(c))
.Execute(new VerifyRecipient(c.Recipient)),
// The answer arrives as a command. The request kept in state fixes the reply type.
(Verifying v, RecipientVerified) =>
ctx.Persist(new InvoiceIssued(v.Request.Total, v.Request.Recipient, ctx.UtcNow))
.Schedule("reminder", TimeSpan.FromDays(30), new SendReminder())
.Reply(v.Request, new InvoiceAccepted(ctx.EntityId)),
(Verifying v, RecipientRejected r) =>
ctx.Persist(new VerificationFailed(r.Reason))
.Reply(v.Request, new InvoiceRejected(r.Reason)),
(_, RecipientVerified or RecipientRejected) => ctx.Ignore(),
(Issued s, RecordPayment p) when p.Amount == s.Total =>
ctx.Persist(new PaymentRecorded(p.Amount))
.CancelTimer("reminder")
.Reply(p, new PaymentAccepted()),
// A lost reminder mail is acceptable, so the light, unrecorded Run is enough.
(Issued, SendReminder) =>
ctx.None().Run<IInvoiceMailer>((mailer, ct) => mailer.RemindAsync(ct)),
(_, SendReminder) => ctx.Ignore(),
(_, IssueInvoice c) =>
ctx.None().Reply(c, new InvoiceRejected("Invalid invoice operation")),
(_, RecordPayment p) =>
ctx.None().Reply(p, new InvoiceRejected("Invalid invoice operation")),
};
public static InvoiceState Evolve(InvoiceState state, InvoiceEvent @event) =>
(state, @event) switch
{
(Draft, VerificationStarted e) => new Verifying(e.Request),
(Verifying, VerificationFailed) => new Draft(),
(Verifying, InvoiceIssued e) => new Issued(e.Total, e.Recipient),
(Issued s, PaymentRecorded) => new Paid(s.Total),
_ => throw new InvalidOperationException($"Cannot apply {@event} to {state}."),
};
}
VerifyRecipient is the effect: plain data, journaled in the same write as VerificationStarted. It says which command Decide gets when the directory gives no answer:
[AkkaSerializable(Manifest = "verify-recipient-v1")]
public sealed record VerifyRecipient([property: AkkaField(0)] string Recipient)
: IInvoiceProtocol, IEffect<InvoiceCommand>
{
public InvoiceCommand GaveUp(WorkGaveUp g) =>
new RecipientRejected($"directory: {g.Reason}");
}
The only impure code is its handler, which Akka.Durable resolves from a fresh DI scope when the effect runs. The handler's second type argument says what kind of answer it produces, here a command that goes back through Decide:
public sealed class VerifyRecipientHandler(IRecipientDirectory directory)
: IEffectHandler<VerifyRecipient, InvoiceCommand>
{
public async Task<InvoiceCommand> HandleAsync(
VerifyRecipient effect,
EffectDelivery delivery,
CancellationToken ct) =>
await directory.LookupAsync(effect.Recipient, ct) switch
{
Known => new RecipientVerified(),
Unknown u => new RecipientRejected(u.Reason),
};
}
// at startup, next to the other services
services.AddEffectHandler<VerifyRecipient, InvoiceCommand, VerifyRecipientHandler>();
The state, command, event, and reply declarations are in the guide. You write the domain functions and the handlers; Akka.Durable supplies the actor.
The calling surface is small: IEntityRef sends commands, and IDurableEntityRef adds state reads:
public interface IEntityRef<in TCommand>
{
EntityId Id { get; }
void Tell(TCommand command, IActorRef? sender = null);
Task<TReply> Ask<TReply>(
IReplies<TCommand, TReply> command,
CancellationToken cancellationToken = default) where TReply : notnull;
}
public interface IDurableEntityRef<in TCommand, TState, TEvent> : IEntityRef<TCommand>
{
Task<StateSnapshot<TState>> GetStateAsync(CancellationToken cancellationToken = default);
Task<StateSnapshot<TState>> WaitForStateAsync(
Func<TState, bool> until,
CancellationToken cancellationToken);
IAsyncEnumerable<StateSnapshot<TState>> WatchStateAsync(
CancellationToken cancellationToken = default);
}
Ask infers its reply type from the command. GetStateAsync returns the committed state and its journal sequence number. Both reference factories can be injected: use IEntityRefs<InvoiceCommand> for messaging, or IDurableEntityRefs<InvoiceCommand, InvoiceState, InvoiceEvent> for messaging plus state reads. Both are registered by AddDurableEntities(). The registry is keyed by command type, so each entity type must have its own command type.
To react to a change, do not read the state in a loop. Wait for the state, or watch it:
// In a request handler: wait at most five seconds for the payment.
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(TimeSpan.FromSeconds(5));
// Throws OperationCanceledException at the limit.
var paid = await invoices.Get(id).WaitForStateAsync(s => s is Paid, limit.Token);
// In a status stream: the current state first, then each new one.
await foreach (var snapshot in invoices.Get(id).WatchStateAsync(ct))
await WriteStatusAsync(snapshot.State, snapshot.SequenceNr, ct);
You get the current state first, then a snapshot after each write that holds events, once its Run effects have finished. Every snapshot carries the journal's sequence number as the version of the state, and a slow reader of the stream gets the newest one. This is a live, best-effort push held in memory: nothing is journaled, a state can be missed while the entity restarts or moves, and a reaction that must happen belongs in an effect. Workflow refs have the same two calls, and WaitForOutcome is built on the wait. See Waiting for a state, and watching it.
You do not need to build an outbox. Akka.Durable has one.
// In Decide:
ctx.Persist(new PaymentRecorded(p.Amount))
.Execute(new PublishPayment(ctx.EntityId, p.Amount));
services.AddEffectHandler<PublishPayment, PublishPaymentHandler>(
Retry.UntilAcknowledged(
TimeSpan.FromSeconds(1),
TimeSpan.FromMinutes(5)));
public sealed class PublishPaymentHandler(IBus bus)
: IEffectHandler<PublishPayment>
{
/* ... */
}
PublishPayment is recorded in the same journal write as PaymentRecorded, and its handler runs at least once, after a crash too, until it returns without throwing; it can run more than once, so it must be safe to repeat.
See Effects for the other retry policies, and for Execute without a policy, which is attempted once and tells Decide how it ended. A workflow's work takes the same policies from the same registration: see Workflows.
Getting started
Install the .NET 11 SDK pinned in global.json, then run:
dotnet restore
dotnet build
dotnet test
The solution targets net11.0 and enables preview C# features (C# 15 unions are used throughout). Package versions are managed centrally; Akka.NET packages are pinned to 1.6.0-beta7 (Aaron.Akka.Reminders to 1.6.0-beta5).
| Package | Contents |
|---|---|
Aaron.Akka.Durable |
Entity definitions, decisions and effects, entity refs, the entity runtime, and Akka.Hosting integration. Everything is in the Akka.Durable namespace. |
Aaron.Akka.Durable.TestKit |
Test helpers built on Akka.Hosting.TestKit, in the Akka.Durable.TestKit namespace |
Guide
The rest of the documentation is in docs/, one topic per page. Read it in this order:
| Page | What it covers |
|---|---|
| State, commands, events, and replies | How to declare an entity's state, commands, events and replies, and what a decision can do. |
| Effects | Execute, the normal way to do outside work, retry policies (the outbox), and the light forms Run, Tell and Send. |
| Effects with outcomes | Effect handlers, answers and give-ups, for work whose result the entity decides on. |
| Talking to other entities | Send and Accepts, for one entity that drives another. |
| Starting a workflow from an entity | Uses, and Start, Notify and Cancel from a decision. |
| Serialization | What is serialized, and how to change stored types safely. |
| Hosting | Local and sharded hosting, passivation and shard count. |
| Sending commands | Entity refs, Ask and Tell, and entity IDs inside messages. |
| Reading state | State-aware refs, and what a state read sees. |
| Waiting for a state, and watching it | WaitForStateAsync and WatchStateAsync, and what a state subscription guarantees. |
| Workflows | Finite processes that start once and end with an outcome: states, work, retry policies on work, the fact table, and workflow refs. |
| Workflow rules | Rules for writing a workflow that stays correct across restarts. |
| Testing | Decisions as plain functions, and the hosted TestKit. |
| Status and direction | What works today and what is not done yet. |
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Aaron.Akka.Durable (>= 0.1.0-alpha.6)
- Akka.Hosting.TestKit (>= 1.6.0-beta7)
- xunit.v3.assert (>= 4.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.1.0-alpha.6 | 0 | 11/12/2026 |
| 0.1.0-alpha.5 | 33 | 11/11/2026 |
| 0.1.0-alpha.4 | 41 | 11/11/2026 |
| 0.1.0-alpha.3 | 43 | 11/10/2026 |
| 0.1.0-alpha.2 | 43 | 11/10/2026 |
| 0.1.0-alpha.1 | 60 | 11/7/2026 |
Sixth alpha release of Akka.Durable. A caller can now wait for an entity's or a workflow's state, and watch it, without polling. `WaitForOutcome` is built on this and no longer polls. Akka.Durable is still a proof of concept, not an official Akka.NET project.
* **`WaitForStateAsync(until, cancellationToken)`** on `IDurableEntityRef` and `IWorkflowRef`. It returns the first snapshot whose state satisfies `until`. The token is required: it is the time limit, and when it fires the wait throws `OperationCanceledException`. When the state already satisfies `until`, it returns after one round trip. The predicate runs in the caller's process; the entity never sees it.
* **`WatchStateAsync(cancellationToken)`** on the same refs. An `IAsyncEnumerable` of snapshots: the current state first, then one after each later write that holds events. A slow reader gets the newest snapshot it has not read. For a workflow, the stream ends after the finished snapshot.
* **The guarantee.** On subscribing you get the current state, and then one snapshot after each later write that holds events, in order, each with the sequence number `GetStateAsync` would return at that moment. A snapshot is sent only after its events are journaled and its `Run` effects have finished. When the entity stops, passivates, restarts or moves, the subscription registers again by itself and goes on from the state the entity has then, so states in that time can be missed. This is a live, best-effort push held in memory, not durable delivery: nothing is journaled or sent again, and a reaction that must happen belongs in an effect.
* **`WaitForOutcome(cancellationToken)`** no longer polls. It waits on the subscription. `pollEvery` is removed, and the token is required.
* **Removed: `CommittedEvent<TEvent>` and `EntityUpdate<TState, TEvent>`.** Nothing used them. The event type stays on `IDurableEntityRef`.
**What you change from 0.1.0-alpha.5:** `WaitForOutcome(pollEvery, token)` becomes `WaitForOutcome(token)`, and a call without a token now needs one. Remove any use of `CommittedEvent<TEvent>` or `EntityUpdate<TState, TEvent>`. A loop that reads `GetStateAsync` until the state changes can become one `WaitForStateAsync`. Nothing stored changes: a subscription writes nothing to the journal, the snapshot store or the reminder store. During a rolling upgrade, a subscription to an entity on a node that still runs 0.1.0-alpha.5 does not connect until that node is upgraded, so a wait runs to its token. Upgrade every node before you rely on a subscription.
Not yet implemented: delivery of a workflow's outcome to the entity or workflow that started it, child workflows, a scenario test kit for workflows, event subscriptions, entity contracts and proxies, source generation, and snapshot retention tests.