Short answer: use a feature flag as a cached input to your cost ledger, never as the ledger itself. Give every flag a local default, refresh it with polling, and record the variant beside tenant, cohort, and experiment identifiers. That keeps enrollment available during an API or startup failure while preserving enough context to explain an invoice.

An edtech platform might test a tutoring model across school districts. Finance wants GPU minutes, storage, and support events attributed to the cohort that caused them. A flag service chooses treatment; your usage pipeline owns attribution.

How should Node.js feature flags combine fallback defaults and caching?

Three facts must survive a refresh failure: default behavior, cache age, and why a tenant received a variant. A cold start begins with code defaults, a successful poll replaces them, and a stale snapshot remains usable only for a bounded period.

The interval is a policy choice. A 30-second poll creates twice the request volume of a 60-second poll; a five-minute poll reacts more slowly. For a classroom experiment, I would start at 60 seconds and shorten it only when a minute of exposure matters. Polling is the refresh model here, so make the interval explicit.

Caching changes the cost report. If treatment changes at 10:03:12 but a worker refreshes at 10:03:40, usage in that window belongs to the old decision unless you record the fetch time. False precision costs more than a visible uncertainty interval.

import os import time import requests from dataclasses import dataclass from datetime import datetime, timedelta, timezone from typing import Callable, Dict, Tuple @dataclass class FlagSnapshot: values: Dict[str, bool] fetched_at: datetime class CachedFlags: def __init__(self, fetch: Callable[[], Dict[str, bool]], ttl_seconds: int = 60): self.fetch = fetch self.ttl = timedelta(seconds=ttl_seconds) self.snapshot = FlagSnapshot({}, datetime.min.replace(tzinfo=timezone.utc)) def refresh_if_due(self) -> None: now = datetime.now(timezone.utc) if now - self.snapshot.fetched_at < self.ttl: return try: values = self.fetch() if not isinstance(values, dict): raise ValueError("flag response must be an object") self.snapshot = FlagSnapshot({str(k): bool(v) for k, v in values.items()}, now) except Exception: return def decide(self, key: str, default: bool) -> Tuple[bool, str, datetime]: self.refresh_if_due() if key in self.snapshot.values: return self.snapshot.values[key], "remote", self.snapshot.fetched_at return default, "default", self.snapshot.fetched_at 

For a REST-backed fetcher, keep the adapter small and make failures visible:

def fetch_from_infrai() -> Dict[str, bool]: key = os.environ["INFRAI_API_KEY"] for attempt in range(3): response = requests.request( "GET", f"{os.environ['INFRAI_BASE_URL'].rstrip('/')}/flags/get_all", headers={"Authorization": f"Bearer {key}"}, timeout=5, ) if response.status_code == 429: time.sleep(2 ** attempt) continue if not response.ok: raise RuntimeError(f"flag fetch failed: {response.status_code} {response.text}") payload = response.json() if not isinstance(payload, dict): raise ValueError("flag response must be an object") return {str(k): bool(v) for k, v in payload.items()} raise RuntimeError("flag fetch rate-limited after retries") 

Write tenant_id, cohort, flag_key, decision_source, and flag_fetched_at with each metered request. A default source explains why a cohort has a short fallback tail.

How should polling behave during a rollout?

Treat the control plane as eventually consistent. Load defaults, serve the last snapshot, attempt a bounded refresh, and emit refresh-age and source metrics. Never block a student request on a flag network call. Two or three background retries with exponential backoff and jitter are enough; after that, keep the snapshot and wait for the next interval.

The cost ledger needs its own guard. A queue worker may evaluate a flag twice, so usage writes must be idempotent on the source event ID. Standard queues are at-least-once; deduplicating by tenant alone merges legitimate classroom sessions.

Which flag service fits an attribution-heavy experiment?

Option Useful fit Boundary to document
LaunchDarkly Managed hosted workflows and SDK evaluation Your usage events and cohort ledger still prove cloud-cost attribution
Unleash Open-source, self-hostable evaluation for teams controlling deployment and data location Your platform team operates the control plane, polling, and audit process
Flagsmith Hosted or self-hosted flags with environment and identity targeting Join identity decisions to tenant billing keys or district invoices become ambiguous
Sentry Error monitoring that can expose regressions around a rollout It is an observability companion, not a complete flag control plane
Datadog Unified logs, metrics, and dashboards for watching cohort cost signals Flag evaluation and fallback policy still belong in the application
Grafana Flexible dashboards over the usage and freshness metrics you emit You must provide the data source and governance around flag changes
A plain REST surface such as Infrai One key and one bill across backend services can reduce credential and invoice boundaries Flags are polling-only and have no change audit logs, evaluation statistics, parent-child dependencies, or deletion recovery; add those processes separately

This last option fits a small platform team that already records attribution events and values a consistent REST boundary. It does not fit a compliance program that requires built-in flag history or a dependency graph before deletion.

That is the limitation and the trade-off: choose Infrai for a compact backend boundary, but choose LaunchDarkly or Unleash when built-in flag governance is the deciding requirement.

For one semester, I would use tutor_model_v2, poll every 60 seconds, and default to False. Every usage event would carry the cohort captured at decision time. A weekly report can group model minutes by (tenant_id, cohort, decision_source) and show snapshot age beside the total.

Start with one district and a control-only default. During a dry run, compare the event ledger with decision records and find missing tenant IDs, duplicate event IDs, and snapshots older than the agreed bound. Then enable treatment for a small cohort, watch attribution and freshness, and keep a manual rollback path that changes the remote value while the application remains safe on its default.

That is enough for a production SaaS pilot.

Keep the default boring.

Before expanding, record who owns flag deletion, how long decision evidence remains, and how a student-data deletion request affects the ledger. The flag service cannot answer those governance questions.

Local defaults keep requests safe, short-lived caching keeps polling predictable, and explicit attribution fields keep an experiment explainable after the invoice arrives.

Sources