SDKs
.NET SDK
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.On this page
Install
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.0andnet8.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) andNanoFlags.OpenFeature(the provider). The engine inNanoFlags.Engineis 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.
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
Createreturns. An error from that first attempt can arrive before your handler is attached;LastErroralways holds the latest one. - Browser keys (
nf_pub_…) work too but only see client-exposed flags.CreatethrowsNanoFlagsException(codeConfig) only for an empty key or a base URL that is not http(s).
ASP.NET Core
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.
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| Method | Returns |
|---|---|
BoolVariation(key, context, fallback) | a bool |
StringVariation · DoubleVariation | a string, a finite double |
IntVariation · LongVariation | a 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
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);| Property | Meaning |
|---|---|
Value | The value served (your fallback in the fallback cases). |
Reason | RuleMatch, Default (no rule matched), Off (flag disabled), FlagNotFound, Error (wrong type or malformed configuration) |
RuleIndex · RuleId | The matching rule (zero-based index) and its id. |
InRollout · Bucket | For percentage rollouts: whether the key is inside the allocation, and its bucket (0 to 99.99). |
Revision | The configuration revision the result came from. |
Trace | A list of TraceStep explaining the decision step by step. |
Error | Why 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.
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| Property | Meaning |
|---|---|
Revision · PreviousRevision | The new revision and the one it replaced (-1 for the first). |
Checksum | Checksum of the new configuration. |
Source | Network, Store or Bootstrap |
Transport | Live (pushed), Stream (fetched after a server-sent-events notice) or Poll |
Latency | A 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/bundlewithETagevery 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-Stalenever moves the client backwards.
Readiness and status
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 nullReadycompletes once the first load attempt has finished:truewhen a configuration is in use.WaitForReadyAsync(timeout)andWaitForReady(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).
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") };FileStorewrites atomically, with owner-only permissions on Unix. A restored copy is verified again before it is used. ImplementIStoreto keep it elsewhere.Bootstrap(aBundle) andBootstrapJsontake a configuration you ship; an invalid one is ignored and reported with codeInvalidBundle.- 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.
// 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
Erroris raised with codeSignature. - A bundle naming an unknown key id (a key rotation) makes the client load
GET /v1/keysonce, at most once a minute.FetchKeys = trueloads 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 = trueturns it off explicitly. - A bundle written for a newer evaluation engine than
NanoFlagsClient.SupportedEngineVersionis refused (codeEngine) 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"}).
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 allRedact 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.
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:
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); /* … */ });| API | Description |
|---|---|
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. |
SessionEvaluator | The client's variation methods, plus IsActive, Id, ExpiresAt, Revision. |
NanoFlagsSession.Begin(token) · Run · RunAsync | Makes 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). |
NanoFlagsSessionHandler | A 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
dotnet add package NanoFlags.OpenFeatureusing 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 (
OpenFeature2.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 calledkey). 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 carriesrevisionandruleIndex. - The provider emits
PROVIDER_READY,PROVIDER_STALE,PROVIDER_ERRORandPROVIDER_CONFIGURATION_CHANGEDwith the keys of the flags that changed. - Constructor:
new NanoFlagsProvider(client, closeClient: false, initTimeout: null).closeClient: truecloses the NanoFlags client on provider shutdown;initTimeoutbounds initialisation (default 10 s).
Options
| Property | Default | Description |
|---|---|---|
BaseUrl | https://edge.nanoflags.io | Edge URL. |
Service | "unknown" | The name this process reports under. |
HttpClient | SDK-created | Uses the system proxy settings (for example HTTPS_PROXY). |
PollInterval · LivePollInterval | 30 s · 5 min | TimeSpan.Zero disables polling. |
Live · Streaming | true | Turn the WebSocket or server-sent events off. |
Store · Bootstrap · BootstrapJson | none | See Last good config. |
Verify · DisableVerification | on for the hosted edge | See Signature verification. |
Events | 10 % sampled | See Telemetry. |
RequestTimeout · LiveConnectTimeout | 10 s · 10 s | HTTP request and WebSocket connect timeouts. |
Logger | none | An 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
await flags.CloseAsync(); // or flags.Dispose()
// or scope it
using (var job = NanoFlagsClient.Create(sdkKey, new NanoFlagsOptions { Service = "nightly-job" }))
{
Run(job);
}CloseAsync()andDispose()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 throwsNanoFlagsExceptionwhen that request failed.
Troubleshooting
- Every variation returns the fallback. Check
StatusandLastError.Unauthorizedmeans the key was rejected; with a browser key (nf_pub_…) only client-exposed flags are delivered. - Behind a proxy or with a custom handler. The SDK-created
HttpClientuses the system proxy settings; pass your ownHttpClientfor anything else. If WebSocket upgrades are blocked,TransportshowsStreamorPoll. - Errors with code
Signature. The bundle did not verify and was not used. With a customBaseUrl, pin that edge's keys withVerifyOptions. - Errors with code
EnvironmentDeleted. The edge closed the socket with code 4004. The client stops reconnecting and keeps the last configuration asStale; replace the key.