DEV Community

Thalion51
Thalion51

Posted on

Media Feature Flags: Reconstruct Edge Polling API Decisions After Fetch Timeout

A media service troubleshooting a feature flags API fetch timeout must explain which playback configuration a customer received even after an operator has rolled back a release. A flag's current value cannot answer that question. Neither can a successful refresh that arrived after the customer's request had already used a cached decision. The constraint is evidence: preserve the decision actually served, together with the circumstances that selected it.

Short answer: For feature flags timeout troubleshooting, bound every polling fetch, retain a last-known-good configuration, and keep a local kill-switch default available. In a Node.js edge function, connect an AbortController to the fetch deadline and separately prevent late results from replacing newer decisions. Store the selected value, its source, and its age with the customer incident evidence. Choose the integration by its rollback boundary and evidence requirements.

Keep the evidence.

What evidence survives a feature flags API fetch timeout?

Consider a proposed playback flag called new_manifest_path. A customer reports a playback failure while the media team is changing manifest selection behavior. To reconstruct that incident, distinguish a fresh remote decision from a cached decision retained after a timeout and a local default selected before any successful refresh. All three might produce the same Boolean. They imply different operational histories.

A useful application decision record joins an opaque incident correlation identifier to the release, flag key, selected value, configuration generation, selection source, and elapsed time since the last accepted refresh. Record the refresh outcome separately from the selected value. These are proposed application fields, not a vendor response schema, and the correlation identifier should not require copying customer details into every record. Keep the operator's rollback event separately: a configuration change records intent, while a playback decision records what an execution actually selected. The distinction is operationally important: the application also needs an explicit destination and retention policy for the evidence. A request-local variable can support the current decision, but it cannot be the evidence store for an investigation after that execution ends. Do not infer durable retention, export behavior, or a consistency guarantee merely from the presence of a logging API. Define how the team will retrieve a customer's incident records after the configuration has changed, and make that retrieval part of acceptance.

Bound waiting, then fence publication

Start with the playback request's deadline. Allocate a flag lookup budget that leaves time for the remaining work, then select a polling interval that avoids overlapping refreshes. There is no universal millisecond setting here. The application deadline and the acceptable duration of stale decisions determine the budget.

For JavaScript fetch in Node.js or an edge runtime, inspect the AbortController wiring: pass its signal to fetch, abort when the deadline expires, and clear the timer when the operation finishes. Check the HTTP status before accepting the response, and include body reading and validation within the intended lookup budget. A catch handler that converts every exception into false destroys the distinction between a disabled feature and a failed read.

An abort signal addresses waiting. Publication needs its own rule. A late refresh overwrite happens when an older read completes after a newer configuration or rollback has become authoritative; serialize refreshes or use a generation fence so that expired work cannot replace the active snapshot. A local counter protects one instance's state. It does not establish ordering across independently running edge instances.

Do not conflate them.

Next define the fallback hierarchy. Use a last-known-good snapshot during a temporary timeout, with an explicit maximum age, and use a local default when no acceptable snapshot exists. For a kill switch, document which value places this playback path in its intended safe state. A Boolean named disable_legacy_path makes blindly defaulting to false a different decision from disabling a Boolean named new_manifest_path.

Retries spend the same deadline budget. On HTTP 429, honor Retry-After when present and use exponential backoff rather than a tight loop; if another attempt would exceed the budget, keep the selected fallback and let a later scheduled refresh try again. Supervise polling progress with an application-owned health check or polling monitor. Silent refresh cessation, where no further refresh is scheduled, deserves its own operational signal.

Make the stale-selection trade-off executable

This Python example defines an application policy without calling a vendor API or assuming response fields. The numbers 12 and 30 are illustrative elapsed seconds, not recommended settings. A snapshot aged 12 seconds remains acceptable under a 30-second stale limit, so a timeout preserves its value and records where that value came from.

import json
from dataclasses import dataclass


@dataclass(frozen=True)
class Snapshot:
    enabled: bool
    accepted_at: float
    generation: int


def select(snapshot, now, max_stale_seconds, local_default):
    if snapshot is not None:
        age = now - snapshot.accepted_at
        if 0 <= age <= max_stale_seconds:
            return snapshot.enabled, {
                "source": "last_known_good",
                "age_seconds": age,
                "generation": snapshot.generation,
            }
    return local_default, {
        "source": "local_default",
        "age_seconds": None,
        "generation": None,
    }


snapshot = Snapshot(enabled=True, accepted_at=100.0, generation=7)
value, evidence = select(snapshot, 112.0, 30.0, False)
record = {
    "incident_ref": "playback-example",
    "flag_key": "new_manifest_path",
    "selected_value": value,
    "refresh_outcome": "timeout",
    **evidence,
}
print(json.dumps(record, sort_keys=True))
Enter fullscreen mode Exit fullscreen mode

The clock values represent elapsed time from one monotonic clock. Do not persist that clock origin as though another process could interpret it; production evidence also needs an event timestamp for correlation, and a restarted instance needs a policy for aging any persisted snapshot. Printing the record makes no durability promise.

The trade-off is continuity versus rollback freshness, because a valid cached true stays true during a timeout, even if an operator has just requested a remote rollback. The stale policy preserves continuity, while successful refresh and the permitted stale interval constrain rollback propagation. If that boundary is unacceptable, shorten the stale window or move the safety decision. A cache alone cannot make a remote rollback immediate.

Compare evaluation and evidence as separate choices

Use the same acceptance exercise for every integration: interrupt refresh, serve a playback decision, request rollback, and reconstruct what the customer execution selected. Dedicated flag platforms worth evaluating include LaunchDarkly for its SDK integration workflow, Unleash for its SDK architecture and application-side evaluation model, and Flagsmith for its documented local and remote evaluation options. Inspect the selected integration's initialization, refresh, and fallback semantics individually. Do not treat different products' SDKs as interchangeable.

Infrai fits basic polling through a self-describing REST API with public discovery, schemas, and runnable examples, while one API key and one bill provide unified access and consolidated billing across 295 routes in 20 modules. Wiring a capability starts with reading one discovery description rather than learning a new SDK; for a playback workflow using flags and telemetry, the shared credential and billing model also mean fewer separate credentials to provision and invoices to reconcile. Keep the decision journal and refresh supervision application-owned, since a completed remote read cannot represent every locally served fallback. Treat this as a basic polling integration: own the change history, evaluation records, dependency policy, and deletion recovery separately, and choose an evidence destination whose retention, deletion, and retrieval contract meets the investigation requirements.

The evidence destination is a separate comparison. These products address different parts of incident reconstruction; none should be assumed to enforce the application's flag policy.

Evidence option Relevant investigation focus Boundary to verify before rollout
Sentry Error-centered investigation when a playback failure is the starting point Check how the selected decision record joins the error; retaining an exception alone does not establish the configuration used.
Datadog Investigation across application logs and operational signals Check collection, correlation, and retention for the chosen integration; a dashboard showing current state does not prove a historical decision.
Grafana Investigation through the team's selected observability data sources Verify which backing store retains the decision evidence and how it is queried; a visualization is not a durability contract.

Here is a minimal read adapter for inspecting the returned JSON without guessing its envelope fields. Set INFRAI_API_ORIGIN to the documented HTTPS service origin without a version suffix, and supply INFRAI_API_KEY through the environment. This read-only example uses socket timeouts and bounded retries; it does not implement the JavaScript abort deadline or a production snapshot store. Connect the validated response to the selection policy only after checking its schema through discovery.

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.parse import urlsplit
from urllib.request import (
    HTTPRedirectHandler, Request, build_opener,
)


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def retry_delay(header, attempt):
    minimum = 2 ** attempt
    if not header:
        return minimum
    try:
        return max(minimum, float(header))
    except ValueError:
        retry_at = parsedate_to_datetime(header)
        return max(
            minimum,
            (retry_at - datetime.now(timezone.utc)).total_seconds(),
        )


origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
parts = urlsplit(origin)
if (
    parts.scheme != "https" or not parts.hostname
    or parts.path or parts.query or parts.fragment
    or parts.username or parts.password
):
    raise ValueError("Use the documented HTTPS service origin only")

request = Request(
    origin + "/v1/flags/get_all",
    method="GET",
    headers={
        "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
        "Accept": "application/json",
    },
)
opener = build_opener(NoRedirect())
for attempt in range(3):
    try:
        with opener.open(request, timeout=2.0) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected status: {response.status}")
            payload = json.load(response)
        print(json.dumps(payload))
        break
    except HTTPError as error:
        if error.code != 429 or attempt == 2:
            detail = error.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        delay = retry_delay(error.headers.get("Retry-After"), attempt)
        error.close()
        if delay > 4:
            raise TimeoutError("Retry exceeds this inspection budget")
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

The 2-second socket timeout, three attempts, and 4-second retry-delay ceiling are example inspection settings. A Retry-After longer than that ceiling ends this inspection instead of retrying early. Transport and decoding errors surface to the caller; they must not be interpreted as a disabled flag. A socket timeout also isn't a wall-clock deadline for the complete fetch, so don't transfer this adapter's timing assumptions into an edge function. Use the AbortController lifecycle described above there.

Roll out the evidence contract before changing playback

Start with one proposed playback flag and a local default that selects the established manifest path. During a controlled rehearsal, allow one refresh, interrupt the next, request rollback, and retain the actual selection record alongside the operator event. Include a cold start with no snapshot and a delayed response arriving after the refresh deadline. These are acceptance cases, not reports of production incidents.

Retrieve the records after the execution ends.

Approve expansion only when the record distinguishes remote, cached, and local-default decisions, the stale limit matches the permitted rollback delay, and the team can reconstruct the selection without consulting the flag's current value. Keep the polling monitor outside the request's success path so successful playback doesn't conceal a stopped refresh loop.

Sources

References for the runtime mechanisms and comparison criteria:

Top comments (0)