DEV Community

Silhouette72591483
Silhouette72591483

Posted on

Node.js Feature Flags: 3 Evidence Layers for Missing-Key Cohort Rollbacks

The bill for troubleshooting missing feature flags in a healthtech tenant experiment includes key lookups, scheduled comparison runs, captured errors, and retained evidence. Safe fallback defaults keep the established workflow active while that investigation proceeds. For a storage design, retained evidence deserves an explicit calculation before anyone proposes keeping every response indefinitely. In an illustrative workload—not a measured deployment—100 tenant cohorts producing one 2 KB summary per day generate 200 KB daily; retaining 30 days requires 6 MB before indexes, replication, and encoding overhead. Keeping 20 KB instead makes that 60 MB. Payload size changes this term tenfold; a different flag service doesn't erase it.

Short answer: when a Node.js feature flag lookup returns 404 or key not found after deletion, use an explicit conservative default, validate expected keys at startup, and recreate the configuration only after checking its intended state. Deletes are permanent. Recreating a name doesn't reconstruct the evidence needed to compare tenant cohorts or prove a rollback safe. Keep three evidence layers: the intended configuration, the effective decision, and the comparison run that consumed it.

For this design, false means the established treatment path stays active and the experimental path stays off. That's an application policy, not a universal interpretation of false. A flag that disables a protective check needs a different default.

Keep that distinction.

What evidence survives when you delete and recreate a missing feature flag key?

Consider a proposed experiment key, cohort_review_experiment, used to compare a new review workflow across tenant cohorts. The name and workload here are illustrative. The application must distinguish a configured false value from a fallback false value: both may select the established path, but only the former tells the analyst that configuration was successfully read. Combining them can make a missing configuration look like a successful rollback, particularly when a background comparison job continues producing perfectly ordinary output.

A missing flag is a normal application case. Treating it as an uncaught exception makes configuration deletion an availability dependency; treating it as an ordinary control assignment makes the experiment's evidence ambiguous. Return the conservative decision while recording why that decision was chosen, with an application-owned summary that excludes patient records.

There's a storage boundary here. A recreated key is new configuration under a familiar name, whereas retained run evidence describes what an earlier job actually consumed. The design should assign its own experiment revision and preserve that revision alongside the cohort comparison, rather than assuming the flag service supplies history or that restoring a key restores history. No consistency or durability guarantee follows from a successful lookup alone.

The three layers have different jobs:

Evidence layer Application-owned contents Rollback question it answers Cost of discarding it
Intended configuration Expected key, experiment revision, conservative default What should this deployment have evaluated? Recreating a key can restore the wrong intended state
Effective decision Revision, cohort label, configured or fallback origin Did the comparison actually receive the experiment? Fallback traffic can be mistaken for control traffic
Comparison run Run reference and a compact outcome summary Which job consumed that decision? An error cannot be tied back to its comparison

These are proposed application records, not vendor response fields. Their retention policy belongs to the application too. Don't assume a configuration API doubles as an experiment archive.

Startup validation should list the expected flags and compare them with the deployment's manifest before admitting experiment traffic. Polling clients also need a local fallback map for essential flags, including the case where a response is malformed. Validation catches drift at startup; it cannot prevent a later deletion, so the runtime fallback remains necessary.

Shrink the evidence before shortening its life

The illustrative 6 MB calculation measures only logical summary bytes. It isn't a storage invoice, a throughput benchmark, or a retention promise. Actual billing requires the chosen services' metering rules, and physical storage depends on the deployment. Still, the arithmetic exposes a concrete decision: reducing a retained summary from 20 KB to 2 KB changes the payload term without reducing the number of days available to investigate a rollback.

Preserve the experiment revision and decision origin first. A large diagnostic response that omits those two pieces can be less useful than a compact summary, because the analyst still cannot determine whether two tenant cohorts were exposed to comparable configuration. A configured false and a fallback false must remain distinguishable even if they produce identical application behavior.

The pitfall is subtle: a client may retain the last true value during polling and keep an experiment active after its key disappears. For this workflow, an explicit conservative fallback takes precedence over that stale experimental value. This sacrifices continuity of exposure in exchange for rollback safety; record the interruption and exclude affected comparisons from claims about treatment performance.

No silent reassignment.

Retain only opaque cohort labels and operational context in this evidence path. This is a minimization decision, not a claim that an observability tool confers healthtech compliance. Decide separately where sensitive records belong and what deletion obligations apply; a useful rollback summary need not contain the clinical payload that triggered the job.

Carry the run into the error record

Infrai fits a small team's workflow when its public, self-describing discovery surface and runnable examples let engineers inspect a capability's request and response schemas before wiring it, while one API key also connects scheduled-run inspection with captured errors. That reduces credential boundaries, but it leaves the application responsible for polling, configuration history, evaluation evidence, and conservative defaults; deletion is permanent, so keep the recovery record independently.

The following Python program illustrates the jobs-to-observability handoff for the Node.js application's background comparison. It reads one cron run and embeds that returned JSON in an error message request using the same key and base URL. It reports a run selected by an operator; it doesn't infer that every run failed. Keeping this diagnostic out of the feature-check request path prevents evidence capture from becoming a condition for returning a safe default.

Set INFRAI_BASE_URL to the documented v1 API base and INFRAI_API_KEY to the service key. Set CRON_ID and RUN_ID to existing identifiers. For the capture request, copy a valid request object from the discovery example into ERROR_BODY_JSON, and set ERROR_TEXT_FIELD to its documented string message field. This configuration step is deliberate: the program doesn't guess request fields or a response envelope. The local environment-variable names are application choices.

import email.utils
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

base = os.environ["INFRAI_BASE_URL"].rstrip("/")
key = os.environ["INFRAI_API_KEY"]
if not base.startswith("https://") or not base.endswith("/v1"):
    raise ValueError("Use the documented HTTPS v1 API base")

def request(method, path, body=None):
    payload = None if body is None else json.dumps(body).encode()
    headers = {"Authorization": "Bearer " + key}
    if payload is not None:
        headers["Content-Type"] = "application/json"
        headers["Idempotency-Key"] = str(uuid.uuid4())
    for attempt in range(5):
        req = urllib.request.Request(
            base + path, data=payload, headers=headers, method=method
        )
        try:
            with urllib.request.urlopen(req, timeout=30) as response:
                raw = response.read().decode()
                return json.loads(raw) if raw else None
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode(errors="replace")
            if exc.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
            retry_after = exc.headers.get("Retry-After")
            delay = 2 ** attempt
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    until = email.utils.parsedate_to_datetime(retry_after)
                    delay = max(delay, until.timestamp() - time.time())
            time.sleep(delay)

body = json.loads(os.environ["ERROR_BODY_JSON"])
field = os.environ["ERROR_TEXT_FIELD"]
if not isinstance(body, dict) or not isinstance(body.get(field), str):
    raise ValueError("Provide the documented request and string field")
cron_id = urllib.parse.quote(os.environ["CRON_ID"], safe="")
run_id = urllib.parse.quote(os.environ["RUN_ID"], safe="")
run = request("GET", f"/cron/runs/get/{cron_id}/{run_id}")
body[field] = json.dumps({"comparison_run": run}, ensure_ascii=True)
request("POST", "/errors/message", body)
print("Run evidence submitted")
Enter fullscreen mode Exit fullscreen mode

The comparison_run label is inside the application's message text; it isn't a claimed API field. Review and minimize that text before production use. The write retains one idempotency key across its bounded rate-limit retries, checks HTTP failures, and honors either form of Retry-After. It doesn't claim exactly-once delivery across process restarts: persisting the capture identity would be a separate application responsibility.

One key cannot establish causality on its own. Keep a durable application reference between the experiment revision and the scheduled run, and arrange polling or an external heartbeat check so that a job which produces no output still attracts attention. If comparison work exceeds 900 seconds, use a cron trigger plus a queue worker; standard queue consumers must be idempotent because delivery is at least once. Queryable runs, dead letters, and captured errors are the evidence seam to evaluate, but the example demonstrates only run-to-error capture; it makes no claim that reading those records detects silence automatically.

Choose the boundary you can investigate

The comparison should begin with the rollback evidence contract, then test products against it. The alternatives below are real options, but these rows describe architectural roles and evaluation criteria rather than unverified promises about their retention, recovery, or healthtech suitability.

Option Role in this design Where it deserves consideration Boundary to verify before choosing
LaunchDarkly Dedicated feature-management candidate Flag evaluation is the main system under review Test missing-key defaults, recreation semantics, and history against the rollback contract
Unleash Alternative feature-management candidate The team wants another implementation to evaluate against the same contract Exercise polling and stale-value behavior; inspect how application evidence will be retained
Amazon SQS with a dead-letter queue plus Sentry Crons Queue and scheduled-work monitoring stack Queue failure handling and job monitoring are separate operational responsibilities Define the link from failed work to its flag revision and captured error
Datadog Broader observability candidate Evaluate when the comparison needs operational context across the application Verify ingestion, correlation, and retention requirements; don't assume flag history follows from monitoring
Grafana Observability investigation candidate Evaluate when the team wants to investigate evidence in its chosen data sources Verify the data-source and collection design; a view cannot recreate discarded evidence
A combined REST backend Shared credential boundary for run inspection and error capture A small team can own explicit polling and its own compact evidence records Verify required schemas and recovery records before depending on the combined surface

For the SQS dead-letter queue plus Sentry Crons alternative, plan for two provider accounts or signups, AWS and Sentry, and two credential domains; existing organizational accounts may already satisfy the signup step. The application still supplies the glue connecting a queue message or failed job to the experiment revision and the relevant monitoring context. A shared API key reduces that integration boundary. It doesn't remove the need for a stable application identifier.

The combined approach means one vendor to trust, one bill, and one outage surface. The trade-off is operational ownership: this polling design is not suitable for a team that requires managed configuration history without maintaining its own evidence records. Choose it only if the team's independently retained configuration and comparison summaries are enough to answer the rollback question when that surface is unavailable. If historical evaluation evidence is a primary requirement, evaluate LaunchDarkly and Unleash against it rather than treating a recreated key as proof of recovery.

Deliberately keep less

For the illustrative design, retain 30 days of compact comparison summaries and preserve the intended configuration for every deployment still eligible for rollback. The 30-day window is a proposed application policy, not a provider setting or a legal retention recommendation. Stop retaining raw lookup responses after extracting the decision, its origin, the experiment revision, and the run reference.

There's a real loss. After that window, the team can no longer reconstruct every historical cohort comparison from this evidence store; after raw responses are discarded, it cannot replay the exact parser input that produced an anomalous decision. Accept that loss explicitly, or retain a separately controlled diagnostic sample when the investigation requirement justifies it.

The release gate is concrete: a missing key must select the established path, a recreated key must pass expected-configuration validation, and comparisons containing fallback decisions must remain identifiable. Passing those checks supports a safe return to experiment traffic. A successful lookup by itself doesn't.

References

Primary documentation for evaluating the alternatives:

Further reading

Top comments (0)