What are feature flags in a monolith, and which types do you actually need?
In a monolith, a feature flag is a runtime switch inside the single deployable artifact that selects between code paths without a redeploy. Every module ships together, so flags let you separate deploying code from releasing behavior. That shared artifact is also the risk: one flag can reach into billing, search and email at once.
Flags differ mainly in purpose and lifespan, and those two properties determine how each should be handled.
| Type | Typical placement | Safe default | Expected lifetime | Removal expectation |
|---|---|---|---|---|
| Release | Entry point of unfinished feature | Off | Days to weeks | Delete once fully rolled out |
| Experiment | Request handling, per user/cohort | Control variant | Length of the experiment | Delete when a winner is chosen |
| Ops / kill switch | Around expensive or external calls | On (normal operation) | Months to indefinite | Review periodically; may stay |
| Permission | Authorization or entitlement checks | Off (deny) | As long as the product tier exists | Rarely removed; treat as config |
Decide the type when you create the flag, because the type sets its default, who may flip it and when it is due for deletion. A release flag created without an owner and an expiry tends to become permanent. Product engineers mostly create release and experiment flags. Platform and on-call engineers own ops flags. Permission flags belong with whoever owns entitlements.
Ops and permission flags follow different rules: they are meant to last. Record each flag's type explicitly and review it. Classifications drift, such as a release flag that quietly becomes a kill switch, and cleanup tooling depends on these labels being correct.
How do feature flags work at runtime?
A flag system has three parts: where flag definitions are stored, how they reach the running process, and how a single decision is computed.
Definitions. Each flag has a key, a default value, and optionally a set of targeting rules. The definitions can live in a config file in the repository, a database table, or a dedicated flag service. A rule might say "on for tenant IDs in this list," "on for internal staff accounts," or "on for a percentage of users."
Delivery to the process. Most setups keep the current definitions in memory inside the monolith and refresh them in the background, either by polling the store on an interval or by receiving pushed updates. Evaluation then becomes a local, in-memory computation with no network call on the request path. The trade-off is propagation delay: after someone flips a flag, each running instance picks up the change only on its next refresh. If the store is unreachable, the process keeps its last known definitions or falls back to the coded default. This is why the "safe default" column in the table above matters.
Evaluation. A decision takes the flag key plus an evaluation context, typically the user ID, tenant, region, or account tier, and runs the rules in order. Percentage rollouts usually hash a stable identifier such as the user ID together with the flag key into a bucket and compare the bucket against the rollout percentage. Because the hash is deterministic, the same user gets the same answer on every request, and raising the percentage only adds users. Nobody already in the rollout gets switched back.
The rest of this article is about where that evaluation result goes once it has been computed. The flag system decides. Your code structure determines how far that decision spreads.
Why do feature flags turn into spaghetti conditionals?
Flag debt is usually blamed on missed cleanup, but the damage starts earlier, when the flag is first wired in. The usual pattern is a call to the flag client in the middle of business logic, such as flags.isEnabled("new-pricing", user), placed wherever the behavior differs. Take a typical calculateInvoice function. It checks new-pricing before computing line items. It checks the flag again before applying discounts, because the new discount rules depend on the new line-item shape. It checks once more before rounding. Inside one branch it also checks tax-v2, which only makes sense when new-pricing is on. Old and new logic are interleaved line by line, and nothing in the code states which combinations are valid.
That structure has three costs.
- More runtime states. Each active flag can double the number of possible paths. Three interacting flags give eight combinations. Tests usually cover two of them, and production may hit any of them, especially if the flag is evaluated several times per request and its value changes partway through.
- Harder reviews. A reviewer has to trace every branch by hand to understand what one configuration does.
- Blocked teams. If the flag sits in shared code, the team that owns it effectively locks that code. Nobody else can safely refactor it until the flag is removed.
Cleanup tooling can't fix this after the fact. The structure has to be designed differently from the start.
// BEFORE: the anti-pattern. The flag client is called inside business logic,
// the same flag is read three times per call, and tax-v2 only works when
// new-pricing is on, but nothing in the code says so.
function calculateInvoice(order: Order, user: User): Invoice {
// Read #1: picks the line-item shape
const items = flags.isEnabled("new-pricing", user)
? buildLineItemsV2(order)
: buildLineItems(order);
let subtotal = sum(items);
// Read #2: the new discount rules assume V2 line items. If the flag
// changed since read #1, V2 discounts run against V1 items.
if (flags.isEnabled("new-pricing", user)) {
subtotal = applyTieredDiscounts(items, subtotal);
// Nested flag: tax-v2 is only valid inside new-pricing.
// That dependency exists only because of where this line sits.
if (flags.isEnabled("tax-v2", user)) {
subtotal += computeTaxV2(items, user.region);
} else {
subtotal += computeTax(subtotal, user.region);
}
} else {
subtotal = applyLegacyDiscount(subtotal, order.couponCode);
subtotal += computeTax(subtotal, user.region);
}
// Read #3: rounding rules differ too, so this is one more place the
// old and new paths can disagree within a single request.
const total = flags.isEnabled("new-pricing", user)
? roundHalfEven(subtotal, 2)
: Math.round(subtotal * 100) / 100;
return { items, total };
}
A typical interleaved calculateInvoice that queries the flag client three times, nests a dependent flag inside a branch, and mixes old and new pricing logic line by line, so no single configuration can be read in one place.
How does separating the toggle decision from the toggle point work?
The split is between two concerns that flag client libraries tend to merge. The toggle decision answers "is this flag on for this request?" The toggle point is the place where behavior differs. Domain code should own toggle points but never make decisions.
Decisions sit behind a small interface, such as a FlagDecisions with one method per flag. Only the edge of the application depends on it. Evaluation happens once, at request entry or in the composition root, and the result travels down the call stack in one of two forms. It can be a per-request flag context, or it can be an implementation that wiring has already chosen.
HTTP request
|
v
[ entry middleware ] --> FlagDecisions.evaluate(user, tenant)
| |
| FlagContext { newPricing: on, asyncExport: off }
v |
[ composition root ] <---------+
| wires PricingStrategy = TieredPricing
v
[ billing module ] -- calls PricingStrategy, no flag client import
Evaluating once means a request cannot see a flag flip halfway through and charge one price while displaying another. Tests become simpler too. You pass a fake decision source with fixed answers and skip mocking the vendor client.
There are two costs. First, eager evaluation computes flags that a request never reaches. Second, some targeting rules need data that only exists deep in the call path, such as an order total or a resolved account tier. Both are handled by lazy evaluation behind the same interface. The context exposes a decision that resolves on first access and memoizes the result for the rest of the request, so consistency holds. Domain code still never sees the flag client.
HTTP request
|
v
+------------------------+ +------------------------------+
| entry middleware |----->| FlagDecisions (interface) |
| evaluate(user, tenant) | | real: vendor flag client |
+------------------------+ | test: fake, fixed answers |
| +------------------------------+
v
+--------------------------------------------------+
| FlagContext (one per request, memoized) |
| newPricing : on (eager, at entry) |
| asyncExport : off (eager, at entry) |
| bulkDiscount : lazy (resolves on first access) |
+--------------------------------------------------+
v
+--------------------------------------------------+
| composition root |
| wires PricingStrategy = TieredPricing |
+--------------------------------------------------+
v
+--------------------------------------------------+
| billing module (no flag client import) |
| PricingStrategy.price(order) |
| ctx.bulkDiscount(orderTotal) |
| first access: evaluates via FlagDecisions |
| later accesses: memoized value |
+--------------------------------------------------+
The entry middleware evaluates flags once into a per-request FlagContext. The composition root uses it to wire a concrete strategy, and the billing module sees only that strategy plus lazy, memoized decisions, never the flag client.
How do you implement toggle points with strategy objects and module boundaries?
The implementation has four steps.
-
Define a narrow interface owned by the module. If the billing module is changing how it calculates proration, it declares a
ProrationPolicywith one method. The interface describes the behavior that varies, not the flag. Callers never see a boolean. -
Write old and new behavior as sibling classes.
LegacyProrationPolicyandDailyProrationPolicyeach implement the interface completely. Neither one checks a flag. Each can be tested in isolation, and each can be deleted without editing the other. -
Select the implementation in dependency wiring. The module's factory or container binding reads the request's flag context and returns one strategy. Reference the key as a literal constant,
BILLING_DAILY_PRORATION = "billing.daily-proration", defined once in the module. A plain text search for that string then finds the definition, the wiring, and the flag configuration. Building keys by concatenation would break that search. -
Keep the flag inside the module boundary. Other modules call
billing.invoiceFor(account)through the module's public interface. They never import the strategies or the flag constant. The rollout stays a private detail of billing, and removing the flag touches only one directory.
Trade-offs
Indirection. Indirection costs readability. A reader has to follow the wiring to learn which code path runs, so the selection logic should stay in one obvious place.
Duplication. Duplication is the bigger risk. While both strategies exist, a bug fix may need to land in both. Expect divergence once the old path stops getting attention. Duplication turns into debt once the new path is at full rollout and nobody plans to switch back. From then on, the legacy class is dead code that still has to compile.
// billing/proration.ts: internal to the billing module, not re-exported
export const BILLING_DAILY_PRORATION = "billing.daily-proration"; // literal, so text search finds it
export interface FlagContext { isEnabled(key: string): boolean; }
// Narrow interface for the behavior that varies. No boolean appears here.
export interface ProrationPolicy {
prorate(amountCents: number, daysUsed: number, daysInPeriod: number): number;
}
// Old behavior: bill in half-month blocks. Deleting this class later touches nothing else.
export class LegacyProrationPolicy implements ProrationPolicy {
prorate(amountCents: number, daysUsed: number, daysInPeriod: number): number {
return daysUsed * 2 <= daysInPeriod ? Math.round(amountCents / 2) : amountCents;
}
}
// New behavior: bill per day used. Neither strategy checks the flag.
export class DailyProrationPolicy implements ProrationPolicy {
prorate(amountCents: number, daysUsed: number, daysInPeriod: number): number {
return Math.round((amountCents * daysUsed) / daysInPeriod);
}
}
// Wiring: the only place that reads the flag.
export function prorationPolicyFor(flags: FlagContext): ProrationPolicy {
return flags.isEnabled(BILLING_DAILY_PRORATION)
? new DailyProrationPolicy()
: new LegacyProrationPolicy();
}
// billing/index.ts: the public surface. Other modules see only this.
export class BillingModule {
constructor(private readonly flags: FlagContext) {}
invoiceFor(account: { planCents: number; daysUsed: number; daysInPeriod: number }): number {
const policy = prorationPolicyFor(this.flags);
return policy.prorate(account.planCents, account.daysUsed, account.daysInPeriod);
}
}
A billing module in TypeScript that keeps its proration toggle internal: a narrow ProrationPolicy interface, two strategy classes that never check the flag, one wiring function that reads a literal flag key, and a public invoiceFor method that other modules call without seeing the flag.
When should you avoid strategy objects and just use a conditional?
That cost is worth paying only when the flag will live long enough, or reach far enough, to justify two implementations. Many flags won't. A release flag expected to live a few days and touching one call site can be a single conditional at the module edge, where the request enters the feature. One if in one place is easy to find and easy to delete, so it has little room to spread.
Use four criteria to decide:
- Expected lifespan. Days favour a conditional. Weeks or more favour a strategy object.
- Number of toggle points. One point is fine. Several points that must stay consistent need a single decision behind an abstraction.
- Cross-module reach. If the flag would leak into another module's code, give it a boundary.
- Flag type. Release flags are short by design. Ops and permission flags are long-lived and earn the full pattern.
Sometimes you don't need a runtime flag at all:
| Approach | Upfront cost | Switchable at runtime | Cleanup burden |
|---|---|---|---|
| Plain conditional at module edge | Very low | Yes | Low if removed within days; grows quickly if not |
| Config value read at startup | Low | No (restart or redeploy) | Low |
| Branch by abstraction, no runtime flag | Medium | No | Medium: delete old implementation and seam |
| Short-lived feature branch | Low | No | Merge conflicts grow with branch age |
| Dark launch behind unexposed route | Low | Yes, by exposing the route | Low: route removal or promotion |
The conditional only stays cheap if you remove it promptly. Put its removal on the same ticket that introduces it.
What are the alternatives to runtime feature flags?
Runtime flags are one way to separate deploying from releasing. Depending on what you need, other mechanisms may cover it with less ongoing cost.
- Startup configuration. An environment variable or config file value read once at boot. This works well for per-environment differences and for switches you change rarely. The limitations: changing it requires a restart or redeploy, and it cannot target individual users or tenants.
- Branch by abstraction without a flag. You introduce the interface and the new implementation, and switch over in a single commit when the new code is ready. You get the same seam as the strategy pattern above, but not runtime control. This fits refactors where users should see no behavior change.
- Short-lived feature branches. Isolation happens in version control instead of in the running code. This is acceptable when the branch lives for a day or two. Merge pain grows with branch age, which is the main reason teams move to flags.
- Dark launches behind unexposed routes or UI. The code is deployed and reachable only by direct URL or internal tooling. Release means exposing the entry point. There is no per-request evaluation inside domain logic.
- Deployment-level rollout: canary or blue-green. A load balancer sends a fraction of traffic to instances running the new build, or switches all traffic between two environments. Rollback means routing back to the old version. In a monolith, the unit is the whole artifact, so you cannot roll out one feature while holding back another that shipped in the same build. You also cannot target specific customers by business attributes.
- An entitlements or permissions system. For permission-type flags, a proper entitlement model is usually the better long-term home. A tier that customers pay for is product configuration, not a temporary toggle.
The choice usually comes down to two questions. Do you need to change behavior without a deploy? Do you need to target a subset of users smaller than "all traffic on these instances"? If the answer to both is no, one of the simpler options is likely enough.
How do release flags support trunk-based development?
Trunk-based development asks everyone to integrate into the main line at least daily, which means half-finished features land in production code long before they are ready for users. A release flag makes that safe. The new code path ships dark, the old path stays live, and the main line remains deployable at every commit. The flag replaces the long-lived feature branch as the isolation mechanism, and conflicts get resolved in small increments instead of one painful merge at the end.
This only works if both lifetimes stay short. A branch that lives for a day keeps merge pain low. A release flag that lives for a few weeks keeps the number of dormant code paths low. A release flag that outlives its feature has become configuration nobody owns.
While the flag exists, test both sides. Parametrize the test over the flag value so the same assertions run against the legacy strategy and the new one. That catches the common failure where the new path passes and a refactor quietly breaks the old one. The example that follows runs one test function against both strategies.
Keep the combination space small by never letting one release flag depend on another. Ten independent boolean flags already produce 1,024 combinations, so you will not test them all. Test each flag in isolation against the production defaults, and accept that coverage. When the flag is removed, delete the parametrization and the test case for the losing path in the same commit.
import pytest
def legacy_shipping_cost(weight_kg: float) -> float:
# Old path: stays live while the flag is off.
return round(5.0 + 1.2 * weight_kg, 2)
def tiered_shipping_cost(weight_kg: float) -> float:
# New path: ships dark behind the release flag.
rate = 1.2 if weight_kg <= 10 else 1.0
return round(5.0 + rate * weight_kg, 2)
def shipping_cost(weight_kg: float, flags: dict) -> float:
# Single decision point; the flag reads no other flag.
if flags.get("release_tiered_shipping", False):
return tiered_shipping_cost(weight_kg)
return legacy_shipping_cost(weight_kg)
@pytest.mark.parametrize("flag_on", [False, True], ids=["legacy", "tiered"])
def test_shipping_cost_behaviour(flag_on):
flags = {"release_tiered_shipping": flag_on} # other flags at prod defaults
assert shipping_cost(0, flags) == 5.0
assert shipping_cost(2, flags) == 7.4
assert shipping_cost(20, flags) > shipping_cost(2, flags)
@pytest.mark.parametrize("flag_on, expected", [(False, 29.0), (True, 25.0)])
def test_heavy_parcel_pricing(flag_on, expected):
assert shipping_cost(20, {"release_tiered_shipping": flag_on}) == expected
A pytest example that parametrizes over a single release flag so the same tests run against both the legacy and new pricing strategies, with a separate case for behaviour that is meant to differ.
How do you automate toggle cleanup and detect flag debt?
Removal only happens reliably if it is decided when the flag is created. Give every flag a registry entry with its key, owner, type (release, experiment, ops, permission), creation date, and either an expiry date or a removal condition such as "100% rollout for two weeks." Open the removal ticket in the same change that opens the feature ticket, so the cleanup is already in the backlog.
A registry and a CI check
The registry can be a plain YAML or JSON file in the repository, one entry per flag. A CI script then does three comparisons:
- It extracts flag key constants from the source with
grep -rhoEand a pattern matching your naming convention. - It lists keys that are in code but not in the registry (missing) and keys in the registry with no code references (orphaned).
- It lists release and experiment flags whose expiry date has passed. Ops flags carry
expiry: noneand are exempt by name, not by omission.
Missing keys should fail the build. Expired flags can start as a visible warning and become a failure once the team trusts the check.
There are two limits. Keys assembled at runtime, such as "checkout_" + region, will not appear in a static search, so ban that pattern or register the prefix. Also, a failing expiry check without scheduled removal work gets bulk-extended by a script, and the check then means nothing.
Illustrative estimate: assume 40 stale flags, each costing 15 minutes a month in review questions and test maintenance. That is about 120 hours a year. At an assumed 2 hours per removal, clearing them costs 80 hours once.
How do structured feature flags save engineering time?
Flags do not save time automatically. The savings come from specific workflows they replace, and the structure described above is what keeps those savings from being eaten by flag debt.
- Less merge work. Integrating into the main line daily behind a release flag replaces one large merge at the end of a long-lived branch with many small ones. Conflicts surface while the context is fresh and the diff is small.
- Fewer coordinated release events. Deploys go out on the normal schedule. Turning a feature on becomes a separate, low-ceremony action, often done by the team that owns the feature. Nobody has to hold a deploy back to wait for one unfinished change.
- Faster mitigation during incidents. Flipping a kill switch or turning off a release flag takes effect on the next refresh. A revert has to go through review, build and deploy. On-call engineers can stop the damage first and debug afterwards, without an emergency release.
- Cheaper validation in production. Turning a feature on for internal accounts or one tenant exposes real data and traffic patterns. Doing that is cheaper than reproducing them in staging, and problems show up before full rollout.
- Cheaper tests and reviews when decisions are centralized. Because evaluation happens once and domain code receives a strategy, tests pass a fake decision source instead of mocking the flag client. Reviewers read one implementation at a time instead of tracing interleaved branches.
- Removal becomes deletion. With sibling strategy classes, a module-local flag constant, and a registry entry, removing a flag means deleting one class, one wiring branch, one registry line and one test case. Nobody has to untangle conditionals across a shared function.
The same mechanisms cost time when they are applied carelessly. Flags scattered through shared code block refactoring. Untested flag combinations cause incidents. Stale flags add review overhead, as the illustrative estimate above shows. The net result depends on keeping flags typed, owned, bounded to a module and scheduled for removal.
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.