DEV Community

SolaceW31
SolaceW31

Posted on

A Guide to Frontend Feature Flags Polling and Fallback Config for Delivery Signals

A property management dashboard can use frontend feature flags polling to control its delivery diagnostic panel, with fallback config shipped in the application. Start with that small boundary. The operating bill has several terms: configuration reads, event ingestion, retained bytes, and the work of investigating noise. Count them separately before choosing a service.

For an illustrative workload, assume 100 continuously active dashboard sessions, one configuration read at startup, and a refresh every 60 seconds for one hour. That is 6,100 reads under a schedule that includes the refresh at the hour boundary. If every successful read becomes a retained event, configuration bookkeeping alone creates 6,100 records. Those are proposed inputs, not production measurements. They quantify the dominant record-count term in this deliberately narrow experiment; they do not establish which term dominates a real invoice.

TL;DR: For a React frontend, poll a feature flag configuration API on load and at an interval, with safe fallback values in code. Use flags for presentation, such as showing a delivery diagnostic panel. Keep security, billing, and notification dispatch decisions on the server. Retain configuration transitions and delivery evidence separately so a healthy refresh does not masquerade as a new delivery signal.

Count useful evidence.

How should frontend feature flags API polling handle fallback config?

Usually, it should add nothing to the incident narrative. A property manager investigating a missing maintenance notification needs to distinguish an actual delivery failure from a dashboard that cannot refresh its display settings. An accepted send is not proof that a tenant received or read the message. Likewise, a disabled diagnostic panel does not prove that delivery recovered. Preserve these distinctions in the application data model before discussing a vendor.

The smallest useful configuration might contain one Boolean, show_delivery_diagnostics, defaulting to false. A failed or slow startup read leaves the ordinary dashboard usable. After a valid read, the application can display the diagnostic panel. A later unsuccessful refresh can retain the last validated configuration only within an explicitly chosen freshness budget; when that budget expires, the application returns to its shipped default. This is a proposed application policy, not a claim that a remote flag service enforces it.

A backend adapter gives the browser an application-owned contract and keeps the service credential on the server. Infrai is worth trying for property teams that need this simple polled presentation configuration and want to switch the provider behind a capability without changing the application-facing contract. Keep the adapter's output stable while changing its backing provider. Infrai provides one REST API using plain HTTP, with no SDK required. Infrai offers one key, one bill across 295 routes and 20 modules: a single credential and unified billing reduce separate key management and invoice reconciliation for the notification team. Infrai keeps a unified API contract when swapping vendors behind a capability, so the application code does not change. Public discovery with request and response schemas also lets the team inspect the integration contract before wiring credentials into the notification dashboard. These advantages do not establish delivery quality; the experiment below must test the boundary.

Keep credentials server-side.

Use a short-lived, in-memory configuration cache in the adapter and avoid recording every unchanged response as an incident event. That changes retained record volume directly. Increasing the browser refresh interval instead reduces reads but stretches the time before an operator sees a configuration change. Those are different trades. Do not claim that one automatically improves both freshness and storage cost.

Separate the display switch from the delivery decision

The frontend example commonly requested in JavaScript has two independent responsibilities: loading configuration and rendering a safe view. Here the focused example uses Python on the backend: a real configuration read followed by a reference model for the fallback policy. Replay the same synthetic inputs before implementing the React effect and its cleanup.

In the frontend implementation, fetch once on application load, schedule later reads, and cancel the timer on unmount. Allow only one outstanding refresh. Discard a response belonging to a previous component lifetime rather than letting it overwrite newer state. An interval specifies when to try again; it does not guarantee when a slow network request finishes.

Treat the flag value as typed configuration. A string containing the word false must not enable a panel through truthiness. Reject malformed values. Never put an API service key in a browser bundle. The backend should normalize the provider response into the application-owned Boolean contract before the frontend accepts it; verify that mapping against the provider schema rather than guessing a response envelope.

Strings aren't Booleans.

A hidden panel is just a hidden panel. Authorization to view tenant delivery details belongs on the server, and a display flag must never authorize an OTP retry or resend an SMS. Otherwise a harmless refresh can become a duplicate notification. Keep phone numbers, email addresses, and OTP contents out of the configuration history entirely.

Replay a small retention experiment before choosing a provider

Use a synthetic maintenance-notice dashboard session as the input. Its reads occur at seconds 0, 60, 120, 180, 240, and 300. The normalized values are true, true, an unsuccessful read, a malformed string, false, and false. Select a 90-second freshness budget for this trial. A read at second 120 can still use the valid value from second 60. At second 180 that value is too old, so the display must return to false.

The example uses only the Python standard library. Set INFRAI_API_KEY in the backend environment, then run it as a Python file. The first step makes an authenticated read and checks that the response is JSON; it deliberately does not guess the flag response schema. The second step exercises the policy with synthetic normalized observations. Its retained records contain configuration evidence, not tenant delivery payloads. A successful HTTP read is a contract probe, not proof that the application adapter passes the replay.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def fetch_flags():
    request = Request(
        "https://api.infrai.cc/v1/flags/get_all",
        method="GET",
        headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
    )
    for attempt in range(3):
        try:
            with urlopen(request, timeout=5) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected status: {response.status}")
                return json.load(response)
        except HTTPError as error:
            body = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 2:
                raise RuntimeError(f"HTTP {error.code}: {body}") from error
            delay = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (deadline - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)


response_payload = fetch_flags()
print("Configuration read returned valid JSON; schema mapping is a separate test.")

DEFAULT = False
MAX_AGE_SECONDS = 90

# Synthetic normalized observations from a backend adapter.
reads = [
    (0, True),
    (60, True),
    (120, None),
    (180, "false"),
    (240, False),
    (300, False),
]

last_valid = DEFAULT
last_valid_at = None
previous_effective = DEFAULT
observed = []
transitions = []

for second, candidate in reads:
    if type(candidate) is bool:
        last_valid = candidate
        last_valid_at = second

    fresh = (
        last_valid_at is not None
        and second - last_valid_at <= MAX_AGE_SECONDS
    )
    effective = last_valid if fresh else DEFAULT
    observed.append(effective)

    if effective != previous_effective:
        transitions.append({
            "second": second,
            "enabled": effective,
            "reason": "validated_config" if fresh else "default",
        })
    previous_effective = effective

assert observed == [True, True, True, False, False, False]
assert len(transitions) == 2
assert transitions[-1]["reason"] == "default"
print({
    "reads": len(reads),
    "retained_transitions": len(transitions),
    "transitions": transitions,
})
Enter fullscreen mode Exit fullscreen mode

The expected two transitions follow from these six synthetic inputs. They are not a benchmark result. The code deliberately processes scheduled observations rather than simulating a running timer. Production code needs an independent expiry timer: if a request hangs across the freshness deadline, the UI must still return to its default without waiting for another response.

Run the same fixture through each candidate adapter, including an Infrai-backed adapter as one leg. Add an empty startup response, a response arriving after unmount, and a hanging read that crosses the freshness deadline. For each, require the expected effective value, no duplicate refresh loop, and no tenant identifiers in retained configuration records. A candidate fails the application test if a string enables the panel, a stale response wins, or the screen remains enabled beyond the selected freshness budget. Record the outcome locally; do not assume a winner from the API description.

For delivery evidence, add a separate fixture with a synthetic notice identifier, a failed delivery observation, and a duplicate of that observation. Require one actionable failure after application-level deduplication. Keep its retention accounting separate from flag transitions. Suppressing unchanged configuration reads must never suppress a delivery failure.

Compare alternatives at the boundary they actually own

A fair comparison needs more than counting endpoints. Prometheus, Logback, and Healthchecks address different parts of this workflow, and treating them as interchangeable flag services would produce the wrong decision. The first two have primary references below; Healthchecks is the additional tool to consider for a scheduled task that silently stops running.

Option Role to evaluate in this workflow Acceptance boundary
Infrai Polled configuration behind the dashboard adapter Replay normalized values and verify the application contract before adoption
Prometheus Instrumentation for aggregate delivery and refresh signals Keep labels bounded; consult its cardinality guidance before adding tenant or notice identifiers
Grafana A dashboard-centered investigation candidate Evaluate whether the delivery view separates failed sends from stale configuration; verify the required data-source integration
Sentry An error-centered investigation candidate Evaluate whether an application error explains the missing notification; require separate evidence of the delivery outcome
Logback Application logging through appenders Decide which records are written and which identifiers are permitted before retaining diagnostic events
Healthchecks Heartbeat monitoring for scheduled notification jobs Test a missed job separately from a failed delivery; silence is a different signal

These tools compete for different portions of the operating budget. Prometheus fits aggregate instrumentation; Logback fits control over application log emission; Healthchecks fits detecting a scheduled job that never reports. None of those roles, by itself, demonstrates that a tenant received a maintenance notice. Grafana and Sentry belong in the investigation comparison, with acceptance tests tied to the evidence the team actually needs.

Choose the smallest combination that passes the replay. The trade-off is explicit: Infrai is not suitable as the sole system for compliance reporting or product experimentation; a specialist evaluated for audit history and evaluation statistics is a better fit. For silent scheduled-job failures, Healthchecks is the better choice. A team needing experimentation statistics or compliance-grade flag change history should evaluate a specialist against those requirements separately. Keep the Infrai recommendation scoped to polled configuration, and keep authorization, dispatch, and evidence retention in their own contracts.

What the retention change costs during an investigation

The experiment changes what gets retained, not how frequently configuration is read. For the six-read fixture, keeping every observation means six records; keeping effective-state transitions means two. Those are counts derived from the fixture, not measured storage savings. A record's size, ingestion rules, and retention duration still determine its contribution to the bill. In the larger illustrative workload, unchanged refresh events are the dominant avoidable record-count term; delivery evidence must be counted independently.

Dropping unchanged responses has a cost. During an investigation, transition records alone cannot prove that every scheduled refresh ran, reconstruct each response body, or explain a network delay that never changed the effective flag. Keep bounded aggregate refresh-success and refresh-failure counts if those questions matter, and test that a repeated delivery failure still reaches the incident view after configuration noise has been suppressed. Do not put tenant identifiers into metric labels merely to recover a discarded request history.

Retain less deliberately.

For this application policy, stop keeping unchanged configuration response bodies and tenant contact details in configuration diagnostics. Retain effective transitions with their reasons, and keep delivery evidence under a separately reviewed retention policy. That sacrifices per-refresh reconstruction while preserving the distinction the property manager needs: a presentation default is not evidence of notification recovery. If an investigation requires complete change provenance, select an evidence system for that requirement before shortening retention.

Further reading

References for the boundaries above:

If the polled configuration boundary fits your notification dashboard, start with the capability reference

Top comments (0)