Tutorial

How to Build a Feature Flag Service

Design an in-process feature flag service with rules, gradual rollouts, and safe overrides that degrade gracefully when the flag store is unavailable.

On this page

  1. Introduction
  2. The problem
  3. Design decisions
  4. Implementation
  5. Testing the boundary
  6. Common pitfalls
  7. Operational considerations
  8. Conclusion

Introduction

Feature flags decouple deploy from release. Instead of shipping a feature and hoping it works, you ship it behind a flag and turn it on for a subset of users. A good flag service is more than a boolean map: it evaluates rules, supports gradual rollouts, and degrades gracefully when the flag store is unavailable. This guide builds an in-process flag service that handles all three concerns without an external dependency.

The problem

The naive approach is a config file with boolean values. That works for permanent flags but fails for rollouts: you cannot turn a flag on for ten percent of users without code changes. It also fails for safety: if the config source is unavailable, every flag defaults to false and you lose features in production. A real flag service needs rules, a rollout gate, and a fallback strategy.

Design decisions

The flag model has a key, an enabled state, an optional list of rules, and a rollout percentage. Rules are predicates over a context object, such as user ID, tenant, or region. The rollout gate uses a deterministic hash of the flag key and user ID to decide whether a user is in the rollout bucket, so the same user always sees the same result. The service caches flags locally and refreshes on a timer, with a fallback to the last known state on error.

class FeatureFlags {
  flags = new Map();
  eval(key, ctx = {}) {
    const flag = this.flags.get(key);
    if (!flag) return false;
    if (!flag.enabled) return false;
    if (flag.rules && !flag.rules.every(r => r(ctx))) return false;
    if (flag.rollout < 100) {
      const hash = simpleHash(key + ctx.userId);
      if (hash % 100 >= flag.rollout) return false;
    }
    return true;
  }
}

Implementation

The service loads flags from a store on startup and refreshes on an interval. The store can be a file, a database, or an API; the service treats it as a source of truth with a local cache. On refresh failure, it logs and keeps the last cache rather than clearing flags, so a store outage does not disable features. The evaluation is synchronous and fast, suitable for the request path.

async refresh() {
  try {
    const fresh = await this.store.getAll();
    this.flags = new Map(Object.entries(fresh));
  } catch (e) {
    console.error('flag refresh failed, keeping cache', e);
  }
}

Testing the boundary

Test the rollout boundary: with a fifty percent rollout, roughly half of a thousand user IDs evaluate true, and the same user always gets the same result across calls. Test rule evaluation: a flag with a rule that checks the user region only enables for matching contexts. Test the fallback: if the store throws, the service keeps the previous flags and does not reset to empty.

Common pitfalls

Avoid non-deterministic rollout gates like Math.random, which cause flicker and break analytics. Avoid synchronous store calls in the request path; refresh on a timer instead. Avoid flag sprawl: archive flags after rollout completes, or the config grows unmanageable. Avoid client-side evaluation for security-sensitive flags, since the rules are visible in the bundle.

Operational considerations

Store flags in a database or config service and cache them in-process with a short TTL of 15 to 60 seconds, so flag evaluations stay local and do not add a network hop to the hot path. The cache refresh should be a background tick, not a read-through on every evaluation, so a slow config service never stalls a request. On startup, block briefly to load the first flag snapshot; after that, never block on the store. If the store is unreachable, keep serving the last cached snapshot and emit an alert, rather than failing open or closed by default.

For gradual rollouts, use a stable hash of a user identifier modulo 100, compared against the rollout percentage. A stable hash means the same user always gets the same value within a flag version, so a user who sees the new path does not flip back. When you change the percentage, some users cross the boundary; that is expected. Never use Math.random for rollout decisions, because it flips every evaluation and breaks user session consistency. Document which identifier is hashed, because changing it reshuffles every user.

Local overrides are useful for debugging and QA: a developer sets a flag to a specific value in their environment without touching the shared store. Keep overrides in a separate layer that takes precedence over the cached snapshot, and never persist overrides to the store. In production, overrides should be off by default and enabled only through a feature-gated admin path, so an accidental override does not change behavior for real users.

Track each flag’s evaluation count and the true-to-false ratio over time. A flag that evaluates true for 100% of traffic for weeks is a candidate for removal, because the code path is now permanent and the flag only adds evaluation overhead. A flag that never moves from its default may be dead configuration. Tie flag lifecycle to ownership: every flag has a team and an expected end date, and stale flags surface in a weekly report so they get cleaned up rather than accumulating as permanent indirection.

Conclusion

A feature flag service needs a model, a deterministic rollout gate, a refresh mechanism with fallback, and tests for the boundary. Ship it behind a simple API, keep the evaluation fast, and archive flags when the rollout is complete. The result is a service that lets you decouple deploy from release without trading away safety. When a flag is ready to retire, remove both the flag and the dead code branch it gated in the same change, so the flag does not outlive the feature it was protecting.

Sources: Feature Toggles, LaunchDarkly best practices.

FAQ

Should flags be evaluated server-side or client-side?
Server-side evaluation keeps rules private and avoids client drift; client-side is fine for UI-only flags with a minimal payload.
How do I handle a flag store outage?
Fall back to the last cached state or a safe default; never block the request path on the flag service.
What rollout granularity should I use?
Start with boolean on/off, then add percentage rollout keyed by user ID for gradual exposure; segment rules come last.

Related Examples