Skip to content
NanoFlags
Start free

SDKs

.NET SDK

The NanoFlags package evaluates flags locally, without I/O, against a signed, in-memory configuration that it keeps current in the background over the live connection. Evaluations never throw and never block, and one client is safe to share between threads.

Install

sh
dotnet add package NanoFlags
dotnet add package NanoFlags.OpenFeature   # optional: OpenFeature provider
  • Published on NuGet as NanoFlags 0.2.0 and NanoFlags.OpenFeature 0.2.0. Targets netstandard2.0 and net8.0, so it runs on .NET 8 and newer as well as on .NET Framework and other .NET Standard 2.0 runtimes.
  • The only dependency is Microsoft.Extensions.Logging.Abstractions. Ed25519 is a self-contained RFC 8032 verifier, so no native or third-party crypto is needed.
  • Namespace NanoFlags (the client) and NanoFlags.OpenFeature (the provider). The engine in NanoFlags.Engine is a port of the NanoFlags engine, tested against the shared fixtures generated from the reference engine (21,998 evaluation cases), so it gives the same results as every other SDK. Number parsing and formatting are exact, so results do not depend on the runtime.
  • Apache-2.0. Source in nanoflags-sdk/dotnet.

Quickstart

Copy a server key (nf_srv_…) from Settings → SDK keys in the dashboard and keep it in an environment variable. Subscribe to Error right after creating the client, before you wait for readiness.

Program.cs
using NanoFlags;

var flags = NanoFlagsClient.Create(
    Environment.GetEnvironmentVariable("NANOFLAGS_SDK_KEY")!,   // nf_srv_… (server view)
    new NanoFlagsOptions { Service = "checkout-api" });         // shown in "which revision is each service running"

flags.Error += (_, e) => Console.Error.WriteLine($"nanoflags {e.Code}: {e.Message}");

if (!await flags.WaitForReadyAsync(TimeSpan.FromSeconds(5)))    // never throws
    Console.WriteLine($"flags not loaded yet ({flags.LastError?.Message}): evaluations return their fallbacks");

var user = new Dictionary<string, object?> { ["key"] = "user-42", ["plan"] = "pro", ["country"] = "SA" };
if (flags.BoolVariation("new-checkout", user, false))
{
    // ...
}

await flags.CloseAsync();                                       // on shutdown (or Dispose())
  • Create one client per SDK key at startup and share it: it is thread-safe. The base URL defaults to the hosted edge, https://edge.nanoflags.io.
  • The client starts loading as soon as Create returns. An error from that first attempt can arrive before your handler is attached; LastError always holds the latest one.
  • Browser keys (nf_pub_…) work too but only see client-exposed flags. Create throws NanoFlagsException (code Config) only for an empty key or a base URL that is not http(s).

ASP.NET Core

Program.cs
builder.Services.AddSingleton(_ =>
{
    var client = NanoFlagsClient.Create(
        builder.Configuration["NanoFlags:SdkKey"]!,
        new NanoFlagsOptions { Service = "web" });
    client.Error += (_, e) => Console.Error.WriteLine($"nanoflags {e.Code}: {e.Message}");
    return client;
});

// in a handler
app.MapGet("/checkout", (NanoFlagsClient flags, HttpContext http) =>
    flags.BoolVariation("new-checkout", new Dictionary<string, object?> { ["key"] = http.User.Identity?.Name }, false)
        ? Results.Ok("new") : Results.Ok("classic"));

Register the client as a singleton. The container disposes it at shutdown, which flushes telemetry and stops the background work. Pass an ILogger in NanoFlagsOptions.Logger to route its logs through your logging setup.

Typed variations

Each variation takes the flag key, the context and the fallback. The context is an IReadOnlyDictionary<string, object?> (a Dictionary<string, object?> works); "key" is the identity used for percentage rollouts. Values may be strings, booleans, any numeric type, null, sequences and dictionaries.

csharp
bool    enabled = flags.BoolVariation("new-checkout", user, false);
string  accent  = flags.StringVariation("accent", user, "blue");
double  ratio   = flags.DoubleVariation("sample-ratio", user, 0.1);
int     limit   = flags.IntVariation("rate-limit", user, 100);
long    quota   = flags.LongVariation("quota-bytes", user, 1_000_000L);
object? layout  = flags.JsonVariation("layout", user, null);   // null, bool, double, string, List<object?>, Dictionary<string, object?>

var every = flags.AllFlags(user);                               // records no telemetry
MethodReturns
BoolVariation(key, context, fallback)a bool
StringVariation · DoubleVariationa string, a finite double
IntVariation · LongVariationa whole number
JsonVariation(key, context, fallback)plain .NET data: null, bool, double, string, List<object?>, Dictionary<string, object?> (in configuration order)
JsonValueVariation(key, context, fallback)the same value as a JavaScript-typed JsonValue
…VariationDetail(key, context, fallback)an EvaluationDetail<T>, see Details and reasons
Evaluate(key, context, fallback)the engine result without a type check
AllFlags(context) · AllFlagsDetail(context)every flag of the loaded configuration (no telemetry)

You get your fallback when no configuration has loaded yet, when the flag is unknown, or when it serves a value of another type (reason FlagNotFound or Error). A disabled flag is not a fallback case: it returns the flag's configured off value.

Details and reasons

csharp
var d = flags.BoolVariationDetail("new-checkout", user, false);
Console.WriteLine($"{d.Value} {d.Reason} {d.RuleId} r{d.Revision}");   // True RuleMatch beta r63

foreach (var step in d.Trace)                                         // the same steps the dashboard shows
    Console.WriteLine(step);
PropertyMeaning
ValueThe value served (your fallback in the fallback cases).
ReasonRuleMatch, Default (no rule matched), Off (flag disabled), FlagNotFound, Error (wrong type or malformed configuration)
RuleIndex · RuleIdThe matching rule (zero-based index) and its id.
InRollout · BucketFor percentage rollouts: whether the key is inside the allocation, and its bucket (0 to 99.99).
RevisionThe configuration revision the result came from.
TraceA list of TraceStep explaining the decision step by step.
ErrorWhy Reason is Error.

Live updates and events

The client opens one WebSocket to wss://edge.nanoflags.io/v1/live (subprotocol nanoflags.v1, the key in the Authorization header, never in the URL). The edge pushes each published revision, already signed; the client verifies it and swaps it in atomically.

csharp
flags.Changed += (_, e) =>
    Console.WriteLine($"now on r{e.Revision} (was r{e.PreviousRevision}) via {e.Transport}, {e.Latency?.TotalMilliseconds} ms after commit");

flags.StatusChanged += (_, status) => Console.WriteLine($"nanoflags status: {status}");   // NotReady, Ready or Stale
PropertyMeaning
Revision · PreviousRevisionThe new revision and the one it replaced (-1 for the first).
ChecksumChecksum of the new configuration.
SourceNetwork, Store or Bootstrap
TransportLive (pushed), Stream (fetched after a server-sent-events notice) or Poll
LatencyA TimeSpan? from the database commit to this event, for pushed revisions that carry their commit time. It compares two clocks.
  • Handlers run one at a time, in order, on a thread of the client. Keep them short; a handler that throws never breaks the client. Detach with -=.
  • Fallbacks: if the socket cannot be opened, the client uses server-sent events (/v1/stream) and polls /v1/bundle with ETag every 30 s. While the socket is healthy, a safety poll runs every 5 minutes. Reconnects back off from 1 s up to 5 minutes, with jitter. See Transports for the protocol.
  • A pushed revision is never replaced by an older HTTP answer, and an edge answer marked X-NanoFlags-Stale never moves the client backwards.

Readiness and status

csharp
bool inUse = await flags.Ready;                          // Task<bool>: completes after the first load attempt, never faults
bool ok = flags.WaitForReady(TimeSpan.FromSeconds(5));   // synchronous variant

Status status = flags.Status;           // Status.NotReady | Status.Ready | Status.Stale
long revision = flags.Revision;         // revision in use, or -1
Transport transport = flags.Transport;  // Transport.Live | Transport.Stream | Transport.Poll
var lastError = flags.LastError;        // the error of the last failed request, or null
  • Ready completes once the first load attempt has finished: true when a configuration is in use. WaitForReadyAsync(timeout) and WaitForReady(timeout) bound the wait. None of them throws on failure.
  • Ready: the configuration is known to be current. Stale: a configuration is in use but is not known to be current (restored from the store, edge unreachable, environment deleted). NotReady: nothing is loaded and every variation returns its fallback.
  • Don't block a request on readiness. Wait once at start-up, with a short timeout, and let your fallbacks cover the rest.

Last good config and bootstrap

Once loaded, the last good configuration stays in use through network failures, rejected bundles and edge errors (Status becomes Stale).

csharp
var options = new NanoFlagsOptions
{
    Service = "checkout-api",
    Store = new FileStore("/var/cache/app/flags.json"),   // keep the last good bundle across restarts
};

// Or start from a bundle you ship, served until the edge answers:
var offline = new NanoFlagsOptions { BootstrapJson = File.ReadAllText("flags-bootstrap.json") };
  • FileStore writes atomically, with owner-only permissions on Unix. A restored copy is verified again before it is used. Implement IStore to keep it elsewhere.
  • Bootstrap (a Bundle) and BootstrapJson take a configuration you ship; an invalid one is ignored and reported with code InvalidBundle.
  • The store holds flag rules, never the SDK key.

Signature verification

Every bundle is checked (Ed25519, by key id) before it can replace the one in use: over polling, the live socket and the stored copy alike. With the default base URL this is on by default with the production keys embedded in the package (NanoFlagsOptions.OfficialSigningKeys), and unsigned bundles are refused. The signed bytes are hashed exactly as served.

csharp
// Self-hosted or proxied edge: pin your keys and require signatures
var options = new NanoFlagsOptions
{
    BaseUrl = "https://flags.internal.example",
    Verify = new VerifyOptions
    {
        PublicKeys = { Jwk.Ed25519("…base64url public key…", "k1") },
        Require = true,
    },
};
  • A bundle that fails verification is not used: the previous one stays, and Error is raised with code Signature.
  • A bundle naming an unknown key id (a key rotation) makes the client load GET /v1/keys once, at most once a minute. FetchKeys = true loads keys from the edge instead of pinning them; pinned keys are stronger.
  • Bundles are pinned to the first environment they were signed for. With another base URL, verification is off unless you set Verify; DisableVerification = true turns it off explicitly.
  • A bundle written for a newer evaluation engine than NanoFlagsClient.SupportedEngineVersion is refused (code Engine) and the current configuration stays: upgrade the package. The canonical string is described in Signatures.

Telemetry and redaction

A sampled 10 % of evaluations are sent every 10 s, plus a service report every 60 s. By default, context values never leave the process: a sampled event carries only the names of the attributes the flag's rules use, mapped to their type ({"plan": "string"}).

csharp
var options = new NanoFlagsOptions
{
    Events = new EventsOptions
    {
        SampleRate = 0.05,
        Redact = ctx => new Dictionary<string, object?> { ["plan"] = ctx.TryGetValue("plan", out var p) ? p : null },
    },
};

var quiet = new NanoFlagsOptions { Events = EventsOptions.Disabled };   // no telemetry at all

Redact receives a copy of the evaluation context and returns the dictionary that is sent instead of the default. EventsOptions.Disabled turns telemetry off, the service report included. FlushAsync() sends queued events now.

Test sessions

A shared test session, created in the dashboard (Scenarios → Shared test session), pins a configuration snapshot and a synthetic context to a token (nf_ts_…). A service that receives the token in the x-nanoflags-session header evaluates against that snapshot, with the session's context overlaid by the call's context (the call wins), for that request only. Sampled events from a session carry its id. Shared test sessions are part of the Scale plan.

csharp
var s = await flags.SessionAsync(Request.Headers[NanoFlagsClient.SessionHeader].FirstOrDefault()); // or (token, "checkout-api")
s.BoolVariation("checkout-v2", ctx, false); // session bundle while active
_ = (s.IsActive, s.Id, s.ExpiresAt, s.Revision);

Per request, without passing the evaluator around: NanoFlagsSession keeps the current session in an AsyncLocal that follows the request through awaits. ASP.NET Core needs no extra package; a few lines of middleware do:

Program.cs
app.Use(async (http, next) =>
{
    using (NanoFlagsSession.Begin(http.Request.Headers[NanoFlagsSession.Header].FirstOrDefault()))
    {
        await NanoFlagsSession.FlagsForAsync(flags); // resolve once, before the endpoint runs
        await next();
    }
});

app.MapGet("/cart", () => NanoFlagsSession.FlagsFor(flags).BoolVariation("checkout-v2", ctx, false));

// The next service joins the session: every request of this HttpClient carries the header.
builder.Services.AddHttpClient("pricing").AddHttpMessageHandler(() => new NanoFlagsSessionHandler());

// Queues, jobs and tests
await NanoFlagsSession.RunAsync(job.SessionToken, async () => { var f = await NanoFlagsSession.FlagsForAsync(flags); /* … */ });
APIDescription
client.SessionAsync(token, service?, ct) · Session(token, service?)Resolves the session (GET /v1/session) and returns a SessionEvaluator; service is sent as X-NanoFlags-Service (default: Service); ct ends only the wait.
SessionEvaluatorThe client's variation methods, plus IsActive, Id, ExpiresAt, Revision.
NanoFlagsSession.Begin(token) · Run · RunAsyncMakes token the current session of this async flow (disposing restores the previous one); an absent or malformed token runs outside any session.
NanoFlagsSession.FlagsForAsync(client, service?, ct)The current request's evaluator, resolved once per scope and client; outside a session it behaves like the client.
NanoFlagsSession.FlagsFor(client)Synchronous and never blocks: the evaluator resolved by FlagsForAsync, otherwise one that behaves like the client.
NanoFlagsSession.CurrentSession · Headers()The current token (or null); {x-nanoflags-session: token} (or empty).
NanoFlagsSessionHandlerA DelegatingHandler that adds the header to outgoing HttpClient requests inside a session.
NanoFlagsClient.SessionHeader · IsSessionToken(s)"x-nanoflags-session"; a token is 1 to 512 printable ASCII characters.
  • The edge is asked once per token and service, concurrent callers share the request, and the answer is cached until the session expires. Unknown tokens are remembered for 15 s, failed lookups (reported as error code Session) for 3 s.
  • It never throws: an absent, malformed, unknown, expired, revoked or not permitted token falls back to the normal configuration, and the evaluator behaves exactly like the client. When a session expires mid-flight, it turns inactive and evaluations continue on the published configuration. A newly published revision does not change an active session.
  • An unknown session is still propagated downstream: the next service decides for itself.
  • A session changes which snapshot and context an evaluation uses; it grants no data access and must not be used for authorization. Session bundles are not signed, so verification does not apply to them. A revoked session keeps working in a process that already cached it, until its expiry time.

OpenFeature provider

sh
dotnet add package NanoFlags.OpenFeature
csharp
using NanoFlags;
using NanoFlags.OpenFeature;
using OpenFeature;
using OpenFeature.Model;

var flags = NanoFlagsClient.Create(Environment.GetEnvironmentVariable("NANOFLAGS_SDK_KEY")!);
await Api.Instance.SetProviderAsync(new NanoFlagsProvider(flags, closeClient: true));

var client = Api.Instance.GetClient();
var on = await client.GetBooleanValueAsync("new-checkout", false,
    EvaluationContext.Builder().SetTargetingKey("user-42").Set("plan", "pro").Build());
  • For the official .NET SDK (OpenFeature 2.x). Evaluation stays local: the provider wraps the client above, so live updates, signatures and the last good config work the same.
  • The targeting key becomes the NanoFlags key (and wins over an attribute called key). Reasons: DISABLED, DEFAULT, TARGETING_MATCH, SPLIT (percentage rollouts). Errors: FLAG_NOT_FOUND, PROVIDER_NOT_READY, TYPE_MISMATCH, GENERAL. The variant is the rule id; flag metadata carries revision and ruleIndex.
  • The provider emits PROVIDER_READY, PROVIDER_STALE, PROVIDER_ERROR and PROVIDER_CONFIGURATION_CHANGED with the keys of the flags that changed.
  • Constructor: new NanoFlagsProvider(client, closeClient: false, initTimeout: null). closeClient: true closes the NanoFlags client on provider shutdown; initTimeout bounds initialisation (default 10 s).

Options

PropertyDefaultDescription
BaseUrlhttps://edge.nanoflags.ioEdge URL.
Service"unknown"The name this process reports under.
HttpClientSDK-createdUses the system proxy settings (for example HTTPS_PROXY).
PollInterval · LivePollInterval30 s · 5 minTimeSpan.Zero disables polling.
Live · StreamingtrueTurn the WebSocket or server-sent events off.
Store · Bootstrap · BootstrapJsonnoneSee Last good config.
Verify · DisableVerificationon for the hosted edgeSee Signature verification.
Events10 % sampledSee Telemetry.
RequestTimeout · LiveConnectTimeout10 s · 10 sHTTP request and WebSocket connect timeouts.
LoggernoneAn ILogger.

Error codes

Background failures raise Error with a NanoFlagsException that has a Code (and HttpStatus where relevant): Network, Unauthorized, Http, InvalidBundle, Store, Config, Signature, Session, Engine, EnvironmentDeleted. They never change the configuration in use, and nothing is thrown from a variation call. The meanings match the JavaScript SDK.

Closing and shutdown

csharp
await flags.CloseAsync();   // or flags.Dispose()

// or scope it
using (var job = NanoFlagsClient.Create(sdkKey, new NanoFlagsOptions { Service = "nightly-job" }))
{
    Run(job);
}
  • CloseAsync() and Dispose() send queued telemetry (best effort) and stop the background work. Both are idempotent.
  • After closing, variations keep working on the last configuration; it just stops updating. RefreshAsync() revalidates now and throws NanoFlagsException when that request failed.

Troubleshooting

  1. Every variation returns the fallback. Check Status and LastError. Unauthorized means the key was rejected; with a browser key (nf_pub_…) only client-exposed flags are delivered.
  2. Behind a proxy or with a custom handler. The SDK-created HttpClient uses the system proxy settings; pass your own HttpClient for anything else. If WebSocket upgrades are blocked, Transport shows Stream or Poll.
  3. Errors with code Signature. The bundle did not verify and was not used. With a custom BaseUrl, pin that edge's keys with VerifyOptions.
  4. Errors with code EnvironmentDeleted. The edge closed the socket with code 4004. The client stops reconnecting and keeps the last configuration as Stale; replace the key.
Other languages
Native server SDKs also exist for Python, Go, Java, PHP and Ruby. Other languages can read NanoFlags flags through an OpenFeature OFREP provider.