What are feature flags in a monolith, and which kinds do you actually need?
A feature flag in a monolith is a runtime decision point inside your single deployable: the code for both paths ships in the same build, and a value read at request time chooses which path runs. You don't need a rebuild or a redeploy to switch. This decouples deploy (getting code onto servers) from release (exposing behaviour to users). Teams that ship a monolith several times a day can then merge unfinished work, roll out gradually, and turn off a bad change in seconds rather than waiting for a rollback pipeline.
Not every flag does the same job. The four common kinds differ in who flips them, how long they live, and how dynamic their evaluation must be:
| Kind | Purpose | Typical lifespan | Who changes it | Evaluation |
|---|---|---|---|---|
| Release toggle | Hide incomplete or unreleased work | Days to weeks | Developers | Mostly static, global |
| Ops / kill switch | Disable a costly or risky path under load or failure | Long-lived | On-call, platform | Global, must change fast |
| Experiment toggle | Compare variants across user cohorts | Weeks | Product, data | Per-user, sticky bucketing |
| Permission toggle | Gate features by plan, role, or tenant | Permanent | Product, billing | Per-user or per-tenant |
Most flag debt comes from pushing all four through one mechanism with one set of rules. A release toggle should die soon after rollout. A kill switch should never die. A permission toggle is really product logic. When they all look the same, nobody can tell which flags are safe to delete, so none get deleted. Give each kind its own naming prefix, an owner, and an expiry policy from day one.
How does an in-process flag module work?
The whole module exposes one function: isEnabled(flagKey, context). The context carries what targeting needs, such as user ID, tenant, region, or a request attribute. The function returns a boolean, or a variant name for experiments. Call sites never read a file, query a table, or hold a reference to the store. That one rule decides whether the module stays cheap to change.
The request path
- Call site. A handler calls
isEnabled("release.new-checkout", ctx)and branches on the result. It knows the key and nothing else. - Evaluator. The evaluator looks up the flag definition and applies its rules in a fixed order: kill switch, explicit allow/deny lists, percentage rollout, default. Percentage rollouts hash the flag key together with a stable context field, usually the user ID. This keeps a given user in the same bucket on every request and every instance, without storing any assignment.
- In-memory cache. Definitions are read from a process-local snapshot, not fetched per call. Evaluation then costs a hash-map lookup, so nobody is tempted to cache flag results in their own code.
- Backing store. A background refresher reloads the snapshot on an interval or on a change signal. If a reload fails, the evaluator keeps serving the last good snapshot. If no snapshot was ever loaded, it falls back to hardcoded defaults.
Why this makes migration a swap
Only the refresher knows about the store, so replacing a config file with a table touches one adapter. Moving to Unleash goes further. Its SDKs already provide evaluation and a local cache, so you can implement isEnabled on top of the SDK and delete your evaluator. Either way, the call sites do not change.
import { createHash } from "node:crypto";
type Ctx = { userId?: string; tenant?: string; region?: string };
type FlagDef = { killed?: boolean; allow?: string[]; deny?: string[]; percent?: number; default: boolean };
type Snapshot = Map<string, FlagDef>;
// Hardcoded defaults, used only until the first snapshot loads.
const DEFAULTS: Snapshot = new Map([["release.new-checkout", { default: false }]]);
let snapshot: Snapshot = DEFAULTS;
// Only the refresher knows where flags live. To change backends, swap `load`.
export function startRefresher(load: () => Promise<Snapshot>, intervalMs = 15_000) {
const refresh = async () => {
try { snapshot = await load(); }
catch (err) { console.warn("flag refresh failed; keeping last good snapshot", err); }
};
void refresh();
return setInterval(refresh, intervalMs);
}
// Deterministic bucket 0-99. The same flag and user give the same answer on every instance, with no stored assignment.
function bucket(flagKey: string, id: string): number {
return createHash("sha256").update(`${flagKey}:${id}`).digest().readUInt32BE(0) % 100;
}
// The single public entry point. Rules run in a fixed order.
export function isEnabled(flagKey: string, ctx: Ctx): boolean {
const def = snapshot.get(flagKey);
if (!def) return false; // Unknown flag: fail closed.
if (def.killed) return false; // Kill switch wins over everything.
if (ctx.userId && def.deny?.includes(ctx.userId)) return false;
if (ctx.userId && def.allow?.includes(ctx.userId)) return true;
if (def.percent !== undefined && ctx.userId) return bucket(flagKey, ctx.userId) < def.percent;
return def.default;
}
// Call site: it knows the key and the context, and nothing about storage.
// if (isEnabled("release.new-checkout", { userId: req.user.id })) { ... }
A minimal in-process flag module: isEnabled evaluates rules against an in-memory snapshot in a fixed order, and a background refresher behind a pluggable load adapter is the only code that touches the backing store.
Should flag state live in a config file or a database table?
A config file read at startup is the simplest store. Changing a flag means editing the file and redeploying or restarting, so every change passes through review and your deploy pipeline. A database table read through an in-memory cache with a short TTL lets you flip a flag at runtime without a deploy.
| Aspect | Config file | Database table + cache |
|---|---|---|
| How a change is made | Commit and redeploy | Update a row |
| Propagation delay | Length of a rollout | Up to one TTL per instance |
| Consistency during change | Mixed until rollout ends | Mixed until every cache expires |
| Depends on | Deploy pipeline | Application database |
| Audit trail | Version control history | Whatever you build |
Each process caches independently, so after an update some instances see the new value and others still serve the old one. The worst case is roughly one TTL plus query time, and it applies separately to every process. The state is eventually consistent. A kill switch with a 30-second TTL (an illustrative value) can keep the broken path running for up to 30 seconds after you flip it. Size the TTL against how long you can tolerate that delay.
Putting flags in the application database also ties flag availability to database health. A database outage then hits the flag reads you need for degrading gracefully. Decide the failure behavior per flag type:
- Release flags: off.
- Permission flags: deny.
- Kill switches: the safe state, meaning the expensive or risky path is disabled.
Serve the last known value while it is reasonably fresh. When it goes stale or no value was ever loaded, fall back to the compiled-in default.
import time
# Compiled-in defaults. These are used when no value was ever loaded or the last one is too old.
DEFAULTS = {
"release.new_checkout": False, # release flag: off
"perm.bulk_export": False, # permission flag: deny
"kill.recommendations_off": True, # kill switch: risky path disabled
}
TTL_S = 30 # illustrative: worst-case propagation delay per process
MAX_STALE_S = 300 # illustrative: how long a last known value is trusted
class FlagCache:
def __init__(self, load_flags):
# load_flags() queries the app DB, e.g. SELECT name, enabled FROM feature_flags,
# and returns a dict mapping flag name to bool.
self._load = load_flags
self._values = {}
self._loaded_at = None # time of the last successful load
self._attempted_at = None # time of the last attempt, so a DB outage is retried once per TTL, not on every call
def get(self, name):
now = time.monotonic()
if self._attempted_at is None or now - self._attempted_at >= TTL_S:
self._attempted_at = now
try:
self._values = self._load()
self._loaded_at = now
except Exception:
pass # store unreachable: keep the last known values for now
fresh = self._loaded_at is not None and now - self._loaded_at < MAX_STALE_S
if fresh and name in self._values:
return self._values[name]
# Stale, never loaded, or unknown flag: fall back to the safe default.
return DEFAULTS[name]
A per-process flag cache that reloads from the database at most once per TTL. It serves the last known values while they are reasonably fresh, then falls back to compiled-in safe defaults: release flags off, permissions denied, kill switches engaged.
How do you use feature flags with trunk based development?
Trunk based development means merging to main at least daily, and half-finished features are what make that hard. A release toggle lets you merge the incomplete code while keeping it unreachable in production. The branch stays short. The feature stays dark until the toggle flips.
Test both paths
The cost is that every toggle is a fork in the code, and both sides ship. Run your test suite with the flag on and with it off. The off path is what production runs today. The on path is what it will run next week. If CI only exercises the default, the first real test of the new path happens when you flip it for users.
Interacting flags make this worse. Three independent booleans produce eight combinations. Most are harmless, but the ones that touch the same code path need explicit tests. Keep the number of overlapping flags small, and do not write code that branches on two flags at once.
Don't trade long branches for long flags
A flag that sits half-built for a quarter is a long-lived branch with extra steps. It has the same divergence, plus runtime complexity. Set a removal date when you create the flag.
Flags that touch data
A toggle only controls which code runs. It cannot undo what that code already did. Rows written in a new format, emails sent, and calls to external APIs all stay done when you switch the flag off. Use expand/contract sequencing:
- Add the new schema alongside the old one.
- Have the code tolerate both formats.
- Migrate or backfill the data.
- Gate background jobs separately from request paths.
- Drop the old schema only after the flag is removed.
import pytest
# Flags are passed in explicitly so tests can force each path.
def display_name(row: dict, flags: dict) -> str:
# Read side accepts both row formats, whatever the flag says.
# Rows written while 'split_name_columns' was on keep the new
# format after the flag is flipped off. The toggle can't undo them.
if "first_name" in row:
name = f"{row['first_name']} {row['last_name']}"
else:
name = row["full_name"]
# Release toggle: new UI behavior, merged but dark by default.
if flags.get("short_greeting", False):
return name.split()[0]
return name
OLD_ROW = {"full_name": "Ada Lovelace"}
NEW_ROW = {"first_name": "Ada", "last_name": "Lovelace"}
# Run every test with the flag off (today's production) and on (next week's).
# Cross it with both data formats: 2 flag states x 2 row shapes = 4 cases.
@pytest.mark.parametrize("short_greeting", [False, True])
@pytest.mark.parametrize("row", [OLD_ROW, NEW_ROW], ids=["old_row", "new_row"])
def test_display_name_all_paths(row, short_greeting):
flags = {"short_greeting": short_greeting}
expected = "Ada" if short_greeting else "Ada Lovelace"
assert display_name(row, flags) == expected
A pytest parametrization runs one function with a release toggle on and off and against both the old and the expanded row format, so CI covers every path and data shape that production can hit.
How do you keep feature toggles from becoming permanent debt?
A flag is cheap to add and expensive to forget. Every toggle doubles the code paths behind it, and the cost lands later, on whoever has to reason about behavior they can't see in the code alone.
Give every flag an owner and an expiry
Register each flag with an owner and a removal date when it is created. Then add a test or lint step that fails the build once a date has passed. A failing build forces a decision: remove the flag or consciously extend it. A calendar reminder or a wiki page does not. Make "delete the losing branch and the flag definition" part of the definition of done for the feature, not a follow-up ticket that competes with new work.
Why stale flags are dangerous
A flag that nobody has touched in months has become hidden configuration. Its "off" branch still compiles, but it hasn't run against current data or current neighboring code. If someone flips it during an incident or by mistake, you reactivate untested code in production. That is how a toggle meant to reduce risk ends up causing an outage.
Make changes and state visible
Log every flag change with who flipped it, what the old and new values were, and when. Include the active flag state in error reports and structured logs. When a bug appears, the first question is often "what changed?" An audit trail and per-request flag context can answer it in minutes. Without them, you spend hours reconstructing state.
# flags.py: one registry; every flag must declare an owner and a removal date
import logging
from dataclasses import dataclass
from datetime import date
audit = logging.getLogger("flags.audit")
@dataclass(frozen=True)
class Flag:
owner: str
remove_by: date
default: bool = False
FLAGS = {
"new_checkout_flow": Flag(owner="payments-team", remove_by=date(2026, 12, 31)),
"bulk_export_v2": Flag(owner="reporting-team", remove_by=date(2027, 2, 15)),
}
_state = {name: f.default for name, f in FLAGS.items()}
def set_flag(name: str, value: bool, actor: str) -> None:
old = _state[name] # KeyError on unregistered names: no ad-hoc flags
_state[name] = value
# Audit trail: who flipped which flag, old -> new (the log record carries the timestamp)
audit.info("flag_changed", extra={"flag": name, "old": old, "new": value, "actor": actor})
def active_flags() -> dict:
# Attach this snapshot to error reports and structured log context
return dict(_state)
# Runs in CI with pytest: the build fails once any flag is past its removal date,
# forcing a decision to delete the flag or consciously extend it
def test_no_expired_flags():
expired = [f"{n} (owner {f.owner}, due {f.remove_by})"
for n, f in FLAGS.items() if f.remove_by < date.today()]
assert not expired, "Remove or extend: " + ", ".join(expired)
A minimal in-process flag registry. Each flag has an owner and a removal date, every change is written to an audit log, error reports can include a snapshot of active flags, and a pytest check fails the build when a flag is past its removal date.
When should you avoid a homegrown flag module, and when should you adopt Unleash?
A homegrown module stops being the cheap option once these needs appear:
- Percentage rollouts and user targeting at scale. Sticky bucketing, segment rules, and per-environment strategies are easy to get subtly wrong. Two code paths that hash user IDs differently will put the same user in different cohorts.
- Non-engineers flipping toggles. Product or support staff need a UI with role-based permissions, approval steps, and guardrails against turning off a kill switch in production. Building that well is real work.
- Formal audit requirements. If compliance asks who changed a flag, when, and why, you need a durable event history, not a commit log someone has to interpret.
- The monolith splitting into services. Once two processes must agree on flag state for the same request, you need a shared evaluation source and client SDKs. Unleash provides both, with local evaluation and caching in the client.
The opposite failure is quieter. Someone adds a percentage field, then a targeting rule, then an admin page so the PM stops filing tickets, then a history table. A year later you own an unplanned internal product with no roadmap, no dedicated owner, and an on-call burden nobody budgeted for. If your backlog for the flag module keeps growing, compare it honestly against adopting a dedicated service.
Some problems should not use flags at all. A flag cannot make a destructive schema migration reversible, because both code paths still share one schema. Use expand-and-contract migrations for that. Long-lived per-customer configuration and entitlements also belong in your domain model, not in toggles.
What are the alternatives, and how do they compare on cost?
The realistic choice is not "which flag product" but which of four approaches fits your release cadence and the people who need to flip switches.
| Option | Build and maintenance | Operational dependencies | Propagation speed | Targeting | Audit |
|---|---|---|---|---|---|
| No flags (branch releases, rollback) | None | CI/CD only | One deploy | None | Git history |
| Static config flags | Very low | Config delivery | Redeploy or restart | Environment-level | Git history |
| In-process module, database-backed | Moderate: you own UI, cache, tests | Your existing database | Cache TTL, seconds to minutes | What you build | Whatever you log |
| Self-hosted Unleash | Low code, ongoing upgrades | Extra service and its storage | SDK polling interval | Strategies, segments, gradual rollout | Built-in event log |
Hosting cost rarely decides this. Flags rarely fail because of infrastructure. They fail because every active flag doubles some code paths that must be tested and reasoned about in review.
Illustrative estimate (assumed numbers, not a benchmark)
Monthly flag overhead (hours) = F × (t + r)
- F = active flags = 25 (assumed)
- t = hours per flag per month spent keeping tests for both paths green = 0.5 (assumed)
- r = hours per flag per month of extra review and debugging attention = 0.3 (assumed)
25 × (0.5 + 0.8 − 0.5) = 25 × 0.8 = 20 hours per month.
With these assumptions, the flags cost about half an engineer-week every month whichever tool stores them. Plug in your own F, t and r. If the result is significant, the cheapest option is fewer active flags, not a different flag store.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to feature flags monolith, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.