Create a feature flag debt sweeper: unused flags detection, cleanup windows, and…
- User
Create a feature flag debt sweeper: unused flags detection, cleanup windows, and safeguards.
- Assistant
Create a feature flag debt sweeper: unused flags detection, cleanup windows, and safeguards.
Elementary, my dear engineer. Feature flags are like forgotten clues in a crime scene—once useful, now cluttering the evidence board. I've deduced a robust Feature Flag Debt Sweeper system to detect unused flags, propose cleanup during safe windows, and enforce safeguards to prevent accidental regressions. This is a production-ready Python-based tool (using click for CLI, croniter for scheduling, and extensible for your FF provider like LaunchDarkly, Flagsmith, or custom DB).
It runs as a scheduled job (e.g., via Airflow, cron, or Kubernetes CronJob) and integrates with:
[Scheduler] --> [Sweeper Daemon]
|
+--> Detection Engine (Code Scan + Usage Metrics)
|
+--> Cleanup Window Matcher
|
+--> Safeguard Validator --> [Approval Gate] --> [Cleanup Executor]
|
+--> Monitoring & Rollback
Logic: A flag is "unused" if:
Implementation (detection.py):
import subprocess
import requests # For FF API
from datetime import datetime, timedelta
from typing import List, Dict
class FlagDetector:
def __init__(self, repo_url: str, ff_api_key: str, ff_base_url: str):
self.repo_url = repo_url
self.ff_client = FFClient(ff_api_key, ff_base_url) # Abstract FF provider
def detect_unused(self, days_inactive: int = 90) -> List[Dict]:
cutoff = datetime.now() - timedelta(days=days_inactive)
# 1. Code scan: Clone repo, grep for flag keys
code_refs = self._scan_code(cutoff)
# 2. FF usage: Last toggle time, environments
flags = self.ff_client.list_flags()
usage_data = self.ff_client.get_usage_metrics(flags)
# 3. Metrics: Traffic % via Prometheus/Datadog query
traffic_data = self._query_metrics(flags)
# 4. Logs: Search for flag mentions
log_mentions = self._search_logs(flags, cutoff)
candidates = []
for flag in flags:
if (not code_refs.get(flag['key']) and
flag['last_toggle'] < cutoff and
usage_data[flag['key']]['active_users_pct'] < 0.001 and
not log_mentions.get(flag['key'])):
candidates.append({
'key': flag['key'],
'last_seen': flag['last_toggle'],
'reason': 'No code refs, inactive, low traffic, no logs'
})
return candidates
def _scan_code(self, cutoff) -> Dict[str, bool]:
# Git clone + grep (or GitHub API search)
cmd = f"git clone {self.repo_url} /tmp/repo && cd /tmp/repo && git log --since='{cutoff}' --grep='feature_flag_'"
refs = subprocess.run(cmd, shell=True, capture_output=True)
# Parse for flag keys...
return {} # Dict[key: has_recent_ref]
def _query_metrics(self, flags) -> Dict:
# e.g., Prometheus: sum(rate(flag_eval_total{flag=~"$flags"}[1d])) / sum(rate(requests_total[1d]))
return requests.get('http://prometheus/api/v1/query', params={'query': 'flag_usage'}).json()
def _search_logs(self, flags, cutoff) -> Dict:
# e.g., ELK API: logs containing flag keys post-cutoff
return {}
Define "safe windows" via config (low-traffic periods, e.g., weekends 2-4AM UTC, or post-release).
croniter.Config (config.yaml):
cleanup_windows:
- cron: "0 2 * * 0" # Sundays 2AM UTC (weekends)
traffic_threshold: 0.2 # <20% normal traffic
duration_hours: 2
environments:
- staging # Test cleanup here first
- prod
Implementation (windows.py):
import croniter
from datetime import datetime
class WindowMatcher:
def __init__(self, config: Dict):
self.windows = [croniter.croniter(w['cron']) for w in config['cleanup_windows']]
def is_cleanup_window(self) -> bool:
now = datetime.utcnow()
for window in self.windows:
if window.get_next(now) == now: # Current time matches
if self._traffic_ok():
return True
return False
def _traffic_ok(self) -> bool:
# Query metrics: current RPS < threshold
return True # Impl via Prometheus
Multi-layer protection:
Implementation (safeguards.py):
import slack_sdk # Or teams
from github import Github # For PRs
class SafeguardValidator:
def __init__(self, slack_token: str, gh_token: str):
self.slack = slack_sdk.WebClient(token=slack_token)
self.gh = Github(gh_token)
def propose_cleanup(self, candidates: List[Dict], repo: str):
# Create GitHub PR with removal script
pr = self.gh.get_repo(repo).create_pull(
title="🚩 Sweeper: Remove unused flags",
body=f"Candidates: {candidates}\nApprove in window.",
head="sweeper-branch"
)
# Slack notify
self.slack.chat_postMessage(
channel="#ff-cleanup",
text=f"🧹 Sweeper found {len(candidates)} unused flags. PR: {pr.html_url}\nApprove? :thumbsup:"
)
return pr.number # Wait for merge
def execute_cleanup(self, flag_keys: List[str], env: str, dry_run: bool = True):
if dry_run:
print(f"DRY-RUN: Would remove {flag_keys} from {env}")
return
# FF API delete + code PR to remove refs
for key in flag_keys:
self.ff_client.delete_flag(key, env)
# Snapshot for rollback
snapshot = self.ff_client.export_state()
# Store in S3/DB with TTL
def monitor_post_cleanup(self, flag_keys: List[str], duration_hours: int = 24):
# Watch logs/metrics for mentions
# Alert + auto-rollback if anomalies
pass
sweeper.py)import click
from detection import FlagDetector
from windows import WindowMatcher
from safeguards import SafeguardValidator
@click.group()
def cli():
pass
@cli.command()
@click.option('--dry-run', is_flag=True)
def sweep(dry_run):
detector = FlagDetector(...) # Load config
candidates = detector.detect_unused()
matcher = WindowMatcher(...)
if not matcher.is_cleanup_window() and not dry_run:
click.echo("❌ Outside cleanup window.")
return
validator = SafeguardValidator(...)
pr_num = validator.propose_cleanup(candidates, "your-org/repo")
# Wait for approval (poll GH API) then execute
if click.confirm("Approved? Execute?"):
validator.execute_cleanup([c['key'] for c in candidates], 'prod', dry_run)
validator.monitor_post_cleanup([c['key'] for c in candidates])
if __name__ == '__main__':
cli()
config.yaml with API keys, thresholds.0 1 * * * python sweeper.py sweep --dry-run (daily dry-run).0 2 * * 0 python sweeper.py sweep (Sundays).sweeper_candidates_total, flags_cleaned.This sweeps away FF debt without a trace—safely. Questions, Watson? Run pip install -r requirements.txt and test in staging. 🔍