Implementing a Resilient Feature Flag Audit Service
As Sherlock, I'll deduce a comprehensive, resilient architecture for your feature flag audit service. This system will audit feature flags across your ecosystem (e.g., integrating with providers like LaunchDarkly, Flagsmith, or Unleash via APIs), ensuring reliability through observability, automation, and safeguards. We'll focus on resilience via redundancy (multi-AZ/region), idempotency, circuit breakers, and chaos engineering hooks.
High-Level Architecture
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Stakeholders │ │ Audit Service │ │ Flag Providers │
│ (Dashboards, │◄──►│ (API Gateway) │◄──►│ (LD, Flagsmith) │
│ Training) │ │ │ └──────────────────┘
└─────────────────┘ │ - Dependency Map │
│ - Health Checks │ ┌──────────────────┐
│ - Drift Detection│◄──►│ Data Stores │
│ - Rollback │ │ - Postgres (Meta)│
│ - Reporting │ │ - Neo4j (Graph) │
└──────────────────┘ │ - S3 (Logs/Runbooks)
└──────────────────┘
│
┌──────────────────┐
│ Monitoring/Alerts│
│ (Prometheus/Grafana)
└──────────────────┘
- Core Service: Go-based microservice (resilient with gRPC/REST, rate-limited API gateway like Kong).
- Data Flow: Pull/push from flag providers → Process → Store → Alert/Dashboard.
- Resilience Patterns:
| Pattern | Implementation |
|---|
| Redundancy | Deployed on Kubernetes (3+ replicas, multi-AZ). DBs replicated. |
| Circuit Breaker | Hystrix/istio for external API calls. |
| Backpressure | Kafka queues for async processing. |
| Idempotency | UUIDs + DB transactions for audits. |
| Self-Healing | Keda autoscaling + liveness probes. |
Tech Stack (cloud-agnostic, AWS/GCP lean):
- Backend: Go (fast, concurrent).
- Graph DB: Neo4j (dependencies).
- Relational DB: Postgres (audit logs, rules).
- Queue: Kafka (events).
- Dashboards: Grafana + Prometheus.
- Infra: Terraform + Kubernetes (EKS/GKE).
- Flag Integration: Provider SDKs (e.g.,
launchdarkly-api-sdk).
1. Dependency Graph Mapping
Map flags → services → envs → other flags (e.g., FlagA enables ServiceB, which uses FlagC).
Implementation
- Schema (Neo4j):
(:Flag {id: 'flag-uuid', name: 'new-paywall', env: 'prod', provider: 'ld'})
-[:DEPENDS_ON]-> (:Service {name: 'payment-api'})
-[:TOGGLES]-> (:Flag {id: 'crypto-support'})
- Go Service (
graph_mapper.go):
package main
import (
"github.com/neo4j/neo4j-go-driver/v5/neo4j"
"github.com/launchdarkly/api-client-go/v2" // Or your provider
)
func MapDependencies(driver neo4j.Driver, ldClient *launchdarkly.APIClient, env string) error {
session := driver.NewSession(neo4j.SessionConfig{DatabaseName: "flags"})
defer session.Close()
// Fetch flags from provider
flags, _, _ := ldClient.FeatureFlagsApi.GetFeatureFlags(ldClient.Context, env).Execute()
for _, flag := range flags {
// Parse rules/prereqs (e.g., targets, prerequisites)
tx, _ := session.BeginTransaction()
tx.Run("MERGE (f:Flag {id: $id}) SET f += $props", map[string]interface{}{
"id": flag.Key,
"props": map[string]interface{}{"name": flag.Name, "variation: flag.Variations},
})
// Add edges from flag rules (e.g., if rule targets 'payment-service')
tx.Run("MATCH (f:Flag {id: $flagId}), (s:Service {name: $svc}) MERGE (f)-[:TARGETS]->(s)", ...)
tx.Commit()
}
return nil
}
- Cron Job: Run every 5min via Kubernetes CronJob. Use webhooks from providers for real-time.
- Resilience: Retry with exponential backoff (backoff lib). Graph queries cached in Redis.
2. Health Checks
Active checks: Synthetic traffic with flags toggled; passive: Metrics from services.
Implementation
- Checks:
| Type | Example | Cadence |
|---|
| Synthetic | Toggle flag → API call → Assert 200 | 1min |
| Metrics | Error rate >5% when flag ON | 30s |
- Go Health Checker:
func RunHealthCheck(flagID string, ctx context.Context) HealthStatus {
// Toggle via provider API
ldClient.FeatureFlagsApi.EvaluateFeatureFlag(...).Execute() // ON
resp, err := http.Get("https://svc.com/endpoint") // Synthetic
// OFF, check again
return HealthStatus{Healthy: err == nil && resp.StatusCode == 200}
}
- Store in Postgres:
CREATE TABLE health_checks (
id SERIAL PRIMARY KEY,
flag_id UUID,
timestamp TIMESTAMPTZ,
status JSONB, -- {healthy: bool, latency: float}
UNIQUE(flag_id, timestamp)
);
- Alerting: Prometheus exporter scrapes metrics → Alertmanager if unhealthy >3min.
3. Drift Detection Rules
Detect config drift (e.g., prod flag %rollout != staging).
Implementation
- Rules Engine (Postgres + Go):
CREATE TABLE drift_rules (
id UUID PRIMARY KEY,
flag_id UUID,
rule_type TEXT, -- 'rollout_pct', 'targets'
expected JSONB, -- {"prod_pct": 100}
severity TEXT -- 'critical'
);
- Detector Service:
func DetectDrift(ldClient *launchdarkly.APIClient) []DriftAlert {
var alerts []DriftAlert
rows, _ := db.Query("SELECT * FROM drift_rules")
for rows.Next() {
var rule DriftRule
// Fetch actual from LD
actual, _ := ldClient.FeatureFlagsApi.GetFeatureFlag(ldClient.Context, rule.FlagID).Execute()
if actual.EnvironmentSettings["production"].VariationOrDefault != rule.Expected {
alerts = append(alerts, DriftAlert{FlagID: rule.FlagID, Severity: rule.Severity})
}
}
return alerts
}
- Kafka Topic:
drift-events → Consumers for alerts/Slack.
4. Rollback Runbooks
Automated + manual playbooks.
Implementation
- Runbooks (YAML in S3):
# rollback-runbooks/flag-123.yaml
name: Emergency Rollback - New Paywall
steps:
- cmd: ld-api patch-flag --key new-paywall --env prod --off
- cmd: kubectl rollout undo deployment/payment-api
- notify: slack://#incidents
- Rollback Service (Go):
func ExecuteRollback(runbookID string) error {
runbookBytes, _ := s3.GetObject("rollback-runbooks/" + runbookID + ".yaml")
// Parse YAML, execute steps idempotently (dry-run flag)
return nil
}
- Triggers: API endpoint (RBAC via OPA), drift alerts, health fails.
5. Reporting Dashboards
- Grafana Setup:
- Data Sources: Prometheus (metrics), Postgres (logs), Neo4j (graph viz).
- Panels:
| Dashboard | Queries |
|---|
| Flag Health | rate(health_checks_healthy[5m]) |
| Dependency Graph | Neo4j: MATCH (f:Flag)-[r]->(n) RETURN f,r,n |
| Drift Alerts | SELECT * FROM drift_rules WHERE severity='critical' |
| Audit Timeline | Timeline of toggles + rollbacks. |
- Export: PDF/CSV via Grafana API.
- API for Dashboards:
/api/audit/{env} → JSON for custom UIs.
6. Stakeholder Training
- Onboarding:
- Docs: MkDocs site (GitHub Pages) with tutorials: "How to add a drift rule", "Run rollback".
- Workshops: 1hr sessions: Demo dashboard → Simulate drift → Rollback.
- Self-Service Portal: Streamlit app for non-devs to view health/query graph.
- Access Control: RBAC – Viewers (dashboards), Editors (rules), Admins (rollbacks).
Deployment & Ops
# terraform/main.tf snippet
resource "kubernetes_deployment" "audit_service" {
replicas = 3
template {
spec {
container {
image = "your-repo/audit-service:latest"
liveness_probe { http_get { path = "/health" } }
}
}
}
}
- CI/CD: GitHub Actions → Build → Test (chaos: kill pods) → Deploy.
- Costs: ~$100/mo (EKS + RDS + Neo4j Aura).
- Next Steps:
- POC: Deploy graph + health checker.
- Integrate your flag provider.
- Chaos test:
chaos-mesh toggle flags randomly.
This is production-resilient and scalable. Ping me for code repos, tweaks, or deeper dives (e.g., full Terraform). What's your flag provider?