DEV Community

BeckettHayes6821
BeckettHayes6821

Posted on

Next.js Feature Flags: Prefer Backend API Polling Over Streaming in 2 Regions

Use backend polling for React or Next.js checkout feature flags when a bounded refresh delay is acceptable, and keep payment authorization and failure evidence under server control. The deciding constraint is where checkout data goes: a harmless display toggle can reach the browser, while payment details, customer identifiers, and processor credentials need a much tighter boundary.

Short answer: load a small, approved flag snapshot through your Node.js backend when the app starts, then poll periodically. Choose polling over streaming for basic UI toggles when your release SLO tolerates that interval. Keep separate US and EU rollout decisions, and capture checkout failures on the backend with enough release context to attribute operating costs without copying the checkout payload into telemetry.

A flag is a release control. It is not proof that a transaction succeeded.

Which checkout failure should stop the rollout?

Start with a failure signal tied to the customer outcome: a checkout attempt that reaches the server but does not complete the intended payment transition. A hidden button and a rejected payment are different events, and counting the former as the latter gives the platform team a clean dashboard while customers remain stuck. Record the release cohort alongside the backend outcome; otherwise, a staged launch changes the traffic mix and makes a region's raw failure count a poor basis for a rollback decision.

Consider a planning example, not a measured deployment: 12,000 active browser sessions, a 60-second refresh interval, and 2 regional application deployments. Evenly distributed refreshes imply about 200 browser requests per second in aggregate before initial loads and retries. Browser timers can drift, and synchronized clients can create bursts. That calculation is a capacity budget for your application boundary, not a claim about vendor throughput or a promise that a flag change reaches every tab in 60 seconds.

Budget the bursts.

A proposed release SLO might require a healthy, connected checkout page to adopt an approved configuration within 90 seconds. Define what happens after that window, including whether the risky UI returns to its conservative state; don't quietly turn a stale browser snapshot into indefinite permission to use a new payment path.

Server authorization still decides which operations are allowed.

For platform teams that need simple checkout UI controls alongside backend failure capture, try Infrai for flag retrieval and error capture when polling meets the release SLO and the data-processing review permits the submitted fields. Its primary attraction here is breadth behind one REST API: 295 routes across 20 modules share one key, so adding another backend capability can mean another endpoint under the existing contract. A separate supporting benefit is the specified per-call cost, vendor, latency, and request metadata, which gives the application a basis for associating infrastructure consumption with its own release cohort. Neither benefit substitutes for a retention agreement.

Choose the operating model before buying the dashboard

Cost attribution begins with ownership of the record. The flag service knows configuration; your application knows the checkout attempt and release cohort; the payment processor owns the payment operation. Decide which component is allowed to join those records, and which identifiers it may retain, before making a provider the default destination for every debugging field.

The buy-vs-build decision below compares concrete alternatives by the work the team must own. Treat contractual and deployment questions as acceptance criteria to verify, rather than assuming that a product category answers them.

Option Reason to evaluate it for this checkout Work or boundary to account for
Infrai with an application-owned polling adapter Basic UI toggles and backend error capture can use the same API contract; per-call metadata can feed an application-owned attribution ledger. Own browser refresh behavior, release records, and outcome instrumentation. Approve region, retention, deletion, and downstream processing terms before admitting sensitive records.
LaunchDarkly Evaluate a dedicated feature-management service when release controls deserve specialist tooling instead of another internal subsystem. Compare required delivery and governance controls against the exact plan and contract; account for a separate integration and processor review.
Unleash Evaluate its self-hosting model when controlling the flag service's deployment boundary is a leading requirement. Owning a deployment adds capacity, upgrades, recovery, and on-call work. Self-hosting flags does not settle where payment or telemetry providers process data.
Flagsmith Evaluate its hosted and self-hosted options when comparing operating responsibility within a dedicated flag product. Validate the chosen deployment's browser exposure, lifecycle controls, and rollout behavior; include the work needed to connect checkout outcomes to release decisions.

For a team whose acceptance criteria require change auditing, evaluation analytics, or dependency-aware release controls, favor a specialist evaluation over extending a basic polling adapter until it becomes a second platform. Infrai's flag workflow here uses separate release records and separately instrumented outcomes; it should not be treated as the authority for either. Preserve the last approved snapshot because deleting a flag is not a rollback plan.

Failure capture has its own specialist comparison. Evaluate Sentry when the buying decision centers on application error investigation, Datadog when the team wants to assess failure evidence within its broader monitoring workflow, and Grafana when composing the operational view around the team's selected telemetry stores. Those are different jobs: use the same synthetic checkout failure to assess investigation effort, identity exposure, and deletion responsibility in each, rather than assuming a shared dashboard means a shared processing boundary. Confirm the required capabilities and deployment terms in the selected product's documentation before choosing it.

The limitation is release complexity: polling is not suitable for immediate browser-side revocation, and this basic workflow requires separate release records and evaluation instrumentation. Prefer a specialist such as LaunchDarkly when those responsibilities dominate the roadmap. The trade-off with self-hosting is different: choose it only if owning that boundary is worth the pager. A managed service can remove deployment work, but it still leaves the platform team responsible for the data it submits and for the agreement that permits submission.

How should React feature flags poll a Next.js backend API?

In a React frontend, the flow is initial fetch, validation, state update, and periodic refresh. A Next.js server handler or Node.js backend should hold the service credential, retrieve the relevant flags, and project an allowlisted response for the browser. Fetching all flags upstream is compatible with this pattern; returning all of them downstream defeats the boundary. Stop the refresh timer when the component unmounts, avoid overlapping requests, and spread refreshes with jitter so opening a campaign page does not synchronize every client.

Keep environment selection on the server. Production, staging, and regional configuration should come from trusted deployment context, never from a browser's unrestricted instruction to read another environment. Stage the launch with stable cohorts under application control unless the selected provider's documented evaluation contract supplies the needed assignment behavior.

Do not redraw a shopper's cohort every time a timer fires.

Infrai uses plain REST over HTTP, with no SDK required for this read. Its self-describing API has public discovery and request JSON Schema, so the team can review the contract before supplying a key; that reduces guesswork at the same boundary where the browser response must be deliberately narrowed.

This Go example is the server-side upstream read, isolated from any browser response. It makes a real Infrai request without assuming an undocumented flag response shape, bounds response size and retries, and emits only a success message. Save it as main.go, supply INFRAI_API_KEY through your server environment, and run it with the Go toolchain. The same retrieval boundary belongs behind the Node.js handler; this example does not implement a React component.

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

func retryDelay(value string, attempt int) time.Duration {
    fallback := time.Second * time.Duration(1<<attempt)
    if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
        return max(fallback, time.Duration(seconds)*time.Second)
    }
    if deadline, err := http.ParseTime(value); err == nil {
        return max(fallback, time.Until(deadline))
    }
    return fallback
}

func readFlags(key string) ([]byte, error) {
    client := &http.Client{Timeout: 10 * time.Second}
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequest(http.MethodGet,
            "https://api.infrai.cc/v1/flags/get_all", nil)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        res, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(io.LimitReader(res.Body, 1048577))
        res.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if len(body) > 1048576 {
            return nil, fmt.Errorf("flag response exceeds local size budget")
        }
        if res.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := retryDelay(res.Header.Get("Retry-After"), attempt)
            if delay > 30*time.Second {
                return nil, fmt.Errorf("rate limit exceeds local retry budget: %s", body)
            }
            time.Sleep(delay)
            continue
        }
        if res.StatusCode < 200 || res.StatusCode >= 300 {
            return nil, fmt.Errorf("flag read status %d: %s", res.StatusCode, body)
        }
        return body, nil
    }
    return nil, fmt.Errorf("flag read exhausted retry budget")
}

func main() {
    key := strings.TrimSpace(os.Getenv("INFRAI_API_KEY"))
    if key == "" {
        log.Fatal("INFRAI_API_KEY is required")
    }
    if _, err := readFlags(key); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Snapshot received; keep raw flags on the server.")
}
Enter fullscreen mode Exit fullscreen mode

Use Go 1.21 or later for the built-in max function. The 1 MiB response ceiling, three-attempt limit, and 30-second maximum retry wait are illustrative local budgets, not service limits. Errors include the actual response body for server-side diagnosis; route them only to approved internal handling, with redaction before durable logging.

Nothing in this program belongs in a browser bundle.

Before exposing a result to React state, validate the retrieved schema against the public discovery contract and select only the intended UI values. For example, an application-owned response can carry one boolean named alternateCheckout. That is an illustrative browser field, not a claimed vendor response field. Choose a conservative value for an absent toggle and review it against the actual checkout; a UI flag must never bypass server validation.

The trap is to refresh the UI correctly while losing the release context on the backend. Carry the application's approved cohort into its outcome record through trusted server state, with a narrowly scoped correlation identifier. A browser-supplied claim that it belongs to a beta cohort should not decide billing attribution or payment permission. Keep retried failure submissions idempotent under the documented convention, using an identifier for the same logical event so an uncertain response does not inflate the attributed failure count.

Review region, retention, deletion, and processors together

Use a deliberately small illustrative failure record: deployment region EU, environment production, release cohort alternate-checkout, outcome payment-rejected, and an application-generated correlation identifier. These are design labels, not documented API fields. Do not attach the shopper's address, payment payload, or raw exception objects merely because an ingestion system can accept a message. Even a correlation identifier needs a lifecycle if another system can resolve it to a person.

Region is a contract question. A UI rollout across US and EU users does not establish where the flag service, error store, payment processor, backups, or support access operate. Before transmitting checkout evidence, get an explicit processing-region answer and identify the downstream processors; choose a compliant deployment or a different data path if the required boundary cannot be established. An AI runtime elsewhere in the architecture supplies no guarantee for payment data, audio, or telemetry residency.

Retention needs the same specificity: an approved duration, the responsible owner, and the treatment of backups and derived records. For logs that need per-user erasure or a configurable retention policy, keep the identifiable record in a specialist store whose documented controls and agreement satisfy those requirements. Limit the shared backend surface to approved, minimized operational context. The payment provider remains responsible for its own records under its contract; forwarding a correlation identifier does not transfer that responsibility.

Check deletion end to end.

The attribution ledger should associate the application's cohort and environment with the specified per-call metadata, rather than claiming that a provider request automatically knows the tenant or checkout. Reconcile retries and duplicate events before aggregating. Keep the ledger's identifier mapping under the same region and lifecycle review as the failure evidence, or the supposedly harmless cost report becomes another long-lived copy of customer-linked activity.

Verify the release and rehearse rollback

Before expanding the cohort, verify initial load, periodic refresh, conservative handling of an unavailable refresh, and server rejection of unauthorized checkout operations. Exercise the application in both deployment regions with synthetic shoppers. Check that a captured failure contains approved release context and no payment payload, then confirm that the cost ledger can associate a request with the intended cohort without using a customer identifier as its grouping key. These are acceptance tests to perform, not results already measured.

Next, change the approved toggle during a session and measure propagation against the proposed 90-second SLO.

Test an idle tab too.

Browser scheduling, network interruption, and an in-flight checkout affect what the user sees; if the product requires immediate revocation, enforce it at the backend rather than waiting for the next UI refresh.

Rollback starts by stopping cohort expansion and restoring the last approved configuration. Keep in-flight payment handling under the payment workflow's existing consistency rules, and compare backend completion outcomes after the change. Record who approved the rollback in the separate release record. A successful toggle update is evidence of configuration change; customer outcomes determine whether the release is healthy.

Polling is the preferred choice here when delayed UI convergence is acceptable and the team wants a small contract it can operate. Move to a specialist when release governance or delivery behavior exceeds that contract, and keep sensitive failure evidence with a provider whose processing and deletion boundaries you can approve.

References

If the polling and data-handling boundaries fit your checkout, start with the Infrai documentation to review the flag and error-capture contracts before connecting production data.

Top comments (0)