DEV Community

CaspianHayes3586
CaspianHayes3586

Posted on

Build Feature Flags Service in Node for Auditable Toggle Functionality

Short answer: a small feature-flag service is useful during a delivery incident only when every toggle decision can be tied to the notification attempt that followed it. Store a versioned flag record, evaluate it deterministically, and emit a structured decision event with the same trace and order identifiers as the delivery worker. That gives the person on call a timeline instead of a dashboard full of hopeful counters.

The service can still be simple. The discipline is the part that keeps it simple at 3am.

What did the page actually tell us?

Imagine an order-confirmation worker paging because the failure ratio crossed 4% in five minutes. The page says delivery_failed, region eu-west, and nothing about the release switch that routed traffic through the new provider adapter. The first question is not which chart is red. It is: which decision did this notification receive?

For each attempt, I want one reconstructable chain:

order_id -> notification_id -> flag evaluation -> adapter call -> provider response -> retry outcome

A flag read without that chain is configuration, not observability. The signal that should have fired earlier is a rising count of failures grouped by the flag version and adapter choice. Grouping only by endpoint hides a bad toggle inside healthy traffic.

The log record should carry stable fields rather than a sentence that a parser has to interpret later. OpenTelemetry's log model is a useful baseline: use a timestamp, severity, body, attributes, and trace context so logs can be correlated with spans. Keep the payload small enough that a retry does not create a second mystery.

A practical event looks like this:

type ToggleDecision struct {
    OrderID        string `json:"order_id"`
    NotificationID string `json:"notification_id"`
    Flag           string `json:"flag"`
    Enabled        bool   `json:"enabled"`
    Version        uint64 `json:"version"`
    Reason         string `json:"reason"`
    TraceID        string `json:"trace_id"`
}
Enter fullscreen mode Exit fullscreen mode

The reason field matters. default, tenant_rule, and percentage_bucket are different incident clues. Do not record message content, addresses, or payment data merely because the worker has them.

How can a Node feature flags service build safer toggle functionality?

Use a single evaluation path for reads from the worker and reads from a diagnostic tool. Given a flag key, tenant key, and a snapshot version, the result should be deterministic. A process restart must not move an order from disabled to enabled because a random number generator was reseeded.

Here is the core shape, with the storage and HTTP layer intentionally left out:

type Flag struct {
    Key       string
    Enabled   bool
    Version   uint64
    UpdatedBy string
}

func Evaluate(flag Flag, tenant string) (bool, string) {
    if tenant == "" {
        return false, "missing_tenant"
    }
    if !flag.Enabled {
        return false, "flag_disabled"
    }
    return true, "enabled_snapshot"
}
Enter fullscreen mode Exit fullscreen mode

The toggle endpoint should accept an expected version, then reject a stale write. That small compare-and-set rule prevents an operator with an old browser tab from undoing a newer rollback. A successful change creates a new version and an audit event; a failed change is also observable, because a rejected rollback is an incident detail.

This design has a limitation and a clear trade-off. A local in-memory flag cache is a poor fit when several regions must switch in the same second; choose a strongly consistent store or accept that propagation delay belongs in the incident model. The extra coordination costs latency and operational work, so a single-process service may be the better choice for a small shop.

I keep the default path closed for a delivery feature. If the flag store is unavailable, the worker uses a documented safe default and records flag_store_unavailable. The right default depends on the notification: sending a duplicate password reset is worse than delaying it, while delaying an order confirmation may be worse than sending through a conservative adapter. Write that decision down before the pager rings.

Where does the earlier signal come from?

Instrument the decision boundary, not just the final HTTP request. Emit a counter for evaluations by flag, version, enabled, and reason; a span around the adapter call; and a log event when the result changes. Sample successful traffic if volume requires it, but retain every error and every toggle mutation.

A useful alert is a change detector: compare delivery failures for the current flag version with the preceding version, split by region and notification type. A global failure percentage can stay below threshold while one tenant cohort loses every message. The alert should include the flag version and the last mutation timestamp, so the first screen already answers what changed.

Do not make the dashboard the source of truth. Dashboards aggregate; incident reconstruction needs the raw decision event and its trace ID. Keep retention long enough to cover the longest retry window plus the period in which customers report missing messages.

What does a small implementation need to prove?

Test the failure modes that operators will meet, not just the happy toggle. Run concurrent updates and verify stale versions fail. Replay the same tenant and flag inputs and verify the result is stable. Kill the flag store during a delivery attempt and check that the worker follows the documented default while emitting an event. Send a retry and confirm the notification ID and trace relationship remain visible.

Deployment needs one more guard: ship a flag as disabled, deploy the instrumented worker, verify decision events, then enable a narrow cohort. If the first page fires, rollback is a versioned write with an audit trail, not a manual edit in a database console.

The false-positive cost is real. If a noisy threshold pages on every transient provider timeout, people learn to mute it; the next page about a bad toggle arrives to an empty channel. Set thresholds from the retry and customer-impact policy, and review them after an incident with the raw events in hand.

A feature flag is therefore a control surface for delivery behavior, and its useful unit is the auditable decision. When an order-confirmation failure wakes you, the system should tell you which switch fired, for which order, at which version, and what happened next. That is enough context to reverse a change safely without turning the incident into archaeology.

The implementation language is a detail: Node workers can call the same evaluation contract, and the functionality still depends on version checks and decision events rather than framework magic. Build the smallest path that preserves those facts.

Further reading

Top comments (0)