Skip to content

Feature Flags ​

Introduction ​

A feature flag lets you ship code that is switched off, then turn it on for some people and not others. You can release a redesigned checkout to your own team first, open a beta to twenty percent of users, or run an experiment that shows three different button colours. @plinthjs/feature-flags gives you a FeatureManager where you define each feature once, as a function, and ask whether it is active for a given scope. A scope is whatever the feature depends on: a user, a team, a request, or nothing at all.

bash
pnpm add @plinthjs/feature-flags

Resolved values are remembered per feature and scope, so each resolver runs at most once for each scope. The manager keeps everything in memory in the current process, and it never reads the clock.

Defining features ​

Register a feature with define(name, resolver). The resolver receives the scope and returns the feature's value. It may be sync or async.

ts
import { FeatureManager } from '@plinthjs/feature-flags'

const feature = new FeatureManager()

feature.define('new-api', (user) => (user as { id: number }).id % 2 === 0)
feature.define('maintenance-banner', () => false)

define returns the manager, so you can chain definitions. A good place to put them is a service provider or your application's start-up code, so every feature is registered before the first request.

Checking features ​

active resolves to a boolean, and inactive is its opposite. All the check methods return promises, because resolvers may be async.

ts
const alice = { id: 2 }

await feature.active('new-api', alice) // => true
await feature.inactive('new-api', { id: 1 }) // => true
await feature.active('maintenance-banner') // => false

A feature that was never defined is inactive. It does not throw.

ts
await feature.active('no-such-feature') // => false
feature.defined('new-api') // => true
feature.definedFeatures() // => ['new-api', 'maintenance-banner']

To check several features at once:

ts
await feature.allAreActive(['new-api', 'beta'], alice) // every one is active
await feature.someAreActive(['new-api', 'beta'], alice) // at least one is active

Scopes ​

The scope is the second argument. It decides which cached value you get, so new-api can be on for one user and off for another. Calls without a scope use the shared "global" scope.

To stop repeating the scope, bind it once with for(). The returned object offers the same methods without the scope argument.

ts
const forAlice = feature.for(alice)

await forAlice.active('new-api') // => true
await forAlice.inactive('beta')
await forAlice.values() // => { 'new-api': true, ... }

If most of your checks are about the current user, set a default scope resolver. It is used whenever you do not pass a scope.

ts
feature.resolveScopeUsing(() => currentUser())

await feature.active('new-api') // resolved for currentUser()

Pass undefined to resolveScopeUsing to remove the default.

How scopes are identified ​

The cache needs a string key for each scope. The default serializer builds it like this:

ScopeKey
undefined or nullthe shared global scope
a string, number, boolean or bigintthe type and value
an object with a featureScopeIdentifier() methodthe method's result
an object with a featureScopeId or id propertythat identifier
anything elseits JSON.stringify

Objects with the same id are the same scope, even if they are different instances. If your scopes do not fit these rules, supply your own function:

ts
const feature = new FeatureManager({
  serializer: (scope) => `team:${(scope as { team: { slug: string } }).team.slug}`,
})

WARNING

Two scopes that serialize to the same key share one cached value. If your scope objects have an id that is only unique per type (a user with id 1 and a team with id 1), give them a featureScopeId that includes the type, or use a custom serializer.

Rich values ​

A feature does not have to be a boolean. Whatever the resolver returns is the feature's value, and value() gives it to you as is. active() simply asks whether that value is truthy.

ts
feature.define('checkout-button', () => 'green')
feature.define('plan', async (account) => ({ tier: 'pro', seats: 10 }))

await feature.value('checkout-button', alice) // => 'green'
await feature.active('checkout-button', alice) // => true
await feature.value('plan') // => { tier: 'pro', seats: 10 }

To read several features at once, use values(), which resolves every defined feature for a scope:

ts
await feature.values(alice) // => { 'new-api': true, 'checkout-button': 'green', ... }

Caching and overriding ​

Once a value is resolved for a scope it is stored, so a resolver that does expensive work (a database query, say) runs once per scope no matter how often you check.

ts
let calls = 0
feature.define('expensive', () => ++calls > 0)

await feature.active('expensive', alice)
await feature.active('expensive', alice)
// calls => 1

You can overwrite a stored value yourself. This is how you force a feature on or off for one scope regardless of what the resolver says, for example from an admin screen or in a test.

ts
feature.activate('new-api', { id: 1 }) // force on
feature.deactivate('new-api', alice) // force off
feature.activate('checkout-button', alice, 'blue') // force a specific value

await feature.value('checkout-button', alice) // => 'blue'

To drop an override or a cached value so the resolver runs again on the next check:

ts
feature.forget('new-api', alice) // one scope of one feature
feature.forgetAll('new-api') // every scope of one feature
feature.purge(['new-api', 'beta']) // several features (with no argument: everything)
feature.flushCache() // everything

To recompute values right now instead of waiting for the next check, use load (always re-runs the resolvers) and loadMissing (only runs those not yet resolved). Both resolve to a record of values, and both take an optional list of names and a scope.

ts
await feature.load(['new-api'], alice) // => { 'new-api': true }
await feature.loadMissing(undefined, alice) // every defined feature, cached ones reused

INFO

Overrides live in the manager's memory only. They are lost when the process restarts, and are not shared between processes. If you need flags that persist, store the decision in your database and read it from inside the resolver.

Percentage rollouts ​

To release a feature to a share of your users, use Chance. It decides from a seed string, so the same seed always gets the same answer. A user who is in the rollout stays in it, and raising the percentage only adds people.

ts
import { FeatureManager, Chance } from '@plinthjs/feature-flags'

const feature = new FeatureManager()

feature.define('beta', (user) => Chance.odds(20).wins(`beta:${(user as { id: number }).id}`))

Chance.odds(wins, outOf = 100) means "wins out of outOf", so Chance.odds(20) is twenty percent and Chance.odds(1, 1000) is one in a thousand. Chance.chance(0.2) takes a probability between 0 and 1. Invalid values throw a RangeError.

ts
Chance.odds(20).wins('beta:7') // => false (the same every time for this seed)
Chance.chance(0.5).loses('beta:7') // => true (the opposite of wins)

Include the feature name in the seed, as above. Otherwise the same users would land in every rollout you run, which skews experiments.

Over a thousand users, Chance.odds(20) lands very close to twenty percent in practice:

ts
let on = 0
for (let id = 0; id < 1000; id++) {
  if (await feature.active('beta', { id })) on++
}
// on => 203

If you need the raw number, seedFraction(seed) returns a stable value in the range from 0 up to (but not including) 1 for any string.

Variants for experiments ​

variant(values, seed, weights?) picks one of several values deterministically from a seed. With no weights, each value is equally likely.

ts
import { variant } from '@plinthjs/feature-flags'

feature.define('checkout-button', (user) =>
  variant(['green', 'blue', 'red'], `checkout-button:${(user as { id: number }).id}`),
)

await feature.value('checkout-button', { id: 1 }) // => 'red'
await feature.value('checkout-button', { id: 1 }) // => 'red' (always)

Pass weights to skew the split. They must be non-negative, add up to more than zero, and have the same length as the values.

ts
variant(['control', 'new'], `onboarding:${userId}`, [90, 10]) // about 90% control, 10% new

variant throws a RangeError for an empty list, a weights list of the wrong length, negative weights, or weights that sum to zero.

Testing ​

Because resolvers are plain functions and overrides are first-class, tests are simple. Define the feature with the behaviour you need, or force a value.

ts
const feature = new FeatureManager()
feature.define('new-api', () => false)

feature.activate('new-api') // global scope, forced on
await feature.active('new-api') // => true

feature.flushCache() // start the next test clean

Nothing depends on the clock, so results are repeatable. Build a fresh FeatureManager per test, or call flushCache() between tests.

Released under the MIT License.