Skip to content
NanoFlags
Start free

SDKs

Java SDK

The io.nanoflags:nanoflags-java artifact 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

build.gradle.kts
dependencies {
    implementation("io.nanoflags:nanoflags-java:0.2.0")
    implementation("io.nanoflags:nanoflags-java-openfeature:0.2.0")   // optional: OpenFeature provider
}
pom.xml
<dependency>
  <groupId>io.nanoflags</groupId>
  <artifactId>nanoflags-java</artifactId>
  <version>0.2.0</version>
</dependency>
  • Published on Maven Central as io.nanoflags:nanoflags-java 0.2.0 and io.nanoflags:nanoflags-java-openfeature 0.2.0. Java 11 or newer (tested on 11, 17 and 21).
  • No runtime dependencies: HTTP and the WebSocket use the JDK's java.net.http. Ed25519 uses the JDK provider on Java 15+ and a built-in RFC 8032 verifier on Java 11 to 14.
  • Packages io.nanoflags.server (the client) and io.nanoflags.server.openfeature (the provider). The engine in io.nanoflags.server.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.
  • Apache-2.0. Source in nanoflags-sdk/java. Android apps use the Android and Kotlin SDK instead (client keys, lifecycle, Compose).

Quickstart

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

App.java
import io.nanoflags.server.NanoFlagsClient;
import io.nanoflags.server.NanoFlagsOptions;
import java.time.Duration;
import java.util.Map;

NanoFlagsClient flags = NanoFlagsClient.create(
    System.getenv("NANOFLAGS_SDK_KEY"),                          // nf_srv_… (server view)
    NanoFlagsOptions.builder().service("checkout-api").build());  // shown in "which revision is each service running"

flags.onError(e -> log.warn("nanoflags {}: {}", e.code(), e.getMessage()));

if (!flags.waitForReady(Duration.ofSeconds(5))) {                // never throws
    log.warn("flags not loaded yet ({}): evaluations return their fallbacks", flags.lastError());
}

Map<String, Object> user = Map.of("key", "user-42", "plan", "pro", "country", "SA");
if (flags.boolVariation("new-checkout", user, false)) {
    // ...
}

flags.close();                                                    // on shutdown (it is AutoCloseable)
  • 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 listener is registered; 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).

Typed variations

Each variation takes the flag key, the context and the fallback. The context is a Map<String, ?>; "key" is the identity used for percentage rollouts. Values may be strings, booleans, any Number, null, collections, arrays and maps.

java
boolean 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, Map.of("cols", 3));   // null, Boolean, Double, String, List, Map

Map<String, Object> every = flags.allFlags(user);                           // records no telemetry
MethodReturns
boolVariation(key, context, fallback)a boolean
stringVariation · doubleVariationa String, a finite double
intVariation · longVariationa whole number
jsonVariation(key, context, fallback)plain Java data: null, Boolean, Double, String, List, Map (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 FLAG_NOT_FOUND or ERROR). A disabled flag is not a fallback case: it returns the flag's configured off value.

Details and reasons

java
EvaluationDetail<Boolean> d = flags.boolVariationDetail("new-checkout", user, false);
d.value();       // true
d.reason();      // RULE_MATCH
d.ruleId();      // "beta"
d.revision();    // 63
d.trace().forEach(step -> System.out.println(step));   // the same steps the dashboard shows
AccessorMeaning
value()The value served (your fallback in the fallback cases).
reason()RULE_MATCH, DEFAULT (no rule matched), OFF (flag disabled), FLAG_NOT_FOUND, ERROR (wrong type or malformed configuration)
ruleIndex() · ruleId()The matching rule (zero-based index, -1 without one) 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 listeners

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.

java
Subscription sub = flags.onChange(e ->
    log.info("now on r{} (was r{}) via {}", e.revision(), e.previousRevision(), e.transport()));

flags.onStatus(s -> log.info("nanoflags status: {}", s));   // NOT_READY, READY or STALE

sub.close();                                                // unregister
AccessorMeaning
revision() · previousRevision()The new revision and the one it replaced (-1 for the first).
checksum()Checksum of the new configuration ("" when unknown, for example a bootstrap bundle).
source()NETWORK, STORE or BOOTSTRAP
transport()LIVE (pushed), STREAM (fetched after a server-sent-events notice) or POLL
latency()An Optional<Duration> from the database commit to this event, for pushed revisions that carry their commit time. It compares two clocks.
  • Listeners run one at a time, in order, on a thread of the client. Keep them short; a listener that throws never breaks the client. Each on… method returns a Subscription to close.
  • 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

java
flags.ready().thenAccept(ok -> log.info("configuration in use: {}", ok));   // CompletableFuture<Boolean>, never fails

flags.status();      // NOT_READY | READY | STALE
flags.revision();    // revision in use, or -1
flags.transport();   // LIVE | STREAM | POLL
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. waitForReady(Duration) blocks at most that long. Neither throws.
  • 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). NOT_READY: 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).

java
import io.nanoflags.server.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;

NanoFlagsOptions options = NanoFlagsOptions.builder()
    .service("checkout-api")
    .store(new FileStore(Path.of("/var/cache/app/flags.json")))   // keep the last good bundle across restarts
    .build();

// Or start from a bundle you ship, served until the edge answers:
NanoFlagsOptions offline = NanoFlagsOptions.builder()
    .bootstrapJson(Files.readString(Path.of("flags-bootstrap.json")))
    .build();
  • FileStore writes atomically, with owner-only permissions where POSIX permissions exist. A restored copy is verified again before it is used. Implement Store to keep it elsewhere.
  • bootstrap(Bundle) and bootstrapJson(String) take a configuration you ship; an invalid one is ignored and reported with code INVALID_BUNDLE.
  • 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 artifact (NanoFlagsOptions.OFFICIAL_SIGNING_KEYS), and unsigned bundles are refused. The signed bytes are hashed exactly as served.

java
import io.nanoflags.server.Jwk;
import io.nanoflags.server.VerifyOptions;

// Self-hosted or proxied edge: pin your keys and require signatures
NanoFlagsOptions options = NanoFlagsOptions.builder()
    .baseUrl("https://flags.internal.example")
    .verify(VerifyOptions.builder()
        .publicKey(Jwk.ed25519("…base64url public key…", "k1"))
        .require(true)
        .build())
    .build();
  • A bundle that fails verification is not used: the previous one stays, and onError receives 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 pass verify(…); withoutVerification() turns it off explicitly.
  • A bundle written for a newer evaluation engine than NanoFlagsClient.SUPPORTED_ENGINE_VERSION is refused (code ENGINE) and the current configuration stays: upgrade the artifact. 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"}).

java
import io.nanoflags.server.NanoFlagsOptions.EventsOptions;

NanoFlagsOptions options = NanoFlagsOptions.builder()
    .events(EventsOptions.builder()
        .sampleRate(0.05)
        .redact(ctx -> Map.of("plan", ctx.getOrDefault("plan", "unknown")))   // what leaves the process
        .build())
    .build();

NanoFlagsOptions quiet = NanoFlagsOptions.builder().events(EventsOptions.disabled()).build();   // no telemetry at all

redact receives a copy of the evaluation context and returns the map that is sent instead of the default. EventsOptions.disabled() turns telemetry off, the service report included. flush() 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.

java
SessionEvaluator s = flags.session(request.getHeader(NanoFlagsClient.SESSION_HEADER));   // or session(token, "checkout-api")
s.boolVariation("checkout-v2", Map.of("key", userId), false); // session bundle while active
s.isActive(); s.id(); s.expiresAt(); s.revision();

Per request, without passing the evaluator around: TestSessions holds the current session per thread. The SDK has no servlet dependency; a filter is a few lines:

NanoFlagsSessionFilter.java
public final class NanoFlagsSessionFilter implements Filter {        // jakarta.servlet or javax.servlet
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        try (TestSessions.Scope scope = TestSessions.open(((HttpServletRequest) req).getHeader(TestSessions.HEADER))) {
            TestSessions.flagsFor(flags);                             // resolve once, before the handler runs
            chain.doFilter(req, res);
        }
    }
}

// anywhere in the request
boolean v2 = TestSessions.flagsFor(flags).boolVariation("checkout-v2", Map.of("key", userId), false);
HttpRequest call = TestSessions.propagate(HttpRequest.newBuilder(pricingUri)).GET().build(); // the next service joins
executor.submit(TestSessions.wrap(task));                            // hand the session to another thread
TestSessions.withSession(job.sessionToken(), () -> process(job));    // queues, jobs and tests
APIDescription
client.session(token[, service]) · sessionAsync(...)Resolves the session (GET /v1/session) and returns a SessionEvaluator; service is sent as X-NanoFlags-Service (default: the client's service).
SessionEvaluatorThe client's variation methods, plus isActive(), id(), expiresAt(), revision().
TestSessions.open(token) · withSession(token, fn)Makes token the current session of this thread (Scope is AutoCloseable and restores the previous one); an absent or malformed token runs outside any session.
TestSessions.flagsFor(client[, service])The current request's evaluator, resolved once per scope and client; outside a session it behaves like the client.
currentSession() · sessionHeaders() · propagate(builder)The current token (or null); {x-nanoflags-session: token} (or empty); adds the header to a java.net.http request.
TestSessions.wrap(Runnable / Callable)Runs work on another thread inside the current session.
NanoFlagsClient.SESSION_HEADER · 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

build.gradle.kts
dependencies { implementation("io.nanoflags:nanoflags-java-openfeature:0.2.0") }
java
import dev.openfeature.sdk.*;
import io.nanoflags.server.NanoFlagsClient;
import io.nanoflags.server.openfeature.NanoFlagsProvider;

NanoFlagsClient flags = NanoFlagsClient.create(System.getenv("NANOFLAGS_SDK_KEY"));
OpenFeatureAPI api = OpenFeatureAPI.getInstance();
api.setProviderAndWait(NanoFlagsProvider.builder(flags).closeClient(true).build());

Client client = api.getClient();
boolean on = client.getBooleanValue("new-checkout", false,
    new ImmutableContext("user-42", Map.of("plan", new Value("pro"))));
  • For the official Java SDK (dev.openfeature:sdk 1.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.
  • Builder options: closeClient(true) closes the NanoFlags client when OpenFeature shuts the provider down; initTimeout(Duration) bounds initialisation (default 10 s).

Options

OptionDefaultDescription
baseUrl(url)https://edge.nanoflags.ioEdge URL.
service(name)"unknown"The name this process reports under.
httpClient(HttpClient)SDK-createdUses ProxySelector.getDefault() (honours https.proxyHost).
pollInterval(d) · livePollInterval(d)30 s · 5 minDuration.ZERO disables polling.
live(bool) · streaming(bool)trueTurn the WebSocket or server-sent events off.
store(Store) · bootstrap(Bundle) · bootstrapJson(String)noneSee Last good config.
verify(VerifyOptions) · withoutVerification()on for the hosted edgeSee Signature verification.
events(EventsOptions)10 % sampledSee Telemetry.
requestTimeout(d) · liveConnectTimeout(d)10 s · 10 sHTTP request and WebSocket connect timeouts.
logger(System.Logger)io.nanoflags.serverDebug level only.

Error codes

Background failures reach onError as NanoFlagsException with a code() (and httpStatus() where relevant): NETWORK, UNAUTHORIZED, HTTP, INVALID_BUNDLE, STORE, CONFIG, SIGNATURE, SESSION, ENGINE, ENVIRONMENT_DELETED. They never change the configuration in use, and nothing is thrown from a variation call. The meanings match the JavaScript SDK.

Closing and shutdown

java
Runtime.getRuntime().addShutdownHook(new Thread(flags::close));

// or scope it
try (NanoFlagsClient job = NanoFlagsClient.create(sdkKey, NanoFlagsOptions.builder().service("nightly-job").build())) {
    run(job);
}
  • close() sends queued telemetry (best effort), stops every background thread and waits for them. It is idempotent.
  • After close(), variations keep working on the last configuration; it just stops updating. refresh() revalidates now and throws NanoFlagsException when that request failed.
  • Background threads are daemon threads, so they don't keep the JVM alive.

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. The default HTTP client follows ProxySelector.getDefault(), so set https.proxyHost and https.proxyPort, or pass your own HttpClient. 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 ENVIRONMENT_DELETED. The edge closed the socket with code 4004. The client stops reconnecting and keeps the last configuration as STALE; replace the key.
  5. Seeing what the client does. Pass a System.Logger with logger(…), or enable debug logging for io.nanoflags.server.
Other languages
Native server SDKs also exist for Python, Go, .NET, PHP and Ruby. Other languages can read NanoFlags flags through an OpenFeature OFREP provider.