Deploying and releasing are usually treated as the same event: code merges, the pipeline runs, and every user gets the change at once. If something breaks, the only fix is another deploy or a rollback.

Feature flags separate the two. Code goes to production switched off, and you decide later who sees it (1% of users, your own team, one pilot customer) without another deploy. Here's how to build a small, dependable flag system in Node.js, how percentage rollouts actually work, and how to keep flags from turning into permanent clutter.

What a feature flag is

At its simplest, a flag is a conditional:

if (flags.isEnabled('new-checkout', user)) { return renderNewCheckout(user); } return renderOldCheckout(user); 

The interesting part is everything behind isEnabled: where the rules live, how they're evaluated, and what happens when the flag source is unavailable.

Four kinds of flags (and why it matters)

Type Purpose Typical lifetime
Release flag Hide unfinished work, roll out gradually Days to weeks
Ops flag / kill switch Turn off an expensive or failing feature fast Long-lived
Experiment flag A/B test two variants Length of the test
Permission flag Enable a feature for a plan or a customer Long-lived

Release flags should be deleted soon after rollout. Kill switches and permission flags are meant to stay. Mixing them up is how codebases end up with hundreds of flags nobody dares to remove.

A minimal flag store

You don't need a vendor on day one. A table is enough:

CREATE TABLE feature_flags ( key TEXT PRIMARY KEY, enabled BOOLEAN NOT NULL DEFAULT false, rollout_pct INTEGER NOT NULL DEFAULT 0 CHECK (rollout_pct BETWEEN 0 AND 100), allow_list TEXT[] NOT NULL DEFAULT '{}', owner TEXT NOT NULL, expires_on DATE, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); 

owner and expires_on aren't used for evaluation. They're there so every flag has a person responsible for removing it.

Percentage rollouts that stay consistent

The naive version, Math.random() < 0.1, gives a user the new feature on one request and the old one on the next. You need the same answer for the same user every time, which means hashing:

import { createHash } from 'node:crypto'; function bucket(flagKey, userId) { const hash = createHash('sha256').update(`${flagKey}:${userId}`).digest(); // first 4 bytes as an unsigned int, mapped to 0–99 return hash.readUInt32BE(0) % 100; } 

Including the flag key in the hash matters. Without it, the same 10% of users would get every new feature first and quietly become your testers for everything.

Raising a rollout from 10% to 25% keeps the original 10% in, because anyone whose bucket was below 10 is also below 25. As you raise the number, users only ever move from off to on.

The evaluator

export function evaluate(flag, user) { if (!flag || !flag.enabled) return false; if (user?.id && flag.allow_list.includes(String(user.id))) return true; if (flag.rollout_pct >= 100) return true; if (flag.rollout_pct <= 0 || !user?.id) return false; return bucket(flag.key, user.id) < flag.rollout_pct; } 

The order of checks is deliberate: the master switch first, so a kill switch always wins; then the allow-list, so staff and pilot customers can see a feature at 0%; then the percentage.

Don't query the database on every request

Flags are read far more often than they change. Load them into memory and refresh on an interval:

export class FlagClient { constructor(db, { refreshMs = 15000 } = {}) { this.db = db; this.flags = new Map(); this.ready = this.refresh(); this.timer = setInterval(() => this.refresh().catch(this.onError), refreshMs); this.timer.unref(); } async refresh() { const { rows } = await this.db.query('SELECT * FROM feature_flags'); this.flags = new Map(rows.map((r) => [r.key, r])); } isEnabled(key, user) { return evaluate(this.flags.get(key), user); } onError = (err) => { // keep serving the last known flags; just log the failure console.error('flag refresh failed:', err.message); }; } 

Two decisions are hidden in there:

  • If a refresh fails, the old values stay. A problem with the flag store shouldn't become a site outage.
  • An unknown flag evaluates to false. If someone mistypes a key or deletes a row, the old, known-good path runs.

A 15-second refresh means a change can take up to 15 seconds to reach every instance. For most kill switches that's fine. If it isn't, push changes with PostgreSQL LISTEN/NOTIFY or Redis pub/sub and keep polling as the fallback.

Using it in an Express route

const flags = new FlagClient(pool); await flags.ready; app.get('/checkout', (req, res) => { if (flags.isEnabled('new-checkout', req.user)) { return res.render('checkout-v2'); } res.render('checkout'); }); 

For the frontend, don't send the whole flag table to the browser. Evaluate on the server and send only the results the page needs (for example { "new-checkout": true }), so unreleased feature names don't leak.

A safe rollout sequence

  1. Deploy with the flag at enabled = false. Nothing changes for users.
  2. Add your team to allow_list and test in production.
  3. Turn it on for 1–5%. Watch error rates and latency, split by flag state.
  4. Step up to 25%, 50% and 100% over hours or days.
  5. Once it's at 100% and stable, delete the old code path and the flag.

Step 3 only works if your logs and metrics record which variant each request got. Add the flag state to your structured logs; otherwise, when errors rise, you can't tell whether the new code is the cause.

Keeping flag debt under control

Every flag doubles the number of paths through a piece of code. A few habits keep that manageable:

  • Give every release flag an owner and an expires_on date, and fail a CI check (or post a weekly reminder) when a flag is past it.
  • Remove the flag in the same ticket as the rollout, not "later".
  • Keep flag checks at the edges (route handlers, top-level components) instead of scattering them through business logic.
  • Never reuse a flag key. A new rollout gets a new key, so stale cached values can't switch on the wrong thing.

Build or buy?

A table and about 60 lines of code cover most small and mid-sized apps. Hosted tools such as LaunchDarkly, Unleash, Flagsmith and GrowthBook become worth it when you need audit logs, approval workflows, targeting on many attributes, or experiments with statistics built in. Unleash, Flagsmith and GrowthBook can also be self-hosted. Whichever route you take, the same rules apply: sticky hashing, safe defaults, cached evaluation and flag expiry.

Quick checklist

  • [ ] Unknown or missing flags evaluate to false
  • [ ] Percentage rollouts hash flagKey + userId, not Math.random()
  • [ ] Flags are cached in memory and survive a failed refresh
  • [ ] The kill switch is checked before allow-lists and percentages
  • [ ] Logs and metrics record which variant each request got
  • [ ] Every release flag has an owner and an expiry date
  • [ ] Old code paths are deleted once a rollout reaches 100%

Prism Infoways is a web and software development company that offers web application development and related IT services.

This post was drafted with AI assistance.