Acta. Durable execution for .NET

learn actakeep another system in sync

How to keep a value across retries

A durable variable stores a value with the job the first time it is computed, and every later attempt reads the same value.

A how-to for Acta, durable execution for .NET. New to Acta? Run your first durable job in five minutes.

Checked every release learn/200-durable-execution/203-durable-variable
Read as

1Compute the value once and read it back on every attempt

Pin the sync window once: GetOrSet stores it on the first pass and replays it on the retry, so the window can't shift between attempts.

durable-variable.csexcerpt
public sealed class SyncUsersJob
{
    private static int _attempts;

    [Job("sync-users", MaxAttempts = 2, Backoff = "2s")]
    public async Task Handle(SyncUsers input, JobContext context, CancellationToken ct)
    {
        var syncedAt = await context.GetOrSetVariableAsync("synced-at-utc", () => DateTime.UtcNow, ct);
        Console.WriteLine($"[{input.Source}] syncing changes as of {syncedAt:HH:mm:ss.fff} UTC");

        // Fail the first attempt; the same timestamp comes back on the retry.
        if (Interlocked.Increment(ref _attempts) == 1)
        {
            Console.WriteLine($"[{input.Source}] transient failure - retrying...");
            throw new InvalidOperationException("simulated transient failure");
        }

        Console.WriteLine($"[{input.Source}] sync complete (window pinned at {syncedAt:HH:mm:ss.fff} UTC)");
    }
}

2Run it and check the output

From a clone of the Acta repository, with the .NET 10 SDK:

Terminal
dotnet run --project learn/200-durable-execution/203-durable-variable
Its output must contain
[crm] transient failure - retrying...
[crm] sync complete (window pinned at

Checked every release. Before each release, Acta Verify runs this program and checks that its output contains these lines.

This page shows the code. The rules it relies on, starting with the handler running again from its first line, are in the handler contract.

The whole program

Every file of learn/200-durable-execution/203-durable-variable, as it is compiled.

UseLocalDatabase is a helper of the Acta repository, not of the packages. In your own app, register the database with UseSqlite, UsePostgres or UseSqlServer, as in how to run your first job.

durable-variable.cs59 lines
durable-variable.cs
// How to keep a value across retries
// A durable variable stores a value with the job the first time it is computed, and every later attempt reads the
// same value.
using Acta;
using Acta.Learn.DurableVariable;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.UseActa(j =>
{
    j.UseLocalDatabase(builder.Configuration);
    j.Run<DurableVariableJobs>("durable-variable");
});

// Handler fails once to show retry; quiet the framework failure warning/alert.
builder.Logging.AddFilter("Acta", LogLevel.Error);

using var host = builder.Build();
await host.StartAsync();

var jobs = host.Services.GetRequiredService<IJobs>();

await jobs.EnqueueAsync(new SyncUsers("crm"));
Console.WriteLine("Enqueued. Worker is running - press Ctrl+C to stop.");

await host.WaitForShutdownAsync();
await host.StopAsync();

namespace Acta.Learn.DurableVariable
{
    public sealed record SyncUsers(string Source);

    public sealed class SyncUsersJob
    {
        private static int _attempts;

        [Job("sync-users", MaxAttempts = 2, Backoff = "2s")]
        public async Task Handle(SyncUsers input, JobContext context, CancellationToken ct)
        {
            // learn: Compute the value once and read it back on every attempt
            // Pin the sync window once: GetOrSet stores it on the first pass and replays it on the retry, so the window can't shift between attempts.
            var syncedAt = await context.GetOrSetVariableAsync("synced-at-utc", () => DateTime.UtcNow, ct);
            // learn: end
            Console.WriteLine($"[{input.Source}] syncing changes as of {syncedAt:HH:mm:ss.fff} UTC");

            // Fail the first attempt; the same timestamp comes back on the retry.
            if (Interlocked.Increment(ref _attempts) == 1)
            {
                Console.WriteLine($"[{input.Source}] transient failure - retrying...");
                throw new InvalidOperationException("simulated transient failure");
            }

            Console.WriteLine($"[{input.Source}] sync complete (window pinned at {syncedAt:HH:mm:ss.fff} UTC)");
        }
    }
}

Where to go next

New to Acta?

Acta is durable execution for .NET: workflows and jobs that survive restarts, as a library inside your application with its durable state in your SQL database.