Ducky

2.0 preview .NET 11

Blazor state you can explain to a duck.

Ducky is a small, strict Redux store for .NET and Blazor. Slices, effects, persistence, prerender handoff, cross-tab sync and Redux DevTools follow the same rules in every render mode, and every promise it makes is a named test.

The duck asks: So what happens when two dispatches race?

One dispatcher. One action at a time.

Every action goes through one queue, and a single drainer reduces it. Reducers never run concurrently, actions keep their order, and every committed snapshot comes from one commit, so no reader sees torn state.

await DispatchAsync completes once the action is reduced, so you read your own write. It returns a DispatchResult and never faults.

// generated: store.Dispatch(new Rename("Ada"))
store.Rename("Ada");

// completes once the action is reduced
var result = await store.RenameAsync("Grace");

var name = store.State.Get<Greeting>().Name; // "Grace"

The duck asks: The page prerendered. Does my data load twice?

Load once, in every render mode.

Mark the slice Persist<T>() and Prerender<T>(). The prerendered page hands its state to the interactive store before the first interactive render, and your load effect asks one question: was this slice already restored?

The same rule holds on WebAssembly, Interactive Server, Interactive Auto and static SSR.

public sealed class LoadCatalog(ICatalogApi api)
    : Effect<StoreInitialized>
{
    public override async Task Handle(
        StoreInitialized action,
        EffectContext context,
        CancellationToken cancellationToken)
    {
        // Storage or the prerender seed already restored it:
        // don't load it again.
        if (context.State.WasRestored<CatalogState>())
        {
            return;
        }

        context.Dispatch(new CatalogLoaded(
            await api.GetProductsAsync(cancellationToken)));
    }
}

The duck asks: Your user just opened a second tab. Now what?

Tabs converge. Nothing echoes.

Turn on SyncAcrossTabs for a localStorage slice and a change in one tab reaches the others. A value received from another tab is never written back, even when two processes serialize the same state in different orders.

Sign out in one tab and ClearPersistedState resets the slice everywhere.

public static DuckyBuilder AddSyncedPreferences(
    DuckyBuilder ducky) => ducky
    .UseJson(DocsJson.Default)
    .AddSlice<PreferencesSlice>()
    .Persist<PreferencesSlice>(options =>
        options.SyncAcrossTabs = true); // localStorage only

The duck asks: Trimmed and AOT-compiled. Still works?

No reflection to trim away.

Source generators write the registration, the dispatch helpers and the analyzers. Persistence serializes through each slice's JsonTypeInfo. Every runtime library builds with zero IL2xxx and IL3xxx warnings.

CI publishes a NativeAOT binary and a trimmed AOT WebAssembly app and runs both.

// Persistence serializes each state through its declared
// type's JsonTypeInfo: trim- and AOT-safe, no reflection.
[JsonSerializable(typeof(Preferences))]
[JsonSerializable(typeof(Basket))]
public sealed partial class DocsJson : JsonSerializerContext;

The duck asks: Fine. How do you test any of it?

Given, when, then. No browser required.

Ducky.Testing tests a slice in three lines, runs one effect against stub services, or spins up a whole TestStore you can seed, dispatch into and settle.

Every snippet on this page comes from a compiled, tested file in the repository.

[Fact]
public void ThemeChanged_NewTheme_Applied() =>
    SliceTest.For<SettingsSlice, Settings>()
        .Given(new Settings("light", FontSize: 14))
        .When(new ThemeChanged("dark"))
        .Then(new Settings("dark", FontSize: 14));

They type faster than your API answers. Who wins?

The newest request wins. The stale one can't speak.

  1. You search for Paris. Run 1 starts on a slow connection.
  2. You ask again. Run 2 supersedes run 1.
  3. Run 1 ignores its cancellation token and keeps going.
  4. Run 2 answers first. Paris is 14°C.
  5. The old answer is still on its way. It says 11°C.

A JavaScript model of Concurrency.Switch with demonstration values. Your scroll is its clock, so scroll back and it un-happens.

Paris
14°C
State v
2
Dropped
1
The action log of the race
ActionOriginResult
LoadForecast("Paris")LocalReduced
ForecastLoading("Paris")EffectReduced
LoadForecast("Paris")LocalReduced
ForecastLoading("Paris")EffectReduced
ForecastLoaded("Paris")EffectReduced
ForecastLoaded("Paris") stale runEffectDropped

Dropped.

Run 1 answered late, and Ducky refused it. Paris stays 14°C.

One policy, declared on the effect.

Effects declare a concurrency policy. With Switch, a newer request for the same key cancels the running one, and a superseded run that ignores its token still can't dispatch: its late result is dropped, typed and counted.

Other keys load side by side.

public sealed class LoadForecastEffect(IWeatherApi api)
    : Effect<LoadForecast>
{
    // A newer LoadForecast for the same city cancels the running
    // one; other cities load side by side.
    public override Concurrency Policy => Concurrency.Switch;
    protected override object? ConcurrencyKey(
        LoadForecast action) => action.City;
    public override Task Handle(
        LoadForecast action,
        EffectContext context,
        CancellationToken cancellationToken) =>
        context.Run(
            started: new ForecastLoading(action.City),
            work: token =>
                api.GetForecastAsync(action.City, token),
            succeeded: forecast => new ForecastLoaded(forecast),
            failed: exception => new ForecastFailed(
                action.City, exception.Message),
            cancellationToken);
}

The whole API fits on one desk.

State is an immutable record. Reducers are pure functions on it. The generator writes the registration and the dispatch helpers, so there is nothing to scan and nothing to wire by hand.

public sealed record Greeting(string Name);

[DuckyAction]
public sealed record Rename(string Name);

public sealed class GreetingSlice : Slice<Greeting>
{
    public GreetingSlice() => On<Rename>((state, action) => state with { Name = action.Name });

    protected override Greeting Initial => new("world");
}

[DuckyAction] asks the generator for store.Rename("Ada") and await store.RenameAsync("Ada").

Watch the dispatcher work.

Press anything, as fast as you like. Actions queue, and one drainer reduces them in order. Ask for Paris twice: the first run is superseded, and its late answer is dropped.

State v6

Count2

Paris14°C

Oslo6°C

Queue0

#ActionOriginResult
11ForecastLoaded("Oslo")EffectReduced
10ForecastLoaded("Paris")EffectReduced
9ForecastLoaded("Paris") stale runEffectDropped
8ForecastLoading("Oslo")EffectReduced
7LoadForecast("Oslo")LocalReduced
6ForecastLoading("Paris")EffectReduced
5LoadForecast("Paris")LocalReduced
4IncrementLocalReduced
3ForecastLoading("Paris")EffectReduced
2LoadForecast("Paris")LocalReduced
1IncrementLocalReduced

A JavaScript model of the store, slowed to one beat per action so you can follow it. The real one is C#. Open the playground

A shop that explains itself.

Rubber Duck Supply Co. is a small Blazor WebAssembly shop built only from Ducky, running in your browser. Switch on X-ray and every part names the feature behind it and opens the code that runs it.

The playground with X-ray on: the search, the colour filters, the duck shelf and the basket, each outlined and tagged with the Ducky feature that runs it (Switch, EntityState and selectors, Persist and SyncAcrossTabs, Exhaust), and the inspector tape along the bottom.

Try to break it

Type fast in the search
Concurrency.Switch cancels the run a newer keystroke overtakes, so a slow answer never lands late.
Press Pay three times
Concurrency.Exhaust lets one payment through and drops the other runs.
Open a second tab
The basket follows: Persist with SyncAcrossTabs, and it survives a reload.
Add an eleventh duck
A middleware vetoes it and DispatchAsync says so: DispatchResult.Vetoed.
Open the playground

Same rule in every render mode.

Blazor has five places your state can live, and they disagree about storage, lifetime and prerender. Ducky picks the right behaviour for each one, so your slices and effects don't change.

HostStoreBrowser storageServer storagePrerender seedCross-tabDevTools
WebAssemblyone per appread at init, written on the next turnnot usedtaken at inityesyes
Interactive Serverone per circuitwritten 250 ms after a change, retried after a disconnectIDistributedCache, flushed when the circuit endstaken before the first renderyesyes
Interactive Autoa circuit store and a WebAssembly storesame keys, each write reaches the other storecircuit sidewhichever side startsyes, between both storesyes
Static SSRone per requestnot usedread at init, written throughnonenono
Prerender passone per request, thrown awaynot usedas static SSRwritten from the idle storenono

Condensed from Render modes and the load rule, where every cell has its details.

Built on .NET 11, not around it.

.NET persists component state across prerender and circuit pauses. Ducky's prerender handoff uses that same mechanism. What Blazor leaves to you is everything around it.

Slice<T> On<TAction>
A store: pure reducers, one dispatcher, atomic commits across slices.
Concurrency.Switch
Effects with Merge, Switch, Exhaust and Queue policies, per-key cancellation, and failures you can see.
Persist<T>()
localStorage, sessionStorage or IDistributedCache, versioned with migrations, scoped per user.
SyncAcrossTabs
Tabs converge without echoes.
UseDevTools()
Redux DevTools: action log, state diff, time travel to the exact typed snapshot.
SliceTest EffectTest
Slice, effect and whole-store tests with TestStore, no browser.

The duck checks the receipts.

The specification states 32 invariants. Each one is enforced in exactly one place and has named tests, and a CI gate runs them on every change. The build fails when any of these breaks.

Read the specification

  • 100%line and branch coverage of every library
  • 100%Stryker mutation score of all seven projects, measured before the release candidate; the build breaks below 85%
  • 0IL2xxx and IL3xxx warnings, with NativeAOT and trimmed WebAssembly smoke runs
  • 32invariants, each with named tests, including linearizability and property tests
  • 64diagnostic pages: every configuration error is coded and says how to fix it
  • 3browser engines run the Playwright end-to-end suite: Chromium, Firefox, WebKit

Coming from somewhere else?

Step-by-step guides map what you have to Ducky 2.0. How Ducky compares sets them side by side, including where the others are ahead.

Explained. Ship it.