← Back to JavaScript, page 10

javascript-0187 · Hard senior

How would you design a client-side feature flag library with percentage rollouts, fast startup, and safe defaults?

Evaluate flags locally from a cached rules payload so reads are synchronous and fast. Give each flag a default, bucket users with a stable hash of flag key and user id for percentage rollouts, bootstrap from storage or server-rendered data, refresh in the background, and log exposure once. Keep a kill switch path, and never block rendering on the network.

Full answer

Requirements to ask about: how fast flags must be available, how often they change, who targets them (users, groups, percentages), whether results must be consistent across devices, and whether experiments need exposure data.

Design:

  1. Flag definition: { key, enabled, rules: [{ attribute, op, values, serve }], rollout: { percent }, variants, version }, delivered as one JSON payload per environment, ideally with an ETag so refreshes are cheap.
  2. Evaluation on the client: isEnabled(key, context) is synchronous and pure. It checks the kill switch (enabled: false), explicit targeting rules, then the percentage rollout, and falls back to the default given in code. Unknown flags return the default and report a warning.
  3. Stable bucketing: hash flagKey + ':' + userId with a fast, well-spread hash (FNV-1a or murmur), map to 0 to 9999, and compare to percent * 100. Salting with the flag key means a user is not always in the first 10% of every flag. The same user always gets the same answer, and raising from 10% to 20% keeps the first 10% enabled.
  4. Anonymous users: use a stable random id stored in a first-party cookie or storage. State clearly that a cleared storage means a new bucket.
  5. Startup: render with bootstrap values from the server response (inline JSON) or the last payload in localStorage, then fetch fresh rules in the background. Do not block first paint, and avoid flicker by applying flag changes at the next navigation or only when the value affects non-visible logic, unless the product accepts live updates.
  6. Updates: poll with ETag, or use server-sent events or WebSocket for fast kill switches. Notify subscribers only when an evaluated value changes.
  7. Exposure logging: record "user saw variant X" once per flag, user, and session, when the flag is actually evaluated for a decision, and send it through the analytics batcher.
  8. Safety: defaults in code for each flag, a timeout for the fetch, try/catch around evaluation, and a global override for testing (query parameter or local storage, allowed only in non-production or for signed-in staff).
  9. Security and privacy: client flags are visible to users, so never put secrets, private targeting lists, or paid-feature enforcement only in client flags. Enforce important rules on the server.
  10. Hygiene: owners, expiry dates, and removal of old flags, because long-lived flags multiply the testing matrix.

Trade-offs: local evaluation is fast but exposes rules, while server evaluation hides rules and adds latency. Many products use server evaluation for sensitive flags and local evaluation for UI flags.

javascript
function fnv1a(text) {
  let hash = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) {
    hash ^= text.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193);
  }
  return hash >>> 0;
}
const bucket = (flagKey, userId) => fnv1a(`${flagKey}:${userId}`) % 10000;

function createFlags({ rules, defaults = {}, onExposure = () => {} }) {
  const seen = new Set();
  const listeners = [];
  let current = rules;
  const evaluate = (key, ctx = {}) => {
    const flag = current[key];
    if (!flag) return defaults[key] ?? false;
    if (!flag.enabled) return false;
    for (const rule of flag.rules ?? []) {
      if (rule.values.includes(ctx[rule.attribute])) return rule.serve;
    }
    if (flag.percent == null) return true;
    return bucket(key, ctx.userId) < flag.percent * 100;
  };
  return {
    isEnabled(key, ctx) {
      let value;
      try {
        value = evaluate(key, ctx);
      } catch {
        value = defaults[key] ?? false;
      }
      const exposureKey = `${key}:${ctx?.userId}`;
      if (!seen.has(exposureKey)) {
        seen.add(exposureKey);
        onExposure({ key, user: ctx?.userId, value });
      }
      return value;
    },
    update(next) {
      const before = Object.keys(next).filter((k) => JSON.stringify(current[k]) !== JSON.stringify(next[k]));
      current = next;
      listeners.forEach((fn) => fn(before));
    },
    subscribe: (fn) => listeners.push(fn),
  };
}

const rules = {
  'new-checkout': { enabled: true, percent: 20, rules: [{ attribute: 'role', values: ['staff'], serve: true }, { attribute: 'country', values: ['XX'], serve: false }] },
  'dark-mode': { enabled: true },
  'old-banner': { enabled: false },
};
const exposures = [];
const flags = createFlags({ rules, defaults: { 'unknown-flag': false }, onExposure: (e) => exposures.push(e) });

const users = Array.from({ length: 20000 }, (_, i) => 'user-' + i);
const on20 = users.filter((id) => flags.isEnabled('new-checkout', { userId: id }));
console.log('20% rollout enabled for', (on20.length / users.length * 100).toFixed(1) + '% of 20000 users');

console.log('sticky:', flags.isEnabled('new-checkout', { userId: 'user-7' }) === flags.isEnabled('new-checkout', { userId: 'user-7' }));
console.log('staff rule beats the percentage:', flags.isEnabled('new-checkout', { userId: 'user-1', role: 'staff' }));
console.log('country rule turns it off:', flags.isEnabled('new-checkout', { userId: 'user-staff-like', role: 'x', country: 'XX' }));
console.log('plain flag, disabled flag, unknown flag:', flags.isEnabled('dark-mode', { userId: 'a' }), flags.isEnabled('old-banner', { userId: 'a' }), flags.isEnabled('unknown-flag', { userId: 'a' }));
console.log('exposure events logged once per user and flag:', exposures.length);

const rulesAt40 = { ...rules, 'new-checkout': { ...rules['new-checkout'], percent: 40 } };
const flags40 = createFlags({ rules: rulesAt40 });
const stillOn = on20.filter((id) => flags40.isEnabled('new-checkout', { userId: id }));
console.log('raising to 40% keeps every user from 20%:', stillOn.length === on20.length);

const otherFlag = users.filter((id) => bucket('other-flag', id) < 2000);
const overlap = on20.filter((id) => otherFlag.includes(id)).length;
console.log('overlap with another 20% flag is about 4%, got', (overlap / users.length * 100).toFixed(1) + '%');

flags.subscribe((changed) => console.log('changed flags:', changed));
flags.update({ ...rules, 'dark-mode': { enabled: false } });

Run with Node.js v24.22.1 as js-187.js; two runs gave identical output. Output: 20% rollout enabled for 20.0% of 20000 users sticky: true staff rule beats the percentage: true country rule turns it off: false plain flag, disabled flag, unknown flag: true false false exposure events logged once per user and flag: 20004 raising to 40% keeps every user from 20%: true overlap with another 20% flag is about 4%, got 3.8% changed flags: [ 'dark-mode' ]

Key points

  • Synchronous local evaluation from a cached rules payload, with in-code defaults.
  • Stable hash of flag key and user id gives sticky, monotonic percentage rollouts.
  • Bootstrap from the server or storage; refresh in the background; avoid blocking render.
  • Log exposure once per decision; use polling or streaming for kill switches.
  • Client flags are not secret; enforce important rules on the server and remove old flags.

Common mistakes

  • Using Math.random for rollouts, which gives users a different answer each visit.
  • Using the same hash input for every flag, so the same users are always first.
  • Blocking first paint on a flag request.
  • Treating client-side flags as a place for secrets or access control.

Follow-ups

  • How would you run an A/B experiment with this client?
  • How do you retire a flag safely?
  • Why not evaluate every flag on the server?

Tips

  • Explain stable bucketing and why the flag key is part of the hash.
  • Mention defaults and a kill switch as the safety story.
  • Say plainly that client flags are visible to users.