← 中文资源

简体中文版本

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.

阅读英文原文

引言

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 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. 理解问题的全貌是设计正确方案的前提。

设计决策

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;
  }
}

实现

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);
  }
}

测试边界

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. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。

常见陷阱

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. 避开这些陷阱可以减少生产事故。

结论

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. 按照本文的方法,你可以构建出既安全又高效的解决方案。

Sources: Feature Toggles, LaunchDarkly best practices.