How to Trace Feature Flag Usage Before Removing a Flag

Kyle · · 25 min read
Trace feature flag usage before safely removing a flag

Removing a flag is easy. To trace feature flag usage safely, you need to prove where the check still lives and whether that branch can still execute.

A repo-wide search finds the obvious reads; it won’t show the callers, jobs, shared packages, or stale tests hanging off them. For teams using Claude Code, Cursor, or Codex across multiple repos, that missing context is where cleanup gets risky.

Start with evidence:

  • Search the exact key, wrappers, environment variables, and fixtures.
  • Map callers and entry points around every surviving check.
  • Confirm the winning path, then delete without guessing.

Why Old Flags Feel Riskier Than They Look

Most teams don't stall on flag cleanup because deleting an if is hard. They stall because they can't see the full shape of the decision anymore. The flag started as a release tool. Six months later, it's tangled up with tests, wrappers, fallback config, and one path nobody wants to touch on a Friday.

A quick search usually gives false confidence. You find three reads, delete two, update one, and think you're done. Then a background job still passes a flag-shaped parameter through a helper that nobody associates with the original rollout. That's how stale flags survive.

A single flag can hide in a few different forms:

  • direct SDK reads
  • helper functions like isNewCheckoutEnabled()
  • environment variables and build-time constants
  • generated clients or shared config packages
  • test fixtures, snapshots, and mocks
  • prerequisite rules in the flag system itself

Flags also leave behind branching debt. Even after a rollout is "done," engineers still have to reason about both paths until one is actually removed. Tests do too. That cost is small the first week and irritating by the third quarter.

The maintenance burden can compound at scale: Uber reported that its ongoing Piranha pipeline had removed around 2,000 stale feature flags and their related code from its Android and iOS codebases. That is a single-company case study rather than an industry benchmark, but it illustrates why flag retirement needs a repeatable process rather than occasional cleanup.

Not every flag deserves the same cleanup pressure. Temporary release flags should usually disappear. Kill switches and operational controls are different. If a flag exists so you can shut off a risky payment path in 30 seconds, keep it. Treating that like a short-lived release toggle is how teams remove safety rails by accident.

The real problem is invisible architecture.

You're not just removing a key from a dashboard. You're changing which code paths can execute, which interfaces still matter, and which dependencies were only alive because the old branch kept them alive.

What It Actually Means to Trace Feature Flag Usage

To trace feature flag usage properly, we need evidence from four layers, not one. Teams get into trouble when they answer a structural question with a text search, or a cleanup question with rollout analytics.

Here's the model we use:

  1. Literal code references
    Where does the flag key or its wrapper appear?

  2. Structural dependencies
    What calls those flagged paths, and what fans out from them?

  3. Runtime evaluation data
    Is the flag still being evaluated, and which variants are actually served?

  4. Current flag configuration
    What does the flag platform say the flag does right now?

These layers answer different questions.

  • A code reference tells you a branch exists.
  • Dependency mapping tells you what could break if you simplify that branch.
  • Runtime telemetry tells you whether the branch is still being exercised.
  • Configuration tells you what the platform intends to serve, not what code still expects.

That distinction matters more than people think. A flag can be out to 100 percent for two weeks and still be threaded through hot request paths. It can also look inactive in telemetry because client-side events are coarse, disabled, or simply not getting out.

No single method is enough:

  • Search alone misses indirection and cross-repo relationships.
  • Analytics alone can't tell you where to edit.
  • Platform state alone can't prove cleanup is safe.

So when we say trace feature flag usage, we mean combining literal flag-name searches with graph relationships and source inspection. That's the whole game.

Before you try to find all flag checks, get the flag record straight. This sounds boring. It's also where most sloppy cleanup starts.

Build a short removal brief with the basics:

  • exact flag key
  • human-readable name
  • variations and default behavior
  • environments where the flag exists
  • whether it's temporary or intentionally long-lived
  • prerequisites or dependent flags
  • owner of the removal decision

Then split two things that teams blur together: configuration state and rollout state.

Configuration state is how the flag is defined right now. On or off. Targeting rules. prerequisites. Default variant.

Rollout state is what has actually been served recently. Multiple variants, only control, one non-control variant, no recent evaluations, and so on.

Those are not the same. Not even close.

A flag can be configured "on" but still mostly hit the fallback path because of prerequisite failures. It can be configured for one winning path and still leave old code alive in three repos. We've seen teams delete a flag because the dashboard looked settled, while the code was still carrying both branches everywhere that mattered.

Capture branch intent before you trace anything:

  • Which variation won?
  • Which path should survive after cleanup?
  • Are you keeping the on-path or the off-path?
  • Is there any reason the losing path still needs to exist for rollback?

Write that down. If you don't, you end up doing archaeology during the PR.

If you can't say which branch should remain, you're not ready to remove the flag.

Also watch for false signals. "Out to 100 percent" does not mean removed. "Inactive" does not always mean unused, especially if event reporting is partial. Treat those statuses as clues, not proof.

Find All Flag Checks, Including the Ones Grep Misses

Now start the actual hunt. Begin with literal search across every relevant repository, not just the service where you think the flag lives. Multi-repo systems punish local assumptions.

Search for more than the exact key:

  • exact flag key
  • alternate naming forms
  • wrapper method names
  • environment variable names
  • constants that mirror the flag
  • test doubles, fixtures, and snapshots

And search across the usual hiding places:

  • frontend components
  • backend handlers
  • jobs and workers
  • API clients
  • shared config modules
  • CI or deployment config
  • tests

Expect mixed implementation styles in the same system. That's normal in older codebases.

You may find:

if (flags.isEnabled("new-checkout")) { ... }

if (isNewCheckoutEnabled(user)) { ... }

const useNewCheckout = process.env.FEATURE_NEW_CHECKOUT === "true"

if (props.newCheckout) { ... }

All four might point to the same rollout decision. Only one contains the literal flag key.

Static analysis helps here when you have it. Some tooling can detect SDK reads, environment-backed toggles, or literal constants without running the app. Retirement reports are useful too because they can group read sites by flag and estimate age from git history. That's handy when you're trying to remove stale feature flags in a pile, not one by one.

Record each finding so somebody can act on it later:

  • repository
  • file
  • symbol or line
  • kind of check
  • guarded branch
  • production, test, or tooling

Don't overvalue reference counts. One central read in a request router can matter more than ten test references. Engineers love neat numbers. Flags don't care.

Map the Dependency Graph Around Each Reference

Once you've found the checks, stop thinking in text. Switch to structure.

For each flagged path, ask:

  • who calls this function?
  • which routes or endpoints reach it?
  • which jobs or event handlers depend on it?
  • which shared modules fan out from it?
  • is any of this already unreachable?

This is where feature flag dependency mapping earns its keep. You're not tracing the flag key anymore. You're tracing the blast radius of simplifying one branch.

On larger TypeScript and Python codebases, this is exactly where Pharaoh helps. We use the codebase graph for structural discovery: callers, endpoints, environment variable usage, blast radius, dead code, and cross-repo relationships that are painful to reconstruct by hand. That's useful for engineers and even more useful when an AI assistant is about to edit multiple modules without a strong map of the system.

There are limits, and they matter:

  • A graph is strong at structure.
  • It is not a replacement for literal source reads when you need exact flag-key matches.
  • It does not observe live production flag values.

That last point is worth saying plainly. A graph tells you what depends on what. It does not tell you what variant users got yesterday afternoon.

Use graph questions that grep answers badly:

  • If we remove the false branch, which entry points change?
  • Which tests still cover the surviving path?
  • Is this module already dead?
  • Does this touch one component or four services?

For AI-assisted cleanup, sequence matters. Start with the graph to bound the system. Then inspect the exact source. That cuts down on broad, shaky edits.

Dependency graph to trace feature flag usage across code references

Check Runtime Evidence Before You Delete Anything

After code and structure, look at runtime evidence. Not because telemetry is perfect. Because absence of runtime evidence and absence of code evidence mean very different things.

Review what your flag platform exposes:

  • total evaluations
  • served variants
  • unique users or contexts
  • pages or views where evaluations occur
  • last evaluation time

Many systems also label recent status in simple buckets. Active often means multiple variants were evaluated recently. Inactive may mean only the control variant was seen for a period like the last two weeks. Out to 100 percent often means one non-control variant was the only one served in that same window.

Useful, but don't get sentimental about dashboards.

Server-side SDKs may report every read. Browser and mobile SDKs often report more coarsely, sometimes closer to user exposure than raw read count. If evaluation events are disabled or blocked, zero events proves very little.

Compare runtime evidence against code evidence instead of treating either one as final authority.

A few examples:

  • A flag out to 100 percent with lots of hot-path code checks is a cleanup candidate.
  • A flag with no recent evaluations and many code references might be dead, partly dead, or badly instrumented.
  • A flag with sparse code usage but recent evaluations in a background flow probably deserves a second look before deletion.

Runtime data tells you what happened recently. It doesn't prove a hidden path can't still execute.

Separate Rollout Questions From Cleanup Questions

Teams often ask one question and think they're asking another.

  • Is the rollout finished?
  • Is the code safe to simplify?

Those are related. They are not interchangeable.

Rollout complete means the platform is consistently serving one outcome.

Cleanup safe means you've traced code, dependencies, tests, and non-code dependencies well enough to remove the losing path without surprises.

That second bar is higher.

Check the flag type before you remove anything:

  • Temporary release flags usually want cleanup.
  • Experiment flags may need result retention or reporting history first.
  • Kill switches may stay in place even if rarely touched.

Also check what sits outside the code. Flags often leak into runbooks, alerts, dashboards, support steps, and release playbooks. Engineers forget this because none of it shows up in grep.

If the flag was part of a safer-refactor setup, verify whether both implementations are still being compared or whether one has become the steady state. That's a quiet source of stale branching debt.

Build a Flag Cleanup Workflow You Can Repeat

Treat cleanup like an operating procedure, not a heroic sweep. One-off flag cleanup feels productive for a day and then dies in backlog mud.

A workable flag cleanup workflow looks like this:

Repeatable removal workflow

  1. Confirm basics

    Confirm key, owner, and intended surviving behavior.

  2. Search references

    Find all flag checks across repos.

  3. Map impact

    Map dependencies and blast radius.

  4. Check runtime status

    Review runtime evaluations and current status.

  5. Make the decision

    Decide: remove now, stage removal, or keep.

  6. Update code and tests

    Edit code and tests.

  7. Verify cleanup

    Verify no hidden references remain.

  8. Remove config last

    Remove platform config last, or in the order your rollback policy prefers.

Define a few removal classes so every flag doesn't become a philosophy debate:

  • Safe now: one surviving path, low blast radius, decent observability
  • Safe with staging: larger surface area, weaker telemetry, or cross-repo edits
  • Not safe yet: still active, still intentional, or still poorly understood

Prioritize stale flags with concrete signals:

  • one surviving variant for a long period
  • few read sites
  • older age in git history
  • isolated dependency graph
  • no recent evaluations

If your team merges through PRs, add architectural checks to the cleanup step. PR Guard is useful here because it can surface unreachable exports, regression risk, coverage gaps, and breaking changes during review. Diff review alone won't catch structural fallout reliably. It just won't.

Verify the Feature Toggle Impact Before Merging

This is where cleanup confidence actually comes from. Not the search. Not the dashboard. Verification.

Check the direct code result first:

  • the surviving branch is unconditional
  • the losing branch is gone
  • dead imports, props, and parameters are removed

Then check the structural result. No remaining callers should expect the old branch behavior. No endpoint or job should still route through removed code. No now-unused module should linger because it was only kept alive by the old path.

Test cleanup is usually messier than code cleanup. Update tests that asserted both paths. Keep tests for the behavior that survives. Remove fixtures and snapshots that only existed for the old branch. Then verify coverage still lines up with the paths you care about.

Don't skip config cleanup either:

  • no prerequisite rule still expects the flag
  • no dependent rule still references it
  • no environment-specific definition is left behind

After deployment, watch the affected endpoints or views. Errors should stay flat. If your platform exposes evaluation events, the removed flag should stop appearing.

Treat this like a blast-radius review, not a diff review.

That's the difference between controlled cleanup and optimistic deletion.

Illustrative Example: Tracing a Temporary Release Flag Across a Multi-Repo System

Let's use a simple example.

A boolean flag controls a new checkout flow. The web app reads it for UI routing. The backend reads it during pricing validation. Tests cover both paths. The rollout now serves one variant to everyone.

The trace usually goes like this:

First, search the exact key and wrapper methods across every repo in the workspace. You find UI gates in the web app, a backend helper that still accepts a flag-shaped parameter, an environment fallback in shared config, and tests that explicitly set both states.

Then map callers. The UI branch affects one route group. The backend helper is used by two endpoints and one async reconciliation job. Now the shape of the change is visible.

Next, check runtime evidence. Only one variant has been evaluated recently. Good. That supports cleanup. It doesn't finish the job.

Likely findings:

  • the web branch is still active in code even though rollout is complete
  • a backend helper still carries a parameter that no longer needs to vary
  • tests still build a matrix around a path production no longer uses

Cleanup decision:

  • keep the winning checkout path
  • remove the losing branch
  • simplify helper parameters and call sites
  • remove test cases that existed only for the flag
  • verify no dependent service still expects the old response shape

The risky part wasn't the flag key itself. It was the hidden dependency chain around the old branch.

Prompts and Checks You Can Hand to an AI Coding Assistant

AI assistants are useful here, but only if you give them a real job instead of vague permission.

Use prompts like these.

For literal discovery:

Find all references to the flag key and any wrapper methods that read it across every repository in this workspace. Separate production code, tests, config, and generated code.

For dependency mapping:

For each reference, map callers, routes, endpoints, jobs, and shared modules that depend on the flagged branch. Highlight high-fan-out nodes and possible blast radius.

For cleanup planning:

Assume the winning variation is permanent. Identify the branches, parameters, tests, and modules that become removable if we delete the losing path.

For verification:

After edits, check for unreachable exports, unused helpers, coverage gaps, and remaining references to the flag key or branch-specific behavior.

Keep human checkpoints in the loop:

  • confirm cross-repo usage wasn't missed
  • open the exact source for high-impact references
  • compare removals against rollout and telemetry data
  • make sure the assistant isn't inferring production state from static code

If you're using Pharaoh with an MCP-aware assistant, use the graph for structural discovery first, then inspect source for literal details. In large repos, that order reduces guesswork fast.

Common Mistakes When You Remove Stale Feature Flags

Most bad flag removals follow a short list of avoidable mistakes.

  • treating "out to 100 percent" as proof the code is safe to delete
  • trusting zero evaluation events when reporting may be coarse or disabled
  • searching one repo and missing shared packages or backend services
  • deleting platform config before code and making rollback harder
  • removing the obvious branch while leaving dead params, wrappers, and tests
  • treating long-lived kill switches like temporary release flags
  • letting an AI assistant edit broadly without a blast-radius map

The pattern is always the same. People remove what they can see and assume the rest will reveal itself. Software is not that polite.

When to Use Search, Analytics, Static Analysis, and Graphs Together

Each method answers a different question. Use them that way.

  • Literal search is best for exact keys, wrappers, env vars, and tests.
  • Runtime analytics are best for recent evaluations, served variants, and where evaluations happen.
  • Static analysis is best for surfacing SDK reads, constants, and retirement candidates without running the system.
  • Graph analysis is best for feature toggle impact, blast radius, and cross-repo reasoning.

Cleanup automation can help once you know which path wins. Some tools focus on retirement candidates. Some can delete stale branches in supported languages. None remove the need for ownership, intent, and verification.

Use the right evidence for the right question. That's the practical rule. Teams get into trouble when they expect one tool to answer everything.

MethodBest forKey limitation
Literal searchExact keys, wrapper methods, environment variables, constants that mirror the flag, and test referencesShows that a branch exists, but search alone misses indirection, callers, and cross-repo relationships
Runtime analyticsRecent evaluations, served variants, unique users or contexts, pages or views where evaluations happen, and last evaluation timeShows what happened recently, not where to edit; zero or sparse events can be misleading when reporting is coarse, disabled, or blocked
Static analysisSurfacing SDK reads, environment-backed toggles, literal constants, and retirement candidates without running the systemRuns no code and calls no flag provider, so it cannot observe live evaluations or current production values
Graph analysisFeature toggle impact, blast radius, callers, endpoints, dead code, and cross-repo reasoningStrong at structure, but not a replacement for exact source reads and does not show what variant users got in production

Conclusion

Safe flag removal starts with a mindset shift. You're not deleting a toggle. You're tracing how one branching decision still threads through code, dependencies, tests, and recent behavior.

The workflow that holds up is simple: exact reference search, feature flag dependency mapping, rollout evidence, and explicit verification. Skip one and you're back to guesswork.

If you want one useful step today, pick one old temporary flag, write down the path that should survive, then trace feature flag usage across code and dependencies before you touch the delete key. That's usually enough to turn a nervous cleanup into a controlled change.

Article Record

ReferencesPrimary sources used for this article
  1. Feature flags
  2. Using Feature Flag Tracking
  3. Flag Evaluation Analytics | Featureflip Docs
  4. Introducing Piranha: An Open Source Tool to Automatically Delete Stale Code
  5. Feature flags API Reference - PostHog
  6. Code References: Find Your Feature Flags in Your Code
  7. View feature flag events in Azure App Configuration - Azure App Configuration | Microsoft Learn
  8. 📈 Flag usage tracking | GO Feature Flag
Update HistoryMeaningful revisions to this article
Initial publication.
← Back to blog