Guide
Feature flags: what they are and how they work
How feature flags decide who gets what, the four kinds you will meet, how percentage rollouts keep each user stable, and the habits that stop flags from turning into debt.
A feature flag is a condition in your code that decides, while the software is running, whether a feature is on for a given user. Because the decision comes from configuration rather than from the code itself, you can turn features on, off, or on for some users without deploying again.
Feature flags go by several names: feature toggles, feature switches, and feature gates. They all describe the same mechanism. This guide uses "feature flag" throughout.
What is a feature flag?
In its simplest form, a feature flag is an if statement whose condition you can change from outside the code:
const context = { targetingKey: user.id, country: user.country };
if (await flags.getBooleanValue('new-checkout', false, context)) {
return renderNewCheckout();
}
return renderOldCheckout();
Three things make this more than a config value:
- A context. The check receives facts about who is asking: a user id, their plan, their country, the app version. Rules use those facts to decide.
- A default. The second argument (
falseabove) is what the code does if the flag system cannot answer. It should always be the safe choice. - Rules that change at runtime. Someone can change who gets the new checkout in a dashboard or through an API, and every running instance picks it up within seconds.
A flag does not have to be on or off. It can return a string, a number or a JSON object, which lets one flag choose between several variations, such as three checkout designs or a timeout value.
Why teams use feature flags
The main benefit is that deploying code and releasing a feature become two separate steps. Code can ship to production switched off, and the release happens later as a flag change, for whoever you choose. From that follow most of the uses:
- Trunk-based development. Unfinished work merges to the main branch behind a flag that is off, instead of living on a long branch that is painful to merge.
- Gradual rollouts. Release to 1% of users, watch errors and metrics, then 10%, 50%, 100%. If something breaks, only a few users see it.
- Kill switches. Turn off a feature or an expensive dependency in seconds during an incident, without a rollback.
- Testing in production. Turn a feature on for your own team or a beta group first, on real data and real infrastructure.
- Experiments. Split users between variations to measure which one performs better.
- Entitlements. Decide which plans, accounts or roles get a capability. These long-lived flags are often called feature gates.
The four types of feature flags
Flags differ mostly in how long they live and who changes them. Pete Hodgson's widely used categories still describe them well:
| Type | Used for | Lifetime | Usually changed by |
|---|---|---|---|
| Release flag | Shipping unfinished or risky work switched off, then rolling it out | Days to weeks | The team that built the feature |
| Experiment flag | Splitting users between variations to compare them | Length of the experiment | Product and growth teams |
| Ops flag (kill switch) | Turning off a feature or dependency under load or during an incident | Long-lived | On-call engineers |
| Permission flag (feature gate) | Giving features to some plans, accounts, roles or regions | As long as the feature exists | Product, sales, support |
Labelling each flag with its type tells everyone whether it should be gone next month or is meant to stay. Railflag records it as the flag's kind: release, experiment, ops or permission.
How a feature flag is evaluated
Every flag system answers the same question in roughly the same order. For one flag, one environment and one context:
A rule is a list of conditions on the context, such as country is one of GR, CY and plan is pro, plus what to serve when they all match. Rules are checked top to bottom, so order matters: put specific rules above general ones. Common operators are equality, "one of", starts with and ends with, number and date comparisons, semantic version comparisons (appVersion >= 2.4.0), and segments, which are named groups such as "beta testers" reused across flags.
Local vs remote evaluation
Where the rules are evaluated matters more for performance and reliability than any other choice.
| Local evaluation (server SDKs) | Remote evaluation (browsers, mobile) | |
|---|---|---|
| Where rules run | In your process, from rules kept in memory | On a server close to the user; the app receives results |
| Cost of a check | Microseconds, no network call | One request per context change, then cached |
| If the flag service is down | Keeps using the last rules it had | Uses cached results, then code defaults |
| What the client sees | Nothing: rules stay on your servers | Only its own results, not your targeting rules |
Server code should evaluate locally: the SDK downloads the rules once, keeps them up to date over a stream, and answers every check from memory. Browsers and mobile apps should not download your rules, since they may contain customer names or internal segments. Instead they ask a relay for their own results. Railflag works this way: server SDKs evaluate in-process, and browser SDKs get results from a relay with a public client key.
Percentage rollouts and consistent bucketing
A percentage rollout ("serve the new checkout to 20% of users") must give each user the same answer every time. If it rolled a die on every check, a user would flip between old and new checkout on each page load.
So flag systems do not use random numbers. They hash a stable value, usually the user id together with the flag's key, into a bucket. The same user and flag always land in the same bucket, and buckets are spread evenly across users:
// Railflag: MurmurHash3 of "flagKey.salt.userId", scaled to 100,000 buckets
const hash = murmur3(`${flag.key}.${flag.salt}.${userId}`); // 0 … 2³²−1
const bucket = Math.floor((hash / 2 ** 32) * 100_000); // 0 … 99,999
// 20% rollout: buckets 0–19,999 get the new value
const inRollout = bucket < 20_000;
Two details are worth knowing:
- The flag key is part of the hash. Otherwise the same 20% of users would be the early adopters of every rollout. Including the key (or a per-flag salt) gives each flag an independent split.
- Changing the hash input reshuffles everyone. Renaming the flag, changing its salt, or switching the attribute you bucket by (user id vs account id) moves users between variations. For a B2B product, bucket by account so everyone in a company sees the same thing.
How each vendor buckets users
Every flag platform has its own hash, and they are not interchangeable. That matters when you switch tools: if the new tool hashes differently, users silently move to a different variation. This is how the major platforms do it, read from their open-source SDKs in November 2026:
| Platform | Hash | Hashed value | Buckets |
|---|---|---|---|
| LaunchDarkly | SHA-1 | flagKey.salt.key | 15 hex digits, read as 100,000 |
| Unleash | MurmurHash3 | groupId:userId | 100 (variants: total weight) |
| Optimizely | MurmurHash3, seed 1 | userId + ruleId | 10,000 |
| Split (Harness) | MurmurHash3, per-flag seed | bucketing key | 100 |
| Statsig | SHA-256 | salt.ruleSalt.unitId | 10,000 |
| GrowthBook | FNV-1a | seed and userId | 1,000 (v1) or 10,000 (v2) |
| PostHog | SHA-1 | flagKey.distinctId | 15 hex digits, as a fraction |
| ConfigCat | SHA-1 | settingKey + userId | 100 |
| Eppo | MD5 | salt-subjectKey | Usually 10,000 shards |
| Flipt | CRC32 | entityId + flagKey | 100 (variants: 1,000) |
| AB Tasty | MurmurHash3 | variationGroupId + visitorId | 100 |
| Railflag | MurmurHash3 | flagKey.salt.userId | 100,000 |
Railflag's migration tools reproduce the hash of AB Tasty and Unleash when they import a flag, so every user keeps the variation they had before. See migrating to Railflag.
Targeting rules that stay readable
Rules are where flag systems get hard to reason about. A few habits keep them understandable:
- Target attributes, not lists of ids, except for a handful of test accounts. "plan is enterprise" survives new customers; a list of 400 account ids does not.
- Use segments for groups you reuse, such as internal staff, beta testers or EU customers, and change them in one place.
- Send consistent types. If a rule compares
age >= 18, sendageas a number everywhere. A string"18"from one service and a number from another is a classic source of "works for some users". - Keep rules few. If a flag needs ten rules, it is probably several decisions that deserve separate flags.
Feature flags vs branches, config and experiments
- Feature branches keep unfinished code out of the main line; feature flags keep it switched off on the main line. Flags avoid long-running branches and merge conflicts, at the cost of both paths living in the code for a while.
- Configuration files and environment variables are fine for values that change with a deploy. Flags are for decisions that change at runtime and differ by user.
- Experiments are flags plus measurement: assignment comes from a flag, and the result from analysing a metric per variation.
- Remote config is a flag whose value is data (a timeout, a list of payment methods) rather than on or off.
Feature flag best practices
- Make the code default safe. If the flag system cannot answer, the default should be the old, known-good behaviour.
- Give every flag an owner and a type. A release flag without an owner becomes permanent by accident.
- Remove release flags quickly. Once a feature is at 100% and stable, delete the flag and the old code path, ideally within a few weeks. Stale flags are technical debt: dead code, confusing configuration and untested paths. See how to clean up feature flags safely.
- Name flags for what they do.
new-checkoutorenable-bulk-export, notflag-2024-q3ortest. - Evaluate locally on servers. A flag check should never be the slowest thing in a request, and an outage at your flag provider should not take your app down.
- Test both paths. Run tests with the flag on and off while both exist.
- Review production changes. A flag change is a production change. Require approval for production and keep an audit log of who changed what and why.
- Keep secrets and personal data out of flag values. Values reach SDKs, and browser SDKs are readable by anyone.
- Avoid long chains of dependent flags. One prerequisite is fine; three levels deep is hard to debug.
- Keep kill switches for risky dependencies such as a third-party API or an expensive query, and test that they work before you need them. See kill switches.
Feature flags with OpenFeature
OpenFeature is a CNCF standard API for feature flags. Your code calls the OpenFeature API, and a provider connects it to a flag platform, so changing platforms means changing the provider, not every flag check. Railflag's SDKs are OpenFeature providers (the OpenFeature guide covers context, hooks and switching vendors):
Node.js (server, local evaluation)
import { OpenFeature } from '@openfeature/server-sdk';
import { RailflagProvider } from '@railflag/sdk-node';
await OpenFeature.setProviderAndWait(new RailflagProvider({
sdkKey: process.env.RAILFLAG_SERVER_KEY,
baseUrl: 'https://relay.railflag.com',
}));
const flags = OpenFeature.getClient();
const enabled = await flags.getBooleanValue('new-checkout', false, { targetingKey: user.id, plan: user.plan });
Browser (results from the relay)
import { OpenFeature } from '@openfeature/web-sdk';
import { RailflagWebProvider } from '@railflag/sdk-js';
await OpenFeature.setProviderAndWait(
new RailflagWebProvider({ clientKey: 'cli_…', baseUrl: 'https://relay.railflag.com' }),
{ targetingKey: user.id, plan: user.plan },
);
const enabled = OpenFeature.getClient().getBooleanValue('new-checkout', false);
Python (server, local evaluation)
import os
from openfeature import api
from openfeature.evaluation_context import EvaluationContext
from railflag import RailflagProvider
api.set_provider_and_wait(RailflagProvider(sdk_key=os.environ["RAILFLAG_SERVER_KEY"], base_url="https://relay.railflag.com"))
flags = api.get_client()
enabled = flags.get_boolean_value("new-checkout", False, EvaluationContext(user.id, {"plan": user.plan}))
Go (server, local evaluation)
import (
"github.com/open-feature/go-sdk/openfeature"
railflag "railflag.com/go/openfeature"
)
provider, err := railflag.NewProvider(railflag.Options{SDKKey: os.Getenv("RAILFLAG_SERVER_KEY"), BaseURL: "https://relay.railflag.com"})
if err == nil {
err = openfeature.SetProviderAndWait(provider)
}
flags := openfeature.NewDefaultClient()
enabled, _ := flags.BooleanValue(ctx, "new-checkout", false, openfeature.NewEvaluationContext(user.ID, map[string]any{"plan": user.Plan}))
Java and Kotlin (server, local evaluation)
var api = OpenFeatureAPI.getInstance();
api.setProviderAndWait(new RailflagProvider(RailflagOptions.builder()
.sdkKey(System.getenv("RAILFLAG_SERVER_KEY")).baseUrl("https://relay.railflag.com").build()));
var flags = api.getClient();
boolean enabled = flags.getBooleanValue("new-checkout", false, new ImmutableContext(user.getId(), Map.of("plan", new Value(user.getPlan()))));
Build or buy a feature flag system?
A config file or a database table is enough for a handful of global on/off switches. You outgrow it when you need any of these: per-user targeting, percentage rollouts that stay consistent across services and languages, changes that reach every instance in seconds, local evaluation with a fallback when the service is down, an audit log, and approval for production. Each is straightforward on its own; together, across several languages, they are a product. That is the point where teams usually adopt a flag platform.
Frequently asked questions
- Are feature flags the same as feature toggles?
- Yes. Feature flag, feature toggle, feature switch and feature gate all name the same idea: a runtime condition that turns a feature on or off without a deploy. Feature flag is the most common term today. Some teams use "feature gate" for long-lived pass/fail checks; see feature gates.
- Do feature flags slow down my application?
- Not when they are evaluated locally. A server SDK keeps the rules in memory and evaluates a flag in microseconds without a network call. Flags that call a remote service on every check add that service's latency and availability to every request.
- When should I remove a feature flag?
- Remove a release flag as soon as the feature is at 100% and stable, usually within weeks. Keep kill switches and permission flags as long as the behaviour they control exists, and give each one an owner.
- Can I run A/B tests with feature flags?
- Yes. A flag with several variations and a percentage split assigns each user to one variation consistently. To measure results you also need to record which variation each user saw and analyse a metric.
- Is it safe to put secrets in feature flags?
- No. Flag values reach SDKs, and client-side SDKs run in the browser where anyone can read them. Keep secrets in a secrets manager and use flags only to decide behaviour.
Try feature flags that evaluate in your process
Railflag is free to start: local evaluation in Node, Python, Go and Java, a relay for browsers, percentage rollouts, and approval for every production change.
Start for free