Skip to main content

Feature Flags in Spring Boot with OpenFeature and flagd: Targeting, Gradual Rollout and Failure Modes

Feature flags in Spring Boot 4.2 with the OpenFeature Java SDK and a real flagd daemon: typed flags, targeting rules, a sticky 10% rollout measured on 1000 users, live reload without a restart, what the app does when flagd dies, and how to test both flag states. Every output block comes from a committed transcript.

You merge the new checkout on Friday afternoon. It is behind an if, so it is safe to deploy. On Monday someone has to decide who gets it: the staff first, then the premium customers, then ten percent of everybody, then everybody. If every one of those steps is a redeploy, the if was not really buying you anything. A feature flag moves the decision out of the build and into data you can change while the application is running. This article builds that in Spring Boot 4.2 with OpenFeature (a vendor-neutral API for asking “is this flag on?”) and flagd (a small daemon that serves flag values from a JSON file). Everything is run against a real flagd process, and every output block below is copied from a file that a test or script wrote. You do not need to know either tool. The page starts from the idea, builds the smallest working example, and then spends most of its length on what goes wrong: the daemon being down, a typo in a key, and the default value you wrote in code turning out to be the one production runs on. The longer explanations are folded into collapsible sections so you can open only the ones you need.
Versions this was run against. Spring Boot 4.2.0 (the starter-parent jar is on Maven Central with a 19 Nov 2026 timestamp), JDK 25.0.5 (Temurin), OpenFeature Java SDK 1.23.0 (28 Sep 2026), flagd provider 0.15.0 (15 Oct 2026) and the flagd 0.19.0 daemon (built from the tagged Go module, which the Go module proxy lists as published 17 Nov 2026). The companion module is openfeature in the spring-boot-demo repository; ./scripts/run-all.sh regenerates every transcript quoted here.

A feature flag is an if whose answer is decided outside your deploy

Take the line if (newCheckout) { ... } else { ... }. Today newCheckout is a constant someone edits and ships. With a flag it becomes a question the running application asks: “is new-checkout on for this user, right now?” The answer comes from a flag service, so changing it needs no build. That splits two events that normally travel together. Deploying is putting code on servers. Releasing is letting users reach it. With a flag, code can ship dark on Friday, reach staff on Monday, reach ten percent on Tuesday, and be switched off in seconds if the error rate moves.
1. Deploynew checkout code shipsflag is off: nobody sees it2. Releaseflag on for 10% of usersnothing was redeployed3. Everyoneflag on for 100%still nothing redeployedProblem found?flip the flag offThe rollback is a data change, not a build: it takes seconds, not a pipeline run.That is the whole idea; everything below is about doing it safely.
The picture is the argument: three steps move forward without a build, and the red box is the reason people adopt flags at all. A rollback that is a data change is far less stressful than one that is a pipeline run.
For intermediate readers: the four kinds of flag and why they age differently A flag that hides unfinished work (a release flag) should live days or weeks and then be deleted. A flag that lets you gradually expose a change (a rollout flag) lives until it reaches 100%. A flag that switches off a misbehaving dependency (a kill switch) can live for years. A flag that shows different things to different customers (a permission or plan flag) is really product configuration. This module’s flags map onto them: new-checkout is a targeted release flag, payment-flow-v2 a percentage rollout, discount-percent a plan flag, banner-text and theme plain remote configuration. The practical consequence is in the last section: only the first two should have an expiry date in your head.
Going deeper

OpenFeature is the plug and flagd is one socket

Three names appear in every example, so fix them early.
  • OpenFeature is a specification and a set of SDKs. Your code calls client.getBooleanValue("new-checkout", false, context). That call looks the same whatever answers it. OpenFeature is an incubating project of the Cloud Native Computing Foundation (it reached that level in November 2023, per the CNCF project page).
  • A provider is the adapter that knows how to answer for one particular backend. It implements the SDK’s provider interface and nothing in your business code mentions it.
  • flagd is one such backend: a single Go binary that reads flag definitions from a file (or a URL, or a Kubernetes custom resource), evaluates them, and streams changes. The Java SDK reaches it through the flagd provider.
Your codeCheckoutFlagsOpenFeature clientgetBooleanDetails(…)ProviderFlagdProviderflagd daemongRPC on :8013flags.jsonwatched for editsOnly this box changes if you swap the flag backend.Your code never imports flagd. Moving to another provider (a vendor, a database,a different daemon) is a one-line change in FlagConfig, not a rewrite of every if.
Read the figure left to right. Everything to the left of the amber box is your code and a stable API; everything to the right can be replaced. That is why this article puts the keys and defaults in a single class (next section) and keeps the choice of provider in a single configuration class.
For intermediate readers: the words you will see in output (reasons) and what each means Every evaluation can return more than a value. Asking for details instead of a value returns the variant that was chosen and a reason. These are the reasons that appear in this module’s transcripts, with the transcript that shows each one:
ReasonMeaning hereWhere you will see it
STATICNo targeting rule; the flag’s default variant was returnedtranscript 01, banner-text
DEFAULTA targeting rule exists but gave no answer, so the default variant appliedtranscripts 01 and 02, anonymous users
TARGETING_MATCHA rule (or a percentage split) picked the varianttranscripts 02 and 03
CACHEDThe provider answered from its local cachetranscripts 04 and 09
DISABLEDThe flag exists but is switched off in the file; the in-code default is returnedtranscript 01, legacy-export
ERRORSomething failed; the in-code default is returned and an error code is settranscripts 05 and 06
Log the reason next to the value. A bare false cannot tell you whether the flag was off, the user did not match, or the daemon was unreachable; the reason can.
Going deeper

The smallest thing that works: one flag file, one client, one if

Add the SDK and the flagd provider. The versions are the ones listed at the top; both are in the module’s pom.xml.
    <dependency>
      <groupId>dev.openfeature</groupId>
      <artifactId>sdk</artifactId>
      <version>${openfeature.sdk.version}</version>
    </dependency>
    <dependency>
      <groupId>dev.openfeature.contrib.providers</groupId>
      <artifactId>flagd</artifactId>
      <version>${flagd.provider.version}</version>
    </dependency>
Define a flag. flagd’s file format is JSON: each flag has variants (the possible values), a defaultVariant, and optionally targeting rules. This is the whole of new-checkout from flags/flags.json; we will read the targeting part in the next section.
    "new-checkout": {
      "state": "ENABLED",
      "variants": { "on": true, "off": false },
      "defaultVariant": "off",
      "targeting": {
        "if": [
          { "or": [
              { "==": [ { "var": "tier" }, "premium" ] },
              { "ends_with": [ { "var": "email" }, "@ankurm.com" ] }
          ] },
          "on",
          null
        ]
      }
    },
Register the provider once, when the application starts. This is FlagConfig.java; the rpc mode talks to a flagd daemon over gRPC on port 8013, the file mode is covered near the end.
        FlagdOptions options = "file".equals(props.mode())
                ? FlagdOptions.builder()
                        .resolverType(Config.Resolver.FILE)
                        .offlineFlagSourcePath(props.file())
                        .build()
                : FlagdOptions.builder()
                        .resolverType(Config.Resolver.RPC)
                        .host(props.host())
                        .port(props.port())
                        .build();

        OpenFeatureAPI api = OpenFeatureAPI.getInstance();
        api.onProviderReady(e -> log.info("flag provider READY ({})", e.getProviderName()));
        api.onProviderConfigurationChanged(e -> log.info("flag configuration changed: {}", e.getFlagsChanged()));
        api.onProviderError(e -> log.warn("flag provider ERROR: {}", e.getMessage()));
        api.onProviderStale(e -> log.warn("flag provider STALE: {}", e.getMessage()));
        api.addHooks(new LoggingHook());
        api.setProvider(new FlagdProvider(options));
        return api.getClient("checkout");
Finally, put the flag key and its fallback value in one class, so no other code needs to know either (CheckoutFlags.java).
    public boolean newCheckout(EvaluationContext ctx) {
        return client.getBooleanValue(NEW_CHECKOUT, false, ctx);
    }
The second argument, false, is the default value: what the code uses when the flag cannot be evaluated. Start flagd with ./scripts/run-flagd.sh (it runs flagd start -f file:flags/flags.json) and ask for five different flag types. The output comes from the test that wrote output/01-typed-evaluation.txt.
boolean                flag=new-checkout value=false variant=off reason=DEFAULT
string                 flag=banner-text value=Free shipping over 999 variant=plain reason=STATIC
integer                flag=discount-percent value=0 variant=none reason=DEFAULT
object                 flag=theme value=[color, density] variant=calm reason=STATIC
disabled flag          flag=legacy-export value=false variant=null reason=DISABLED
Each line is one evaluation with no user information, so rules that need a tier or an email cannot match. new-checkout falls to its default variant off. banner-text has no rule at all, hence STATIC. The theme flag returned a structure with two keys, color and density. legacy-export is marked DISABLED in the file, and the client answered with the default value from code (false) and no variant.
setProvider or setProviderAndWait? The configuration above uses the non-blocking setProvider, so the application starts even if flagd is not up yet. Until the provider becomes ready every evaluation returns your default. setProviderAndWait blocks and throws if the provider cannot start. Neither is wrong, but you must pick on purpose; the section on failures shows what each does.
For intermediate readers: why CheckoutFlags exists at all You could call client.getBooleanValue("new-checkout", false, ctx) in every controller. Then the string key and the fallback are copied into every call site, and a typo in one of them compiles, runs, and silently returns the fallback (transcript 06 below shows exactly that). One class that owns the keys, the defaults and the shape of the context gives you a single place to search, rename and test. It also keeps flag vocabulary out of business code: the controller asks newCheckout(ctx), not “evaluate the string new-checkout”. The module registers the provider on OpenFeatureAPI.getInstance(), the process-wide singleton, because that is what an application wants. The tests use OpenFeatureAPI.createIsolated() instead, so no test can leak provider state into another.
Going deeper

The same flag can give different answers to different users

So far the flag is global: everybody gets the same value. The useful part starts when the flag is asked about someone. OpenFeature calls that information the evaluation context: a targetingKey (usually a user id) plus any attributes you choose, such as tier or email. You build it where you know who the user is and pass it with each call; this is CheckoutFlags.java.
    /** Who is asking. The targeting key is what percentage rollouts hash on. */
    public static EvaluationContext userContext(String userId, String tier, String email) {
        Map<String, Value> attrs = new HashMap<>();
        if (tier != null) attrs.put("tier", new Value(tier));
        if (email != null) attrs.put("email", new Value(email));
        return new ImmutableContext(userId, attrs);
    }

    public boolean newCheckout(EvaluationContext ctx) {
        return client.getBooleanValue(NEW_CHECKOUT, false, ctx);
    }

    public FlagEvaluationDetails<Boolean> newCheckoutDetails(EvaluationContext ctx) {
        return client.getBooleanDetails(NEW_CHECKOUT, false, ctx);
    }

    public FlagEvaluationDetails<Boolean> paymentFlowV2(EvaluationContext ctx) {
        return client.getBooleanDetails(PAYMENT_FLOW_V2, false, ctx);
    }
The rule lives in the flag file, not in Java. This is the targeting block of new-checkout: if the user’s tier is premium or the email ends with @ankurm.com, answer with variant on; otherwise answer null, which means “no opinion, use the default variant”. It is JsonLogic with a few flagd-specific operators, and it is already in the new-checkout block shown earlier. Four callers, evaluated by the test that wrote output/02-targeting.txt:
anonymous              flag=new-checkout value=false variant=off reason=DEFAULT
standard               flag=new-checkout value=false variant=off reason=DEFAULT
premium                flag=new-checkout value=true variant=on reason=TARGETING_MATCH
staff email            flag=new-checkout value=true variant=on reason=TARGETING_MATCH
Only the premium user and the staff email match; the standard user falls through to DEFAULT. A second flag, discount-percent, returns a number and uses the same machinery: premium gets 20, standard gets 5, anyone else the default 0. Its definition, from flags/flags.json:
    "discount-percent": {
      "state": "ENABLED",
      "variants": { "none": 0, "small": 5, "big": 20 },
      "defaultVariant": "none",
      "targeting": {
        "if": [
          { "==": [ { "var": "tier" }, "premium" ] }, "big",
          { "==": [ { "var": "tier" }, "standard" ] }, "small",
          null
        ]
      }
    },
The three callers, from the same test (output/02-targeting.txt):
anonymous              flag=discount-percent value=0 variant=none reason=DEFAULT
standard               flag=discount-percent value=5 variant=small reason=TARGETING_MATCH
premium                flag=discount-percent value=20 variant=big reason=TARGETING_MATCH
The same decisions over HTTP, with flagd and the running application, from output/09-http-demo.txt (the premium caller; the full transcript has all four):
$ curl -H 'X-User-Id: u3' -H 'X-Tier: premium' localhost:8080/checkout   # premium
  page: new-checkout
  newCheckout:     {"value": true, "variant": "on", "reason": "TARGETING_MATCH"}
  discountPercent: {"value": 20, "variant": "big", "reason": "TARGETING_MATCH"}
A rule that does not match returns DEFAULT, not an error. That is the behaviour you want, and it is also why a misspelt attribute name ("Tier" instead of "tier") fails quietly: nobody matches and everybody gets the default, exactly as in the anonymous row above. If a rule seems dead, print the reason and the context attributes you actually sent.
For intermediate readers: where evaluation context can come from, and who wins The context you pass at the call site is only one layer. The OpenFeature specification merges up to five, from lowest to highest precedence: the global API context, then a transaction context (typically per request, set by a propagator), then the client’s context, then the invocation context (the one in the call), and finally context added by before-hooks. When the same field appears in several layers, the higher one wins (specification, evaluation-context section). In a Spring MVC application the usual choice is to build the context per call, as this module does, or to set a transaction context in a filter. This module only uses the invocation layer; the other layers are specified but were not exercised here.
Going deeper

A gradual rollout hashes each user into a bucket and keeps them there

“Ten percent of users” sounds like a coin flip per request, which would show one user the new page on one click and the old page on the next. A proper rollout instead hashes a stable identifier into a bucket, once, and every later request lands in the same bucket. flagd does that with the fractional operator; payment-flow-v2 below sends 10 parts of the traffic to on and 90 to off (flags/flags.json).
    "payment-flow-v2": {
      "state": "ENABLED",
      "variants": { "on": true, "off": false },
      "defaultVariant": "off",
      "targeting": {
        "fractional": [
          [ "on", 10 ],
          [ "off", 90 ]
        ]
      }
    },
bucket 0105099Each user hashes to one bucket (0 to 99) and stays thereDark green: on at a 10% rollout (buckets 0-9). Light and dark green together: on at 50% (buckets 0-49).Measured on 1000 users: 100 on at 10%, 486 on at 50%, and 0 users went from on to off.Raising the percentage only ever adds people, so nobody sees the feature appear and vanish.
Each user maps to one bucket, and the buckets are laid out in order: the first ten belong to on. Widening the split to 50 only extends the green region, so everyone already in it stays in it. The test evaluates 1000 synthetic users (user-0000 to user-0999) against two real flagd daemons, one with the 10/90 file and one with a 50/50 copy, and wrote output/03-gradual-rollout.txt:
split 10/90: users with the flag on  = 100 of 1000
split 50/50: users with the flag on  = 486 of 1000
users on at 10% but off at 50%        = 0   (growing the share never takes a user back)
same user asked twice, same answer     = 1000 of 1000
no targetingKey at all:
anonymous              flag=payment-flow-v2 value=false variant=off reason=DEFAULT
100 of 1000 users at ten percent and 486 at fifty: close to the target, not exact, because a hash is random-looking rather than perfectly even. Zero users flipped from on to off when the share grew, and asking twice gave the same answer 1000 times out of 1000. The last two lines are a trap: a context with no targeting key has nothing to hash. The client returned false with reason DEFAULT. If your rollout flag seems stuck at zero percent, check that the user id actually reaches the context.
The bucket depends on the flag key as well as the user. flagd documents that when you omit the bucketing expression it combines the targeting key with the flag key, so the same user can be inside the ten percent for one flag and outside it for another. That is usually what you want (two experiments should not share a cohort), but it means “the beta users” are not the same people across flags unless you build that into the rule.
For intermediate readers: what “sticky” does and does not promise Stickiness here means the same bucketing value and the same configuration give the same variant. It is a property of the hash, not of any stored state, so it survives restarts and works across instances with no database. It does not survive changing the bucketing value (say, switching from user id to e-mail) or reordering and rebalancing the variants in a way that moves the boundaries. Growing the share of the first variant, as the test does, kept every existing user (measured). I did not run the other cases: shrinking that share or reordering variants moves the bucket boundaries, so expect some users to change sides and test it before you rely on it. flagd’s fractional operation hashes the bucketing value with murmur3 and maps it onto a weight space capped at the largest 32-bit integer, so shares finer than one percent are possible (flagd fractional operation reference). Because assignment is deterministic, you can also reason about it offline: given the file and a user id, the answer is always the same. The FILE resolver in the last section proves that by reproducing the daemon’s count of 100 without a daemon.
Going deeper

Edit the flag file and the running application follows, without a restart

This is the point of the exercise. flagd watches the file it was started with; when it changes, flagd tells every connected client which flags changed, and the provider fires a CONFIGURATION_CHANGED event. The test connects a client, registers a handler, edits the file (banner-text from the plain variant to sale), and waits. It wrote output/04-live-reload.txt:
before the edit        flag=banner-text value=Free shipping over 999 variant=plain reason=STATIC
asked again            flag=banner-text value=Free shipping over 999 variant=plain reason=CACHED
edit: banner-text defaultVariant plain -> sale
provider event: CONFIGURATION_CHANGED, flagsChanged=[banner-text]
after the edit         flag=banner-text value=Year-end sale: extra 5% off variant=sale reason=STATIC
event arrived within 10 s: true (indicative latency: about 923 ms)
Two things are worth reading closely. First, the event names the flag that changed ([banner-text]), so a handler can refresh only what it cares about. Second, the repeated call before the edit reports CACHED: the provider keeps a local cache of static results so repeated reads do not each cross the network. After the edit the value is the new one and the reason is back to STATIC, so the cached entry did not survive the change. The measured latency is in the transcript and is indicative, not a promise; it will vary with the machine. The same thing over HTTP, with the real application and a real daemon: the script flips new-checkout from off to on in the flag file and calls the endpoint again with an anonymous user, no restart in between (transcript 09):
# 2. Edit the flag file: new-checkout defaultVariant off -> on (no restart, no deploy)
$ curl -H 'X-User-Id: anon-1' localhost:8080/checkout   # anonymous, after the edit
  page: new-checkout
  newCheckout:     {"value": true, "variant": "on", "reason": "DEFAULT"}
The anonymous user now gets the new checkout, and the reason is still DEFAULT: the rule did not match, but the default variant itself changed. Notice what that edit really did, though. A one-word change to a file flipped behaviour for every user the targeting rules do not cover. That is powerful, and it deserves the same review you give a code change. Keep the flag file in version control.
For intermediate readers: the application-side wiring for these events The application registers handlers on the API once, in FlagConfig. They only log, but the same hooks are where you would refresh a cached value or emit a metric. The log lines from the HTTP run, from transcript 09:
INFO com.ankurm.openfeature.FlagConfig        : flag provider READY (flagd)
INFO com.ankurm.openfeature.FlagConfig        : flag configuration changed: [new-checkout]
WARN com.ankurm.openfeature.FlagConfig        : flag provider STALE: there has been an error
The first line is the provider becoming ready (it appears twice in this run; I did not investigate why). The second is the live edit from the previous step. The third appears when flagd is killed at the end of the run. Separately, LoggingHook prints one line per evaluation (flag=... value=... variant=... reason=...). A hook is a small object the SDK calls around every evaluation, which makes it the right place for logging and metrics because it covers every flag without touching call sites. Its full source (LoggingHook.java) is below.
public class LoggingHook implements Hook<Object> {

    private static final Logger log = LoggerFactory.getLogger("flags");

    @Override
    public void after(HookContext<Object> ctx, FlagEvaluationDetails<Object> details, Map<String, Object> hints) {
        log.info("flag={} value={} variant={} reason={}",
                details.getFlagKey(), details.getValue(), details.getVariant(), details.getReason());
    }
Going deeper

What breaks: flagd is down, a key is mistyped, a type is wrong

A flag service is a dependency, and a dependency has outages. OpenFeature’s design answer is that evaluation never throws at the call site: it returns the default value you passed, with a reason of ERROR and an error code. That keeps the page up. It also means a failure is only visible if you look for it.

flagd is not there when the application starts

With setProvider the application starts and every flag answers with your default until the provider is ready. The test points the provider at a closed port and asks immediately (output/05-flagd-down.txt):
(a) setProvider() against a closed port, asked immediately
    provider state: NOT_READY
    premium user       flag=new-checkout value=false variant=null reason=ERROR errorCode=PROVIDER_NOT_READY (Provider not yet initialized)
The user is premium and would normally be on the new checkout, but the answer is false with PROVIDER_NOT_READY. With setProviderAndWait the failure is loud instead (same transcript, output/05-flagd-down.txt):
(b) setProviderAndWait() against a closed port
    threw: GeneralError
    message: Initialization timeout exceeded; did not complete within the 1000 ms deadline.
    state afterwards: ERROR
It throws a GeneralError from the registration call, after waiting out a 1000 ms initialisation deadline. If you prefer the application to refuse to start without flags, that is the call to use; if you prefer it to start and degrade, use setProvider and watch the provider state.
Even with flagd running, the first connection can miss the one-second window. It did not in the committed run of the HTTP demo, but twice in earlier runs while this was being written the application log showed a WARN with the same “Initialization timeout exceeded” message followed by READY about a second later: the provider kept trying and recovered by itself. The same timeout also failed the first test of a run once, until the test provider was given a 3-second deadline. Those earlier logs were not kept, so treat this as an observation, not a measurement. The default per-call deadline is 500 ms, read from the provider jar.

flagd disappears while the application is running

This is the case that matters in production. The test connects, evaluates, kills the daemon, waits 1.5 seconds, and evaluates again (output/05-flagd-down.txt, part c):
(c) flagd is killed while the app is running
    before the kill    flag=new-checkout value=true variant=on reason=TARGETING_MATCH
    asked again        flag=new-checkout value=true variant=on reason=TARGETING_MATCH
    provider state 1.5 s after the kill: STALE
    same flag, after   flag=new-checkout value=false variant=null reason=ERROR errorCode=GENERAL (DEADLINE_EXCEEDED: CallOptions deadline exceeded a...)
    never-asked flag, after flag=discount-percent value=0 variant=null reason=ERROR errorCode=GENERAL (DEADLINE_EXCEEDED: CallOptions deadline exceeded a...)
READYflagd answersSTALEconnection lostERRORafter the grace periodbanner-text (no targeting)still CACHED, same valuenew-checkout (targeting rule)value=false reason=ERROR: the code defaultThe premium user who saw the new checkout a second earlier now gets the legacy page.The default you wrote in code is what production runs on whenever the daemon is away.
The figure restates the transcript. The provider moved to STALE within 1.5 seconds. The flag with targeting rules was never cached, so it went to the dead daemon, hit the 500 ms deadline and returned the in-code default false. In the HTTP demo the same kill produced the same result: newCheckout returned false with ERROR, the page flipped back to legacy-checkout, and banner-text kept being served as CACHED (transcript 09):
# 3. Kill flagd
$ curl -H 'X-User-Id: u3' -H 'X-Tier: premium' localhost:8080/checkout   # premium, flagd gone
  page: legacy-checkout
  newCheckout:     {"value": false, "variant": null, "reason": "ERROR", "errorCode": "GENERAL"}
  banner:          {"value": "Free shipping over 999", "variant": "plain", "reason": "CACHED"}
The default value is a decision, not a placeholder. A premium customer who was on the new checkout a second ago is on the old one now, because false is what you typed in code. For a flag guarding unfinished work, false is the right fallback. For a flag that switches off a broken dependency, the safe fallback may be true. Choose each default by asking what you want production to do when nobody can answer.

A mistyped key or the wrong type returns the default, with a reason

Nothing throws here either. The test asked for a flag that does not exist, a flag with a typo, and two flags with the wrong type, and wrote output/06-errors.txt:
unknown flag           flag=no-such-flag value=true variant=null reason=ERROR errorCode=FLAG_NOT_FOUND (NOT_FOUND: Flag not found)
typo in the key        flag=new-chekout value=false variant=null reason=ERROR errorCode=FLAG_NOT_FOUND (NOT_FOUND: Flag not found)
boolean asked of a string flag=banner-text value=true variant=null reason=ERROR errorCode=TYPE_MISMATCH (INVALID_ARGUMENT: Type mismatch error)
string asked of an int flag=discount-percent value=n/a variant=null reason=ERROR errorCode=TYPE_MISMATCH (INVALID_ARGUMENT: Type mismatch error)
Each one returned the default passed in (true for the unknown flag, n/a for the string request) with a precise error code. In a real service these are log lines you will never read unless you set up an alert on ERROR reasons, which is cheap: the hook shown earlier is the place.
For intermediate readers: provider states, and the defaults you can tune The provider moves through states you can read from the client (getProviderState()): NOT_READY before it initialises, READY when it can answer, STALE when the connection dropped and the provider is retrying, and ERROR when it gave up or never started. All four appeared in this module’s runs (NOT_READY and ERROR in transcript 05 (a) and (b), STALE in (c), READY in transcript 09’s log). Options on FlagdOptions that control the timing, with the defaults read from the 0.15.0 provider jar (javap -constants on its Config class):
SettingDefaultEffect
deadline500 msper-evaluation gRPC deadline; with it at 500 ms the startup wait in these runs was 1000 ms
retryGracePeriod10 show long the provider stays STALE before it reports ERROR
maxCacheSize1000entries in the local cache of static results
offlinePollIntervalMs5000 mspoll interval for the FILE resolver’s source file
The 10-second grace period showed up in the test console (not in a committed transcript): after the daemon was killed it printed “Provider did not reconnect successfully within 10s. Emitting ERROR event…”. The effect of a longer deadline on user-facing latency was not measured here; a deadline is a per-call wait, so on a dead daemon it adds that much latency to every uncached evaluation.
Going deeper

Test both states without starting anything

Code behind a flag has two behaviours and both need a test. You do not want a flagd process for that. The SDK ships an InMemoryProvider: you give it a map of flags and register it on an isolated API instance, so every test picks its own flag state and nothing is shared. The helpers are in BothStatesTest.java.
    private static Map<String, Flag<?>> flags(boolean newCheckoutOn) {
        Map<String, Flag<?>> m = new HashMap<>();
        m.put(CheckoutFlags.NEW_CHECKOUT, Flag.<Boolean>builder()
                .variant("on", true).variant("off", false)
                .defaultVariant(newCheckoutOn ? "on" : "off")
                .build());
        return m;
    }
The helper builds a flag map with the flag on or off. The first two tests are then one line each. The third shows the part people miss: you can change the flags during a test with updateFlag and give a flag a context evaluator, so a test can model “premium sees it, anonymous does not” (from BothStatesTest.java):
    void flipTheStateInsideOneTestAndTargetByContext() throws Exception {
        InMemoryProvider provider = new InMemoryProvider(flags(false));
        CheckoutFlags f = service(OpenFeatureAPI.createIsolated(), provider);
        EvaluationContext anon = CheckoutFlags.userContext("u1", null, null);
        EvaluationContext premium = CheckoutFlags.userContext("u2", "premium", null);

        boolean before = f.newCheckout(anon);
        provider.updateFlag(CheckoutFlags.NEW_CHECKOUT, Flag.<Boolean>builder()
                .variant("on", true).variant("off", false).defaultVariant("off")
                .contextEvaluator((flag, ctx) -> ctx.getValue("tier") != null
                        && "premium".equals(ctx.getValue("tier").asString()))
                .build());
        boolean anonAfter = f.newCheckout(anon);
        boolean premiumAfter = f.newCheckout(premium);

        new Transcript("08-test-both-states.txt", "Testing behind a flag with InMemoryProvider (no flagd, no network)")
                .line("new-checkout, defaultVariant=off          anonymous -> %s", before)
                .line("same flag, now with a context evaluator   anonymous -> %s, premium -> %s", anonAfter, premiumAfter)
                .line("tests in this class: flagOff, flagOn, flipTheStateInsideOneTestAndTargetByContext")
                .write();

        assertFalse(before);
        assertFalse(anonAfter);
        assertTrue(premiumAfter);
It printed output/08-test-both-states.txt:
new-checkout, defaultVariant=off          anonymous -> false
same flag, now with a context evaluator   anonymous -> false, premium -> true
tests in this class: flagOff, flagOn, flipTheStateInsideOneTestAndTargetByContext
Isolation is the whole trick. OpenFeatureAPI.getInstance() is a JVM-wide singleton. A test that registers a provider on it changes every other test that runs afterwards in the same JVM. createIsolated() returns a fresh API, and a Client taken from it is bound to the provider you gave it. The fourth test in the class also pins the failure contract: an unknown flag returns the code default instead of throwing.
Going deeper

You can skip the daemon and read the same file in-process

Running flagd is one more thing to deploy, monitor and secure. If your flags change a few times a month and you have one or two services, the provider can evaluate the JSON file itself. The provider has three resolvers: RPC (ask a daemon, as above), IN_PROCESS (stream the definitions from a daemon and evaluate locally) and FILE (read a local file and evaluate locally). In this module flags.mode=file selects FILE. The test below uses the same flags/flags.json with no daemon at all, and wrote output/07-file-resolver.txt:
premium                flag=new-checkout value=true variant=on reason=TARGETING_MATCH
payment-flow-v2 on for 100 of 1000 users (the flagd daemon said 100 in transcript 03)
Same targeting, and the same 100 of 1000 users from the daemon’s run in transcript 03, so the in-process bucketing agrees with flagd’s. Only FILE and RPC were run in this module; IN_PROCESS exists in the provider (its default sync port constant is 8015) but was not exercised.
For intermediate readers: choosing between the three resolvers
ResolverNeeds a daemonLatency per evaluationChange reaches the app via
RPCyesa gRPC call, except for cached static resultsa change event over the stream
IN_PROCESSyes (for the definitions stream; not run here)local evaluationthe sync stream (not run here)
FILEnolocal evaluationthe provider re-reading the file; the default poll interval is 5000 ms (the reload itself was not measured here)
Local evaluation removes the network hop and the failure case from the previous section, because there is no daemon to lose. The price is that every instance needs the file: in Kubernetes that usually means a ConfigMap mounted into the pod, and a ConfigMap update reaches a pod after the kubelet’s sync delay, which this module did not measure.
Going deeper

Do you need this, and what to delete afterwards

Be honest about the size of the problem. If you have one service, one environment and a flag that changes twice a quarter, a property in application.yml plus a restart is a feature-flag system with zero moving parts. Flags earn their cost when the change must happen faster than a deploy, for a subset of users, or reversibly under load. Remember what you have added: a second place where behaviour is decided, a daemon or file to keep available, and a default value in code that production silently depends on whenever that daemon is away.

Treat every release flag as a loan. Each one is an if with two branches you must keep tested until the day you delete it. Give the flag an owner and a removal date when you create it, delete the branch you no longer want, and delete the entry from the file. Do not put secrets or security decisions in a flag file, and do not use a flag to hide a permission check: a flag you can flip is a flag someone can flip by mistake.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.