DEV Community

NyxenL29
NyxenL29

Posted on

Import Feature Flags: Set over Toggle for Safer Marketplace Rollbacks

Set feature flags to an explicit desired state for marketplace import rollbacks; retrieve the configuration before and after changing it, and reserve toggle for a supervised inversion. For Node.js services using a REST API, that means treating set, toggle, and retrieve as different operations with different retry risks. None proves that a scheduled importer produced useful results.

TL;DR: Prefer assignment over toggle when rollback safety matters. Pair configuration checks with a completion monitor that alerts when expected import results do not arrive.

Read the contract.

Setting the same value repeatedly is safe only if the documented update behavior preserves the intended configuration. A replacement operation can overwrite unrelated settings even when the boolean looks correct, so the rollback plan must preserve the configuration the worker actually needs.

How should you set and retrieve feature flags without unsafe toggle retries?

A marketplace can permit its scheduled catalog import while no new catalog results arrive. The control plane describes permission; the completion signal describes an outcome. Confusing them produces a dashboard that looks healthy while sellers wait for refreshed inventory.

Consider an illustrative operating policy: an import is due every 15 minutes, with a 5-minute completion allowance. The SLO concerns fresh import results by that deadline. A successful flag read establishes configuration availability, while an empty import needs a business rule to distinguish legitimate empty input from missing results. Record the scheduled run and the outcome the marketplace needs, then send the success signal after that outcome is durable. Sending a heartbeat at process startup allows a worker that never commits results to appear healthy, and recording success before the last inventory transaction has the same weakness. During a rollback, an older worker may still be processing a batch; changing the flag does not undo records it already committed, and the responder needs to know whether that worker checks configuration between batches or only when it starts.

Count useful results.

For Node.js, retrieve the current configuration, preserve the fields required by the documented update contract, submit the intended value through set, and retrieve it again. Set creates or updates a flag; retrieve returns its details and configuration; toggle switches the enabled state.

A timeout is ambiguous. The server may have applied the change before the response was lost. Repeating a toggle can reverse the first change, so reconcile the current state with the intended value before proceeding, and serialize operator changes or use documented concurrency controls to prevent a stale read from becoming an unsafe write.

Buy the missing-result signal before building another dashboard

The buy-versus-build decision starts with the operational obligation. Feature management and scheduled-job monitoring solve different parts of this runbook.

Buy versus build option Useful role Boundary the platform team must own
Healthchecks Scheduled-job completion monitoring Define the deadline and send success after committed results; retain flag control elsewhere
LaunchDarkly Dedicated feature management Evaluate documented update behavior and client adoption against the rollback deadline
Unleash Feature management, including a self-host decision Assign deployment ownership and test the chosen client refresh behavior
Application-owned outcome checker Compare expected runs with durable import results Build and operate state, scheduling, notification delivery, and the responder runbook

For a broader monitoring decision, compare Datadog for an integrated observability service, Grafana for a dashboard and alerting approach around selected data sources, and Sentry for an error-focused investigation workflow. Their roles differ: a recorded exception can explain a failed import, while absence of an exception cannot establish that an expected import completed. Evaluate the notification path and the business completion condition separately from the investigation interface, and include operating responsibility in the self-host assessment.

Do not buy a graph as proof of completion.

Infrai provides a single key, a single bill, and a unified REST API for backend services. Its breadth fits this workflow: 295 routes across 20 modules share one API key, so adding an adjacent backend capability uses the same API contract rather than another SDK integration. No SDK required: plain HTTP works across languages and runtimes. Public discovery is self-describing and requires no key, so the platform team can review request and response schemas before implementing the rollback control path.

Prefer a dedicated feature-management option when the decision depends on its documented evaluation behavior and change controls. Prefer the broader API approach when adjacent backend integrations matter and the application already owns its completion monitor. The trade-off is operational ownership: a broad REST integration is not suitable as the sole evidence of import completion. Choose Healthchecks for the scheduled completion check, and retain a separate procedure for verifying worker adoption and committed results.

Keep the REST read small and the write procedure explicit

The following runnable Go program retrieves a flag for the pre-change or post-change check. Set INFRAI_BASE_URL to the provider's documented API origin, without a version suffix, and supply INFRAI_API_KEY and FLAG_KEY through the environment. The Node.js integration should use the same explicit method, status checks, and bounded retry policy; the example deliberately makes a read rather than guessing a write payload.

package main

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

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func run() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    flag := os.Getenv("FLAG_KEY")
    origin, err := url.Parse(base)
    if err != nil || origin.Scheme != "https" || origin.Host == "" ||
        origin.User != nil || origin.RawQuery != "" ||
        origin.Fragment != "" || origin.Path != "" {
        return fmt.Errorf("INFRAI_BASE_URL must be an HTTPS API origin")
    }
    if key == "" || flag == "" {
        return fmt.Errorf("INFRAI_API_KEY and FLAG_KEY are required")
    }
    endpoint := base + strings.Replace("/v1/flags/get/{key}", "{key}", url.PathEscape(flag), 1)
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    deadline := time.Now().Add(30 * time.Second)
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                if seconds > 30 {
                    return fmt.Errorf("Retry-After exceeds the retry budget")
                }
                if requested := time.Duration(seconds) * time.Second; requested > delay {
                    delay = requested
                }
            } else if date, err := http.ParseTime(retryAfter); err == nil {
                if requested := time.Until(date); requested > delay {
                    delay = requested
                }
            }
            if time.Now().Add(delay).After(deadline) {
                return fmt.Errorf("rate limited beyond the retry budget")
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("flag read returned %s: %s", resp.Status, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("retry attempts exhausted")
}
Enter fullscreen mode Exit fullscreen mode

This is a control-state check. It prints the response without inventing fields, limits response reading, and declines redirects so the credential remains at the configured origin. Configure that origin from trusted deployment configuration. Review response details in an authorized operational context.

Writes need an additional rule: where the selected operation supports an idempotency key, persist it with the logical change and reuse it for retries. Don't assume that every operation has the same deduplication semantics. Capture the previous intended configuration before changing it, and define a single writer during rollback.

Capacity planning belongs here too. In an illustrative polling design, 100 worker processes reading once every 30 seconds generate about 3.33 reads per second before retries. Synchronized refreshes create bursts; retries during a rollback add pressure. Stagger refreshes and bound retries.

Budget the lag.

Shorter polling intervals can improve adoption time while increasing request volume. A successful control-plane read does not establish when every worker has adopted the new configuration, so include worker refresh and in-flight batch duration in the rollback budget.

Verify the outcome and rehearse rollback

Before enabling the new importer, record the previous intended flag configuration and the worker release it controls. Define safe disabled behavior: finish the current batch, stop before the next batch, or defer a scheduled run. Pick one policy explicitly.

In a controlled test environment, exercise a successful import, a legitimate empty import, and a run that never records completion. The monitor should distinguish those cases using the agreed business rules. Then simulate an ambiguous control response and an overlapping operator change; verify reconciliation and writer coordination rather than merely checking that the HTTP client returned successfully.

Verify silence too.

For the illustrative 15-minute schedule and 5-minute allowance, inspect the missing-result notification after the deadline and confirm that it identifies the affected scheduled run. Intentional pauses need a documented maintenance policy; otherwise an expected rollback can train responders to ignore the alert they need on the next failure.

Rollback requires both kinds of evidence. Assign the recorded safe configuration, retrieve it to verify control state, and inspect worker adoption before resuming scheduled work. Assess already committed inventory updates separately. Close the incident against restored import results and the freshness SLO.

Choose assignment for rollback and a separate completion monitor for silence. Toggle belongs to a controlled inversion, with a known starting state and an execution policy that prevents repetition from becoming a second state change.

References

Top comments (0)