What counts as a stale feature flag, and does it depend on the flag type?

Feature toggle debt is the cost of every flag that still forks your code after the decision it guarded has been made. In a monolith that cost is shared: one forgotten flag in a hot path adds a branch every team must read, test, and reason about, even teams that never touched it. A flag is stale when it no longer controls a live decision. What that means depends on why the flag exists.

Flag type Expected lifespan Stale when
Release Days to weeks Fully rolled out (or rolled back) and unchanged for a full release cycle
Experiment Length of the test A winner is chosen and results are recorded
Ops / kill switch Indefinite The guarded dependency or code path no longer exists
Permission / entitlement Life of the product tier The plan, customer segment, or feature is retired

Why one expiry rule fails

Kill switches are meant to sit untouched for months. A switch that sheds load from a fragile downstream service is valuable because nobody flips it until an incident. An "untouched for 90 days" rule would delete exactly these flags first.

Teams learn to avoid the rule. They set expiry dates two years out or extend them by reflex, and the dates stop carrying any meaning. Assign the definition of stale by flag type when the flag is created. A flag should stay as long as the decision it encodes is still open, or as long as it protects a path that still exists.

Why should flag cleanup start on the day the flag is created?

On the day a flag is created, the author knows exactly why it exists, who owns it, and what result will make it unnecessary. Eighteen months later, that knowledge has usually left with a reorg or a departed engineer. Rebuilding it then means reading commit history, asking around in chat, and guessing whether removing the flag will break a customer. Recording it on day one costs a few minutes.

Every flag should carry five pieces of metadata, and a flag missing any of them should fail review:

  • Owning team, not an individual, so ownership survives turnover.
  • Flag type, such as release, experiment, ops, or permission, because the type determines what "stale" means.
  • Creation date, so age can be computed rather than estimated.
  • Removal condition, stated as something you can check, like "100% rollout for two weeks with no rollback."
  • Linked removal ticket, created now and scheduled into the backlog.

Store this in a single typed registry, such as an enum or constant class where each flag key is declared once together with its metadata. Call sites then reference the symbol, not a raw string. This makes cleanup tractable. A compiler or IDE can find every usage, and deleting the entry turns each remaining reference into a build error. Keys assembled at runtime, such as "checkout_" + region, defeat both checks. No search can prove a flag is unused when its name only exists while the program runs.

Skipping this step does not save cost. It moves the cost to later. Each untracked flag adds branches that reviewers must reason about, and it multiplies the configurations tests should cover. It also leaves later engineers afraid to delete code they cannot explain.

// flags.ts: the only place a flag key may be declared.
type FlagType = "release" | "experiment" | "ops" | "permission";

// Every field is required, so a flag missing metadata fails type-checking in CI.
interface FlagMeta {
  owner: string;         // a team, not a person, so ownership survives turnover
  type: FlagType;        // the type decides what "stale" means
  created: string;       // ISO date, so age can be computed
  removeWhen: string;    // a condition someone can actually check
  removalTicket: string; // filed on day one and scheduled in the backlog
}

export const FLAGS = {
  newCheckoutFlow: {
    owner: "team-payments",
    type: "release",
    created: "2026-03-02",
    removeWhen: "100% rollout for 14 days with no rollback",
    removalTicket: "PAY-1423",
  },
  searchRankingV2: {
    owner: "team-search",
    type: "experiment",
    created: "2026-05-19",
    removeWhen: "experiment readout signed off; winning variant hard-coded",
    removalTicket: "SRCH-877",
  },
} as const satisfies Record<string, FlagMeta>;

// Only declared keys are valid. Deleting an entry turns every call site into a build error.
export type FlagKey = keyof typeof FLAGS;

export function isEnabled(key: FlagKey, evaluate: (key: string) => boolean): boolean {
  return evaluate(key);
}

// OK: checked by the compiler and found by find-references:
//   isEnabled("newCheckoutFlow", provider.evaluate)
// Rejected: a runtime-built key is a plain string, not a FlagKey:
//   isEnabled(`checkout_${region}`, provider.evaluate)

A typed TypeScript flag registry where required metadata fields make an incomplete flag fail type-checking, and a key union lets the compiler reject runtime-built flag names.

How do you detect stale flags from operational signals?

Most stale flags can be spotted from evaluation data and configuration, without reading code. Four signals catch the majority of them:

Signal What it suggests Main false-positive risk
Same value everywhere for a sustained period Rollout finished; the branch is now fixed Flag guards a rarely run path
Code default differs from configured value Config is propping up an outdated default Default deliberately kept safe for outages
No evaluations at all Call sites deleted or never deployed Code path only runs occasionally
Past declared expiry Owner's own deadline has passed Expiry set too optimistically

"Unchanged for N days" is a heuristic. Each team should tune N to its release cadence and flag types. A team that deploys many times a day can use a much shorter window than one that ships monthly. A single threshold applied to every flag will either flood the backlog or miss real debt.

Window length matters most for flags that only matter occasionally. Examples are end-of-period billing jobs, seasonal features and disaster-recovery paths. A failover toggle might go unevaluated for months and still be essential. Set the observation window to cover at least one full cycle of the path it guards. Better still, tag these flags with their expected cadence so the detector can skip them.

Also inspect targeting rules, not just the default. A flag can serve the new path to almost all traffic while one tenant is still pinned to the old one, perhaps because of a contract or a pending migration. If you remove the flag, that tenant is silently moved to the new path.

How do you safely remove a feature flag from a monolith?

Start by finding every reference site, and treat a clean grep as a lead, not proof. Search for the key as a string literal and through any constant that wraps it. Look for keys assembled at runtime, such as a prefix joined with a tenant or plan name, because those will never match a literal search. Check templates and views, background jobs, scheduled tasks, migrations that branch on the flag, tests, and config files that set overrides per environment. Then look outside the repository. Mobile clients, partner integrations, and other services may read the flag through an API the monolith exposes, and their code is not in your search results.

Remove the flag in this order:

  1. Confirm the winning branch and its value in every environment, including per-tenant overrides.
  2. Hard-code that value at each call site.
  3. Delete the losing branch and any code that only it reached.
  4. Delete or update the tests that covered the losing branch or toggled the flag.
  5. Deploy, and confirm the new build is serving all traffic.
  6. Only then delete the flag definition from the store.

The order matters because of what happens on a failed lookup. If you delete the definition while code still evaluates the flag, most SDKs return the default value written at the call site. That default is often false, which was usually the old path. The result is a silent rollback of the feature you meant to keep, with no deploy to point to when you investigate.

# BEFORE: the call site still evaluates the flag.
# If the definition is deleted from the store first, the lookup fails,
# the SDK returns default=False, and checkout silently reverts to the old path.
CHECKOUT_V2 = "checkout-v2"  # constant wrapper: grep for both this name and the string

def checkout(cart, user, flags):
    if flags.is_enabled(CHECKOUT_V2, user=user, default=False):
        return new_checkout(cart, user)
    return legacy_checkout(cart, user)  # losing branch

# Dynamic keys like this never match a literal search for "checkout-v2":
def plan_limit_enabled(user, flags):
    return flags.is_enabled(f"limits-{user.plan}", user=user, default=False)


# AFTER (steps 2-3): the winning value is hard-coded by removing the check.
# legacy_checkout() and anything only it called are deleted in the same change.
# The flag definition stays in the store until this build serves all traffic.
def checkout(cart, user):
    return new_checkout(cart, user)


# Order of operations:
#
#  Engineer          Code / CI            Deploy             Flag store
#     |  1. confirm winning value in every env + tenant overrides   |
#     |------------------------------------------------------------>|
#     |  2-4. hard-code, delete losing branch, fix tests            |
#     |------------------>|                                         |
#     |                   |  5. deploy, verify 100% on new build    |
#     |                   |---------------->|                       |
#     |  6. delete flag definition (only now)                       |
#     |------------------------------------------------------------>|

A before/after Python call site for a flag removal, showing the constant and dynamic-key cases a grep can miss and the order of steps that keeps the flag definition in place until no deployed code evaluates it.

What dead code is left behind after the branch is gone?

Deleting the if statement is the easy part. The losing branch usually had supporting code, and nothing points at it once the conditional is gone. Walk outward from the removed branch and check each of these:

  • Helper functions and classes called only from the dead path. Static analysis or "find usages" will flag some of them. Reflection, dependency injection and string-based dispatch will hide others.
  • Config keys and environment variables that the old path read. If you leave them in deployment manifests, they become false documentation.
  • Queues, topics and scheduled jobs that only the old path produced to or consumed from. Before you delete a queue, confirm it has drained.
  • Third-party dependencies pulled in for one implementation. Removing them shrinks the attack surface and makes upgrades cheaper.
  • Database columns, tables and indexes that only the old path wrote.

Schema and data cleanup deserves its own plan. Code removal can be reverted with a deploy. A dropped column can't, and old binaries that are still running during a rolling deploy may still read it. Treat the schema change as a separate expand/contract sequence. First stop writing, then stop reading, then drop the column one or more releases later, once rollback to the flagged build is no longer an option. So one flag's lifecycle can legitimately span several releases. Track the schema step as an open ticket so it isn't quietly forgotten.

Nested and interacting flags

When flags guard code inside other flags, remove the inner ones first. If you remove the outer flag first, the inner conditional becomes unreachable or permanently on, and nobody notices which. Each active flag also doubles the number of possible code paths, and most combinations are never tested. That is a strong reason to keep the active flag count low.

-- Schema cleanup for the removed 'legacy_pricing' flag, split across releases.
-- PostgreSQL syntax. Each step ships in a separate migration.

-- Release N (same release that deletes the flag and the losing branch):
-- New code no longer writes legacy_discount_code. Relax the constraint so
-- inserts from the new code succeed while old binaries in a rolling deploy
-- can still read the column.
ALTER TABLE orders
  ALTER COLUMN legacy_discount_code DROP NOT NULL;

-- Release N+1: no code reads the column any more. Before the contract step,
-- confirm nothing has written to it since the flag was removed.
-- Replace the timestamp with the deploy time of release N.
SELECT count(*) AS recent_writes
FROM orders
WHERE legacy_discount_code IS NOT NULL
  AND created_at > TIMESTAMP '2026-11-01 00:00:00';

-- Release N+2 (or later): rolling back to a build that still has the flag
-- is no longer an option, so the drop is now safe. This cannot be undone
-- with a deploy, so take a backup or snapshot first if the data matters.
DROP INDEX IF EXISTS idx_orders_legacy_discount_code;

ALTER TABLE orders
  DROP COLUMN IF EXISTS legacy_discount_code;

A contract sequence spread over three releases. It retires a column that only the removed flag branch used: first the writes stop, then a check confirms the column is unused, and the index and column are dropped once rollback to the flagged build is no longer possible.

How can CI and team process prevent feature toggle debt?

Guardrails work when the clean path is also the easy one. These patterns are worth adapting to whatever flag system you run:

  • Registry check in CI. A static check fails the build if code references a flag key that is not in the registry. Every flag then has an owner and an expiry date before it can ship.
  • Scheduled expiry report. A weekly job lists flags past their expiry date, grouped by owner, and posts it where each team already looks.
  • Per-team cap on active flags. Once a team reaches the cap, adding a flag means retiring one.
  • Removal ticket on every new-flag PR. The PR that adds a flag links the ticket that will delete it. Cleanup becomes planned work.

Process carries the rest. Reserve a recurring cleanup slot, such as a fixed share of each sprint, so removal does not lose to feature work every time. Track active flag count per team as a health metric next to build time and test flakiness. Define an escalation path for orphaned flags: when an owner leaves, the flag goes to their team lead, and if that team no longer exists, it goes to a named platform owner.

Each guardrail has a cost. Strict enforcement adds friction, and engineers under deadline pressure will hide toggles in environment variables or config files, where the registry cannot see them. Teams also bypass rules that nobody enforces, so all of this needs someone accountable.

The return is time. Removing a flag while its author still remembers it is a small change. Debugging an untested flag combination in production, or digging through old commits to learn what a flag guards, takes far longer.

#!/usr/bin/env python3
# CI guardrail: fail the build when code references a flag key that is not in
# the registry, and print expired flags grouped by owner (warning only).
import json
import re
import sys
from collections import defaultdict
from datetime import date
from pathlib import Path

# Registry shape: {"checkout-v2": {"owner": "team-payments", "expires": "2026-12-31"}}
REGISTRY = Path("flags/registry.json")
SRC_ROOT = Path("src")
# Matches literal call sites such as flags.is_enabled("checkout-v2").
# Keys built at runtime are not detected, so ban them by convention.
FLAG_CALL = re.compile(r"is_enabled\(\s*[\"']([\w-]+)[\"']")

registry = json.loads(REGISTRY.read_text(encoding="utf-8"))

unknown = []
for path in SRC_ROOT.rglob("*.py"):
    lines = path.read_text(encoding="utf-8").splitlines()
    for lineno, line in enumerate(lines, 1):
        for key in FLAG_CALL.findall(line):
            if key not in registry:
                unknown.append(f"{path}:{lineno}: unregistered flag '{key}'")

# Expired flags are reported, not blocking: the weekly report and the
# cleanup slot handle removal, so unrelated merges are not held up.
expired = defaultdict(list)
for key, meta in registry.items():
    if date.fromisoformat(meta["expires"]) < date.today():
        expired[meta["owner"]].append(key)
for owner, keys in sorted(expired.items()):
    print(f"[expired] {owner}: {', '.join(sorted(keys))}")

if unknown:
    print("\n".join(unknown))
    sys.exit(1)  # Every flag needs an owner and an expiry before it ships.

A minimal CI script that blocks references to unregistered flag keys and lists expired flags by owner, combining the registry check and the expiry report in one step.

When should you keep a flag, and what are the alternatives to toggles?

Not every flag should be removed at full rollout. A flag gives you rollback in seconds, with no build and no deploy. If your pipeline takes an hour, or deploys are risky enough to need a change window, keeping a flag for a few more weeks can be reasonable. Write that down. Set a new expiry date, record the reason in the flag's description, and name the owner. Otherwise the flag ends up kept by default, and stale flags start that way.

Some flags were never release toggles and should not be cleaned up as if they were:

Need Better home Why
Per-customer or per-plan access Entitlement model or permissions system It is business logic with its own audit and billing rules, not a temporary release
Environment-specific behaviour Application configuration It changes per deployment, not per request
Gradual release of new code Branch-based or deploy-based release (canary, blue-green) Rollback happens at the deploy layer, so no conditional is left in the code
Emergency shutoff for a risky dependency Documented permanent kill switch It is kept on purpose, tested, and listed in the runbook

Lifecycle checklist

At creation

  • Type: release, experiment, ops, or permission
  • Owner and expiry date recorded
  • Removal ticket filed

At full rollout

  • Flag at 100% and stable for the agreed period
  • Decision recorded: remove now, or keep until a stated date for a stated reason

At removal

  • Losing branch, tests, and config deleted
  • Flag removed from the flag service after the deploy
  • Removal ticket closed

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 stale feature flag cleanup, 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.