Flag cache

A short-lived cache in front of a flag provider, keyed by the evaluation context the decision was made against.

b.flag.cache(downstream, opts?) #

stable0.7.111
{
  ttlMs:      number,    // entry lifetime, at least 1000; default 30000
  maxEntries: number,    // ceiling on entries held; default 10000
  audit:      boolean,   // emit flag.cache.bust through b.audit
}

Wrap a flag provider in a TTL cache. Returns a provider of the same shape, { kind, list, evaluate, bust, stats }, so it goes wherever the wrapped one went.

The cache key is the flag key, the context's targetingKey, and a SHA3-512 digest of the whole evaluation context. A targeting rule reads any path through that context, so every field it could decide on is part of the key and one principal's decision is never answered for another's context. The digest keeps the key a fixed length, since a context carries values a client chooses, such as the agent string. A context that cannot be canonicalized, and one carrying no targetingKey, are passed straight to the wrapped provider rather than cached.

A flag_not_found result is not stored. bust() clears every entry and answers how many it held. Entries expire on read, the oldest is dropped when maxEntries is reached, and expired ones are swept every hundredth miss.

var b = require("blamejs");
var provider = b.flag.providers.memory({
  flags: { beta: { default: "off", variants: { on: true, off: false } } },
});
var cached = b.flag.cache(provider, { ttlMs: b.constants.TIME.seconds(5) });
cached.evaluate("beta", { targetingKey: "alice" });
cached.evaluate("beta", { targetingKey: "alice" });
cached.stats().hits;   // → 1
cached.kind;           // → "cache:memory"

Last updated 2026-10-12T14:21:56.879Z by seeder.