Why can't static analysis prove code is dead in a monolith?

Dead code removal means deleting endpoints, modules, jobs and branches that no production path executes. This guide is for backend and platform engineers who own long-lived monoliths. Removal pays off in three ways. Engineers spend less time reading code that doesn't matter. Unpatched dependencies and forgotten admin routes no longer widen the security surface. Builds and test suites stop compiling and exercising code nobody calls.

Call graphs and dead-code analyzers are a good first pass, but they only return candidates. Static analysis sees references written in source, and many monolith callers never appear there:

  • Reflection and dependency injection resolve classes by name or by container configuration at runtime.
  • String-based routing maps URL patterns or message types to handlers through config files.
  • Serialization hooks are invoked implicitly by frameworks, as are lifecycle callbacks.
  • Scheduled jobs are registered by cron expressions or job tables.
  • Feature flags can keep a branch dormant for months before it turns on.
  • External callers never touch your repository: old mobile app versions, partner integrations, other services and ops cron scripts.

Tools also handle dynamic language features differently. Some assume any reflective call could reach anything, which hides dead code (false negatives). Others ignore reflection entirely, which flags live code as dead (false positives).

Approach What it relies on Main risk
Leave code in place Nothing Growing cognitive load, attack surface and build time
Static-only deletion Analyzer output Breaking hidden or external callers
Static candidates + runtime evidence + staged removal Analyzer output, telemetry, reversible steps Slower, but failures are observable and recoverable

How do you build a complete inventory of endpoints, jobs and entry points?

Telemetry can only tell you what was called. It cannot tell you what wasn't, unless you already have a list of everything that could be. Without that list, an endpoint that receives zero traffic simply never appears in your logs. It looks the same as code that doesn't exist. The inventory is the denominator. Every later stage subtracts observed usage from it.

Build it from the framework's own registries, not by grepping source. The router knows the final set of routes after decorators, mounted sub-applications and plugin registrations have run. Grep sees only literal strings. Dump the route table from a booted application, and do the same for the job scheduler, queue consumer registrations and the CLI command registry. For public module entry points, list exported symbols that other packages or deployables import. Don't forget webhooks, scheduled tasks defined in infrastructure config rather than code, and admin-only routes, because these are the ones most often missed.

For each item, record:

  • Kind: route, job, consumer, command or module export.
  • Normalized identifier: for routes, the method plus the template (GET /orders/{id}), never a concrete path like /orders/8812. This lets the inventory join cleanly against telemetry later.
  • Owner: a team, not an individual, so the entry survives reorgs.
  • Source location: the file and handler.

Commit the result as a generated, sorted file, such as CSV or JSON, in the repository, and regenerate it in CI. Diffs then show new and removed entry points in review. Later stages can join against a known version instead of a moving target.

# Dump routes and CLI commands from a booted Flask app into a sorted CSV inventory.
# Usage in CI: python inventory.py > inventory/entrypoints.csv && git diff --exit-code
import csv, inspect, os, re, sys
from myservice import create_app  # placeholder: your app factory

# Prefix -> owning team. Teams, not people, so entries survive reorgs.
OWNERS = {"/orders": "team-checkout", "/admin": "team-platform"}

def owner_for(path):
    for prefix, team in sorted(OWNERS.items(), key=lambda kv: -len(kv[0])):
        if path.startswith(prefix):
            return team
    return "UNOWNED"  # surface gaps instead of guessing

def location(fn):
    fn = inspect.unwrap(fn)  # see through decorators to the real handler
    src = os.path.relpath(inspect.getsourcefile(fn))  # stable across machines
    return f"{src}:{fn.__qualname__}"

app = create_app()  # the router's view after blueprints and plugins register
rows = []
for rule in app.url_map.iter_rules():
    # /orders/<int:id> -> /orders/{id}, the shape telemetry should also emit
    template = re.sub(r"<(?:[^:<>]+:)?([^<>]+)>", r"{\1}", rule.rule)
    for method in sorted(rule.methods - {"HEAD", "OPTIONS"}):
        handler = app.view_functions[rule.endpoint]
        rows.append(("route", f"{method} {template}", owner_for(template), location(handler)))

for name, cmd in app.cli.commands.items():
    if cmd.callback:  # skip command groups with no callback of their own
        rows.append(("command", f"flask {name}", "team-platform", location(cmd.callback)))

# Jobs and queue consumers: append rows from your scheduler/worker registry the same way.
writer = csv.writer(sys.stdout, lineterminator="\n")
writer.writerow(("kind", "identifier", "owner", "source"))
writer.writerows(sorted(rows))  # sorted output keeps review diffs minimal

A Flask script that reads the live route table and CLI registry, normalizes route templates, assigns team owners and writes a sorted CSV inventory to commit and regenerate in CI.

How does usage telemetry reveal dead endpoints and modules?

The inventory tells you what could run. Telemetry tells you what does. Tag every request with its normalized route template, such as /orders/{id}, rather than the raw path. Raw paths scatter one endpoint across thousands of distinct strings, so a live route can look like noise. Count hits per template over time from access logs or request metrics, and join the counts to the inventory. Any entry point with no row in the counts is a candidate.

Counts alone do not tell you who to call. Record caller identity, such as client ID, user agent or calling service name, so that the last few requests to a "nearly dead" endpoint can be traced to an owner.

For code below the routing layer, add lightweight counters at module entry points and in suspected-dead branches. Production code coverage is another option if your runtime supports it cheaply. Both have costs:

  • Overhead. Instrumentation sits on hot paths.
  • Cardinality. Each label value creates a separate time series, so keep caller labels bounded.
  • Sampling. It misses the rare callers that matter most, such as the quarterly report job or the partner integration. Use full counts, not samples, for deletion decisions.

Validate the pipeline before you trust a zero. Pick a route you know is live and confirm it appears with plausible volume. That check catches templates that fail to normalize, logs dropped at a proxy, and traffic served by a separate deployment that ships the same code but reports elsewhere.

Finally, limit what you record. Headers, query strings and request bodies can carry tokens or personal data. Log only the template and caller ID, and set a retention period no longer than the observation window.

from flask import Flask, request
from prometheus_client import Counter, start_http_server

app = Flask(__name__)

# Bounded caller set keeps label cardinality fixed; anything else is "other".
KNOWN_CALLERS = {"billing-svc", "mobile-app", "partner-example"}

ROUTE_HITS = Counter(
    "http_route_hits", "Requests per route template and caller", ["route", "caller"]
)
MODULE_HITS = Counter(
    "module_entry_hits", "Calls into suspected-dead code paths", ["module"]
)

@app.after_request
def count_route(response):
    # url_rule.rule is the template ("/orders/<int:order_id>"), not the raw path.
    rule = request.url_rule
    route = rule.rule if rule else "unmatched"
    caller = request.headers.get("X-Client-Id", "unknown")
    if caller not in KNOWN_CALLERS:
        caller = "other"
    # Record only template and caller: no query string, headers or body.
    ROUTE_HITS.labels(route=route, caller=caller).inc()
    return response

@app.get("/orders/<int:order_id>")
def get_order(order_id):
    # Known-live route: use it to validate the pipeline before trusting zeros.
    return {"id": order_id}

@app.get("/reports/legacy-export")
def legacy_export():
    # Suspected dead: every call is counted, never sampled.
    MODULE_HITS.labels(module="reports.legacy_export").inc()
    return {"status": "ok"}

if __name__ == "__main__":
    start_http_server(9100)  # Separate port exposes /metrics for scraping.
    app.run(port=8080)

A Flask app that counts every request by route template and a bounded caller label, adds an unsampled counter to a suspected-dead endpoint, and records nothing from headers, query strings or bodies beyond the caller ID.

How long should you observe usage before calling code unused?

Retention matters because the observation window has to be long. A window is only meaningful if it covers every business cycle that could plausibly call the code. That includes weekly batch jobs, month-end close, quarter-end reporting, annual statements, tax season, and yearly contract renewals. An endpoint that reconciles fiscal-year balances will show zero traffic for eleven months and still be essential. "Zero hits in two weeks" tells you nothing about code tied to those rarer events.

The illustrative estimate below assumes the window starts on a random day, quarter-ends fall every 13 weeks, and the annual event happens on one fixed date. Percentages are the chance that the window contains at least one occurrence.

Window Weekly batch Month-end Quarter-end Annual event
2 weeks Covered ~47% ~15% ~4%
6 weeks Covered Covered ~46% ~12%
4 months Covered Covered Covered ~33%
13 months Covered Covered Covered Covered

The trade-off is real. Longer windows delay cleanup and keep maintenance costs on the books. But schedule pressure to shortcut the window is where most deletion breakages start. A team agrees to "just six weeks" and learns in January which code the annual close depended on.

Write down the window you chose, the cycles it covers, and the ones it deliberately skips. When a candidate looks unused but sits near finance, compliance or reporting code, extend its window rather than the whole programme's.

How should you classify deletion candidates?

Before sorting anything, strip out traffic that is not real usage. Requests from your own test suites, load balancer health checks, synthetic monitors and internal crawlers keep dead endpoints looking alive. Tag or exclude these by user agent, source network or service identity. Then re-run the analysis, because this is where many "active" endpoints turn out to have no real callers.

What remains usually falls into one of these classes:

Class What it usually means Recommended action
Zero traffic, no static references Orphaned code with no known path in Strongest candidate. Move to staged deletion.
Zero traffic, statically referenced Callers exist but never run: feature flags, error branches, rare admin paths Trace each reference. Delete the caller first if it is also dead. Otherwise keep it and document why.
Low traffic from one identifiable caller A forgotten script, cron job or another team's service Contact the owner and agree on a migration or removal date. Do not delete unilaterally.
Traffic only from tests, health checks or crawlers Not real usage Treat as zero traffic, and update or remove the tests along with the code.

Some code should not be deleted even when traffic is tiny. Old mobile app versions still in the field, partner integrations, and offline clients that sync rarely are callers you cannot redeploy or force to upgrade. Removing an endpoint they depend on breaks them in ways you may never see in your own metrics.

In these cases, replace the original implementation with a thin compatibility shim. The shim keeps the contract and translates requests to the current code path. This lets you delete the old module behind it while keeping the external surface stable. Add a log line to the shim so you can tell when its last caller finally disappears.

What does staged, reversible code deletion look like in practice?

Run the removal as ordered steps, each one reversible until the last.

  1. Announce the deprecation. Post it in the changelog and in team channels, and name a removal date. Owners who missed the inventory review get one more chance to object.
  2. Make every hit loud. Add a log line and an alert to the code path. Include the caller identity, route and timestamp. A quiet counter is easy to miss, while a page or ticket forces someone to look.
  3. Stub instead of delete. Put the code behind a flag, or replace the handler with a stub that returns 410 Gone and a message naming the replacement. The stub should still call the alert hook so hits stay visible. Then wait through another full observation window. If a hit appears, flip the flag back.
  4. Delete in one reviewable change. Remove the code, routes, tests and config together so reviewers see the whole blast radius in a single diff, and a revert restores all of it at once.

Stubs cost something if they stay too long. They clutter routing, keep stale tests alive, and teach people that deprecated code never actually goes away. Give each stub an expiry: an owner, a date in a code comment, and a ticket or CI check that fails once the date passes.

Then clean up the long tail as separate changes: flags, config keys, permissions, docs, SDK methods, dashboards, columns and tables. Let data-layer cleanup lag well behind code removal. A reverted deploy restores code, but a dropped column does not come back on its own. For a small unused table, the risk of dropping it may never be worth the gain.

import express, { Request, Response } from "express";

// Stub expiry metadata: an owner, a date, and a ticket. A CI test calls
// assertStubNotExpired() so the build fails once the date passes.
export const LEGACY_EXPORT_STUB = { owner: "billing-team", removeAfter: "2026-12-15", ticket: "BILL-1234" };

export function assertStubNotExpired(stub = LEGACY_EXPORT_STUB): void {
  if (Date.now() > Date.parse(stub.removeAfter)) {
    throw new Error(`Stub expired on ${stub.removeAfter}: delete it (${stub.ticket}, owner ${stub.owner})`);
  }
}

// Alert hook: one greppable log line plus a page or ticket, not a quiet counter.
async function alertDeprecatedHit(req: Request, route: string): Promise<void> {
  const event = { route, caller: req.get("x-client-id") ?? "unknown", ip: req.ip, at: new Date().toISOString() };
  console.warn(JSON.stringify({ level: "warn", msg: "DEPRECATED_ROUTE_HIT", ...event }));
  try {
    await fetch("", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(event),
    });
  } catch (err) {
    // A failed alert must never change the response the caller sees.
    console.error("deprecation alert failed", err);
  }
}

const app = express();

// The original handler is gone. The route stays so hits remain visible during the window.
app.get("/v1/reports/export", (req: Request, res: Response) => {
  void alertDeprecatedHit(req, "/v1/reports/export");
  res.status(410).json({
    error: "gone",
    message: "GET /v1/reports/export was removed. Use GET /v2/exports instead.",
  });
});

app.listen(3000);

An Express stub that replaces a deprecated handler with a 410 Gone response, sends an alert on every hit with the caller, route and timestamp, and has an expiry check that a CI test can call to fail the build once the removal date passes.

Go/no-go checklist and how to keep dead code from coming back

Treat each candidate as its own decision. If any item below is unchecked, the answer is "not yet," not "probably fine."

Gate Go when Why it blocks
Owner identified A named team signs off Without an owner, no one can answer "who calls this?"
Inventory confirmed Route, job, or consumer appears in the generated inventory Hand-curated lists miss reflection, config-driven routing, and cron entries
Telemetry window Covers at least one full business cycle (month-end, quarter-end, annual) Low-frequency callers look identical to dead code in a short window
Callers explained Every observed hit is traced to a known source One unexplained caller means the inventory or telemetry is wrong
External consumers notified Partners and other internal teams have acknowledged They cannot see your dashboards
Flag or error-stub stage done Ran in production with no complaints It tests the deletion without losing the code
Rollback tested A revert has been rehearsed, not assumed An untested rollback fails exactly when you need it

Deleting code makes builds and test suites smaller, removes misleading stack frames and alerts during on-call, and gives new engineers fewer modules to read. Those savings are real, but you pay for them continuously in telemetry storage and review time. Spend that effort on large or risky modules, not on trivial helpers.

To keep dead code from returning, make the route and job inventories standing dashboards with an owner column, and fail CI when a new endpoint has no owner. Hold a short quarterly review of zero-traffic entries. At that cadence, the person who wrote the code is likely still around to explain it.

Alternatives to consider

Production code coverage instead of request telemetry

Running a coverage agent or sampling profiler in production records which functions and lines actually execute, not just which routes receive traffic. That is more precise, because it catches dead branches inside live endpoints. The cost is runtime overhead and a large volume of data to aggregate. Many teams enable it on a small slice of instances for a fixed window rather than across the whole fleet.

Quarantine without deletion

Instead of deleting code, you can move suspect modules behind a boundary that forbids new imports, enforced by a lint rule or module visibility settings. This stops dead code from spreading and costs almost nothing. It does not reduce build time, dependency surface, or the attack surface of exposed endpoints, so treat it as a holding state rather than an end state.

Extract, then decide

Under a strangler approach, live functionality is carved out into new services and the monolith shrinks around it. Dead code becomes obvious because nothing migrates it. This works when you are already planning a decomposition. Starting a decomposition only to find dead code is far more effort than the telemetry-driven process above.

Static analysis alone, scoped narrowly

For internal libraries with no reflection, no dynamic dispatch, and no external callers, an unused-symbol linter is often sufficient. It gives fast results with low risk. Use it inside those boundaries, and keep relying on runtime evidence everywhere else.

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 find unused code in large codebase, 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.