How to implement feature flags in code

To implement a feature flag, wrap the new code path in a check such as if (flag("new_checkout", user)), keep the old path as the default, and store the flag's state outside the code so you can change it without a deploy. The check should run in memory, treat an unknown flag as off, and give each user the same answer as a rollout widens. You can build that with a database table and one function, or use a flag service's SDK.

Updated

Implement a feature flag, step by step

  1. Name the flag and declare it. Pick a key that says what changes, such as new_checkout, and declare it in one place in code with an owner and a one-line summary. A list of declared flags is what lets you find and remove them later.
  2. Wrap the new code path. Put the new behaviour inside the flag check and leave the old behaviour as the fallback, so off is always the safe answer.
  3. Keep the state outside the code. The flag's state lives in a table or a flag service, not in a config file that needs a deploy, so changing it takes seconds.
  4. Evaluate in memory. Load every flag's rules into memory and refresh them in the background. A check is then a lookup, with no database or network call per request, and an unknown flag or a failed load means off.
  5. Roll out in stages. Turn the flag on for admins, then named users, then a sticky percentage, then everyone. Hash the flag key and user id so each user keeps the same answer as the percentage rises.
  6. Test both states. Run the tests that cover the flagged code once with the flag on and once with it off.
  7. Remove the flag. Once the feature is on for everyone and stable, delete the check and the old path, then delete the flag.

The smallest working implementation

Many teams start with a table and one function. This is enough for one app and a few flags. The table holds each flag's state and rules:

CREATE TABLE feature_flags (
  key     text PRIMARY KEY,
  state   text NOT NULL DEFAULT 'off',  -- off | admins | targets | percent | on
  users   text[] NOT NULL DEFAULT '{}', -- for state = targets
  percent int  NOT NULL DEFAULT 0       -- for state = percent, 0-100
);

The app loads the table into memory, refreshes it every few seconds, and answers every check from memory. If a refresh fails, it keeps the last rules it had:

import { createHash } from "node:crypto";

let flags = new Map();
async function refreshFlags() {
  try {
    const { rows } = await db.query("SELECT key, state, users, percent FROM feature_flags");
    flags = new Map(rows.map((r) => [r.key, r]));
  } catch (err) {
    console.warn("flags: refresh failed, keeping the last rules", err);
  }
}
await refreshFlags();
setInterval(refreshFlags, 5000);

// The same user always lands in the same bucket, 0-99, for a given flag.
const bucket = (key, userId) =>
  createHash("sha256").update(`${key}:${userId}`).digest().readUInt32BE(0) % 100;

export function flag(key, user) {
  const f = flags.get(key);
  if (!f) return false;                          // unknown or not loaded: off
  if (f.state === "on") return true;             // everyone, including anonymous
  if (!user?.id) return false;                   // anonymous: only "on"
  if (user.isAdmin && f.state !== "off") return true;
  if (f.state === "targets") return f.users.includes(user.id);
  if (f.state === "percent") return bucket(key, user.id) < f.percent;
  return false;
}

The check in a request handler:

if (flag("new_checkout", req.user)) {
  return renderNewCheckout(cart);
}
return renderCheckout(cart);

The bucket is the first 4 bytes of sha256(key:userId), read big-endian, mod 100. Hashing the key with the user means each flag picks a different 10% of users, and a user in the first 10% stays in when you go to 25%. More in percentage rollouts and sticky bucketing.

What the homegrown version is missing

The table above works, and plenty of teams run on one for years. What usually comes next, as more people and agents change flags:

  • A record of every change: who changed which flag, from what to what, when and why. A bare table keeps only the current row.
  • Faster changes: a 5-second poll is fine for one app; many apps polling a database adds load, and pushing changes needs a stream.
  • Restarts during an outage: if the database is down when the app starts, the map above is empty and every flag is off. A cache of the last good rules on disk fixes that.
  • Flags declared in code: the table and the code drift apart, and nobody knows which flags are still checked. See typed feature flags.
  • Permissions: who may change production flags, and what an AI agent may do with a token of its own. See scoped agent tokens.
  • Environments: separate states for production and development, so testing a flag doesn't change what customers see.

Whether to keep building or move to a service is a trade-off of time against control; see build your own, or use a service? If you already have a table like this, moving off an in-house flag table covers importing it with its history.

The same flag with an SDK

With Flagger.gg, the flag is declared in code and registered when the app starts. A flag that doesn't exist yet is created; a deploy never overwrites a state someone set. The SDK keeps the ruleset in memory, follows a stream of changes (polling every 5 seconds if the stream drops), and starts from a disk cache of the last good rules.

// Node / TypeScript: @flaggergg/node
const flagger = createFlagger({
  sdkKey: process.env.FLAGGER_SDK_KEY,
  defs: {
    new_checkout: {
      summary: "Customers see the rebuilt checkout",
      description: "One-page checkout with saved cards",
      owner: "payments",
    },
  },
});
await flagger.start(); // never rejects for network errors

if (flagger.flag("new_checkout", { userId: user.id, email: user.email, isAdmin: user.isAdmin })) {
  return renderNewCheckout(cart);
}
return renderCheckout(cart);
// Go: flagger.gg/go
client := flagger.New(flagger.Options{
    SDKKey: os.Getenv("FLAGGER_SDK_KEY"),
    Defs: []flagger.Def{{Key: "new_checkout", Summary: "Customers see the rebuilt checkout", Owner: "payments"}},
})
client.Start(ctx)
defer client.Close()

if client.Enabled("new_checkout", &flagger.Subject{UserID: u.ID, Email: u.Email, Admin: u.IsAdmin}) {
    return renderNewCheckout(w, cart)
}
return renderCheckout(w, cart)

The rules are the five states from the table above: off, admins, targets, percent and on, with the same bucket formula. Both SDKs run shared test vectors so a user gets the same answer in Go, in Node and in flagger eval. In auto-live mode, the default, a newly registered flag starts on unless it carries a not-ready reason, so a flag for unfinished work passes notReady:

new_checkout: { summary: "...", description: "...", owner: "payments", notReady: "saved cards not done" },

Then roll it out from the CLI or the console:

A not-ready flag can still go to admins, targets or a percentage; only turning it on for everyone needs --confirm-not-ready.

flagger set new_checkout admins --note "try it on the team first"
flagger set new_checkout percent --percent 10 --note "10% of users"
flagger eval new_checkout --user usr_123 --json

In development Public installs of both SDKs (npm and go get) are in development. Browser, Python and mobile SDKs are in development too; today a server sends the browser the flags that are on for that user (evaluatedFlags in Node, For in Go).

Test both sides

Every flag doubles the paths through the code it guards, so test the code with the flag on and with it off. Flagger.gg's SDKs include helpers for this: bothFlagStates runs a test once per state, withFlag forces a state inside one test, and setFlagOverride pins one. Go has the same in flaggertest.

await flagger.bothFlagStates("new_checkout", async (on) => {
  const page = await renderCheckoutPage(cart);
  expect(page.includes("Saved cards")).toBe(on);
});

More in testing both sides of a flag.

Remove the flag when it's done

A release flag is temporary. Once the feature is on for everyone and stable, delete the check and the old path in a small pull request, then remove the flag from the declared list. Flagger.gg marks which flags the code still registers, so a flag no deploy has registered in 30 days stands out, and you can archive it. See flag cleanup and flag debt.

FAQ

How do you implement a feature flag in code?

Wrap the new code path in a check like if (flag("new_checkout", user)), keep the old path as the fallback, and read the flag's state from a table or flag service that you can change without a deploy.

Can I implement feature flags without a third-party service?

Yes. A table with each flag's state, loaded into memory and refreshed every few seconds, plus one check function, is enough to start. What it lacks is a change history, fast updates across many apps, a disk cache for restarts and permissions.

How do I implement a percentage rollout?

Hash the flag key and the user id, take the result mod 100, and turn the feature on when the bucket is below the percentage. The same user always gets the same bucket, so raising the percentage only adds users.

Should feature flags be checked on every request?

Yes, as long as the check runs in memory. Load the rules once and refresh them in the background; never query a database or call a service per check.

What should happen if the flag can't be loaded?

The flag should be off, so the old, known path runs. Flagger.gg's SDKs treat an unknown, not-loaded or errored flag as off, and start from the last good ruleset on disk.

How do I implement feature flags in JavaScript or Go?

The pattern is the same in any language: a check function that reads in-memory rules. Flagger.gg has SDKs for Node/TypeScript (@flaggergg/node) and Go (flagger.gg/go); other languages are in development.

Ship your next change behind a flag.

Sign up, add an SDK key to your app and give your agent a token.

Sign up