Guide

Feature flag examples: 8 patterns with code

Eight feature flag examples you can copy, from a plain release flag to an A/B test. Each one shows the targeting rules, the code in TypeScript, Python, Go, Java or Kotlin, and when to remove the flag.

Every feature flag example has three parts: the question the flag answers, the rules that decide the answer, and the line of code that asks. The examples below use the OpenFeature API, so the call looks much the same in every language. What changes from one to the next is the flag's type, its rules and how long it should live.

Feature flag examples at a glance

ExampleValueKindLives for
Release flagBooleanReleaseWeeks
Percentage rolloutBooleanReleaseDays to weeks
Kill switchBooleanOpsPermanent
Plan gateBooleanPermissionAs long as the plans differ
Beta accessBooleanReleaseUntil general availability
A/B testStringExperimentThe length of the test
Config valueNumberOpsPermanent
Region gateBooleanPermissionAs long as the rule applies

The kind is the four-way split described in the types of feature flags. Railflag stores it on each flag, so a cleanup sweep can skip the ones that are meant to stay.

1. A release flag: merge code before it's ready

The simplest feature flag example. Unfinished work is merged and deployed, but stays off for customers until you turn it on. It is what makes trunk-based development work: everyone merges to main every day, and the flag decides what users see.

Rules for new-search, top to bottom:

  1. email ends with @yourcompany.com → on (your team tries it in production)
  2. Everyone else → off
import { OpenFeature } from '@openfeature/server-sdk';
import { RailflagProvider } from '@railflag/sdk-node';

// Once, at startup.
await OpenFeature.setProviderAndWait(new RailflagProvider({
  sdkKey: process.env.RAILFLAG_SERVER_KEY,
  baseUrl: 'https://relay.railflag.com',
}));
const flags = OpenFeature.getClient();

// On every request.
const context = { targetingKey: user.id, email: user.email };
const useNewSearch = await flags.getBooleanValue('new-search', false, context);
const results = useNewSearch ? await newSearch(query) : await legacySearch(query);

The default, false, is what users get if the flag doesn't exist or the SDK has no rules yet. For a release flag that is the old behaviour.

How long it lives: weeks. Once the new search is on for everyone and nobody wants to go back, remove the check and the old code path in one pull request, deploy, then archive the flag. Cleaning up feature flags covers the order in detail.

2. A percentage rollout: widen a release step by step

The same release flag, served to a growing share of users. Each user's bucket comes from a hash of the flag key and their targeting key, so a user who got the new search at 5% still has it at 25%. How consistent bucketing works.

Rules for new-search:

  1. email ends with @yourcompany.com → on
  2. Everyone else → 5% on, 95% off. Then 25%, 50% and 100%, with a pause at each step.

The code does not change. What matters is the context you pass:

const on = await flags.getBooleanValue('new-search', false, {
  targetingKey: user.id,   // decides who lands in the 5%
  accountId: account.id,   // split by this to move whole companies together
  email: user.email,
});

In a B2B product, set the rollout to split by accountId instead of the user's key, so everyone at one customer sees the same version. Without a stable targeting key, every visitor lands in the same bucket and a 5% rollout becomes all or nothing.

How long it lives: days to weeks. Watch error rates and latency at each step, as progressive delivery describes. On Team and Business, Release Watch reads your monitoring during the rollout and can pause it when a limit breaks. At 100%, remove it like any release flag.

3. A kill switch: turn a dependency off in seconds

A long-lived flag that is on in normal operation. During an incident you turn it off, and the code takes a degraded but working path instead of calling a failing service. Here it is in Python, with the setup from the Python guide:

Rules for recommendations-enabled:

  1. Everyone → on

In an incident you turn the flag off, and every SDK serves its off variation, false, within about a second.

from openfeature.evaluation_context import EvaluationContext

ctx = EvaluationContext(str(user.id), {"plan": user.plan})

# True = call the recommendations service. Turn the flag off to shed it.
if client.get_boolean_value("recommendations-enabled", True, ctx):
    recs = recommendations_api.for_user(user.id, timeout=0.8)
else:
    recs = []  # the degraded but working path

Two choices make the switch safe. The code default is True, so if the flag system can't answer, the feature keeps running. And the check runs in memory, so it still answers when the network is the problem. More in how to build a kill switch.

How long it lives: permanently. Mark it as an ops flag so nobody removes it as a finished release.

4. A plan gate: a feature for paying plans only

A feature gate decides who may use a feature, here by pricing plan. Gate on the capability, not on the plan name, so that moving a feature between plans is a rule change instead of a code change. In Java, with the client from the Java guide:

Rules for bulk-export:

  1. plan is one of pro, enterprise → on
  2. accountId is acme → on (a trial before they upgrade)
  3. Everyone else → off
EvaluationContext ctx = new ImmutableContext(user.getId(), Map.of(
    "accountId", new Value(account.getId()),
    "plan", new Value(account.getPlan())));

if (!client.getBooleanValue("bulk-export", false, ctx)) {
    throw new ResponseStatusException(HttpStatus.FORBIDDEN,
        "Bulk export is on the Pro plan");
}

The plan comes from your billing data on every check; the gate reads it, it doesn't decide what someone paid for. The default is false, so a gated feature stays gated if the flag can't be read. Check it in the API, not only in the UI.

How long it lives: as long as the plans differ, often years. Mark it as a permission flag.

5. Beta access for your team and a list of customers

Before a percentage rollout, a new feature usually goes to your own company and then to customers who asked to try it. A segment holds the beta list, so several flags can share it and you add a customer in one place. In a Next.js Server Component, with the flags() helper from the Next.js guide:

Rules for beta-dashboard:

  1. email ends with @yourcompany.com → on
  2. In segment beta-testers → on
  3. Everyone else → off
import { flags } from '@/lib/flags';

export default async function DashboardPage() {
  const user = await currentUser(); // your auth
  const client = await flags();
  const beta = await client.getBooleanValue('beta-dashboard', false, {
    targetingKey: user.id,
    email: user.email,
  });

  return beta ? <NewDashboard /> : <Dashboard />;
}

The check runs on the server, so the HTML arrives with the right dashboard and nothing flickers in the browser.

How long it lives: until general availability. Then add a percentage step for everyone else (example 2), go to 100%, and remove the flag.

6. An A/B test with a tracked metric

A string flag splits users between variations, and an experiment on that flag compares a metric between them. Here a one-page checkout is tested against the current one, on revenue per user.

Rules for checkout-layout, with variations control and one-page:

  1. Everyone → 50% control, 50% one-page

Then start an experiment from the flag's Experiments tab, with control as the control variation and a metric that adds up the value of each user's purchase events.

const context = { targetingKey: user.id };
const layout = await flags.getStringValue('checkout-layout', 'control', context);
const page = layout === 'one-page' ? onePageCheckout : classicCheckout;

// Later, when the order is paid. Same targetingKey.
flags.track('purchase', context, { value: order.total });
  • Checking the flag reports which variation each user got, once, while the experiment runs. That needs @railflag/sdk-node 0.4 or later; the other SDKs have the same track call.
  • Only users who got their variation from the split are in the experiment. Users in individual targets, or in a rule that serves a fixed variation, are not.
  • Only events that a running experiment counts are sent, and events count from each user's first exposure.

How long it lives: the length of the test, at least the minimum runtime of 7 days. Decide the end date before you start. Then roll the winner out to everyone and remove the flag like a release flag.

7. A config value: change a number without a deploy

Not every flag is on or off. A number flag holds a limit, a timeout or a batch size that you may need to change in a hurry. In Go, with the client from the Go guide, a worker reads how many emails to send per batch:

Rules for email-batch-size, with variations 500, 100 and 0:

  1. Everyone → 500

When the email provider struggles, serve 100 to slow the job down, or 0 to pause it.

evalCtx := openfeature.NewEvaluationContext("email-worker", map[string]any{
    "region": region,
})

batch, _ := client.IntValue(ctx, "email-batch-size", 500, evalCtx)
if batch == 0 {
    return nil // paused by the flag
}
sendNext(ctx, int(batch))

The targeting key doesn't have to be a user. Here it names the worker, and a rule on region could throttle one region only. A flag can also hold a JSON value when several settings belong together; read it with ObjectValue.

How long it lives: permanently. Mark it as an ops flag.

8. A region gate for compliance

Some features may only be offered where they are licensed or where data stays in the region: a payment method, a data export, an AI feature. A permission flag keeps that list out of the code. In Kotlin, with the setup from the Java and Kotlin guide:

Rules for pay-by-bank:

  1. country is one of NL, BE, DE → on
  2. Everyone else → off
val ctx = ImmutableContext(account.id, mapOf("country" to Value(account.country)))

val methods = buildList {
    add(PaymentMethod.CARD)
    if (client.getBooleanValue("pay-by-bank", false, ctx)) {
        add(PaymentMethod.BANK_TRANSFER)
    }
}

Send the country from the account's billing details, not from the visitor's IP address, and enforce the gate on the server. Adding a country is then a rule change, and every change to Production is in the audit log with who made it and why.

How long it lives: as long as the rule applies. Mark it as a permission flag.

What every example has in common

  • A safe default in the code. Off for releases and gates, on for kill switches. The default is what runs when the flag can't be read.
  • A stable targeting key. A user id, an account id, or the name of a worker. Rollouts and experiments depend on it.
  • A check on the server. The browser can hide a button, but the API decides.
  • Both paths tested. Run the code with the flag on and off. Testing code behind feature flags shows how without a live flag service.
  • A known end. Release and experiment flags get removed; ops and permission flags are marked so they stay. The terms are in the feature flag glossary.

Frequently asked questions

What is an example of a feature flag?

A release flag around a new checkout. The code asks the flag for each user: your own team gets the new checkout, everyone else gets the old one. You then widen it to 5%, 25% and 100% of users without a deploy, and once everyone has it you delete the check.

What are the main types of feature flags?

Four. Release flags ship unfinished work safely. Ops flags, such as kill switches and config values, control how the system runs. Experiment flags split users for an A/B test. Permission flags, also called feature gates, decide who may use a feature. Release and experiment flags are temporary; ops and permission flags are long-lived.

How long should a feature flag live?

Release and experiment flags live until the decision is made, usually days to weeks. Then you remove the check and archive the flag. Kill switches, config flags and feature gates are permanent by design, so mark them as ops or permission flags and cleanup will leave them alone.

Can a feature flag return something other than true or false?

Yes. In Railflag a flag is a boolean, a string, a number or JSON. A string flag names the variation in an A/B test, a number flag holds a limit or a batch size, and a JSON flag holds a whole configuration object. Your code reads each one with the matching typed call.

Try these flags in your own code

Railflag's server SDKs for Node, Python, Go and Java evaluate every example above in your process, with no network call per check. Free to start.

Start for free