Ten calls to one: rebuilding feature flags from the inside
A request that checked ten feature flags could make ten API calls. We got that down to one by evaluating the flags in the app.
Feature flags control much of what our platform does. As traffic grew, the API calls we made to check those flags became a bottleneck.
When we checked ten flags in sequence over HTTP, a 30 ms check added up to about 300 ms on a single request. The delay got worse under load.
§Why we could evaluate flags locally
We looked at how the app used the flags and found that it could safely evaluate the rules itself.
Our traces showed how many times each request called the flag provider.
We fetch the rules at startup, inject them into the dependency container, and evaluate flags in the same process as the app. The rules refresh on a schedule, and the evaluator has a fallback.1
§What the fix looked like
Here is a simplified version of the evaluator.
// One call at boot, refreshed on a timer.
const rules = await client.fetchRules({ env, project });
function isOn(name, ctx) {
const rule = rules[name];
if (!rule) return false;
return evaluate(rule, ctx); // pure, in-process
}
Each check uses rules already in memory. We spent most of the project verifying that local and remote checks behaved the same way and writing tests for regressions that could otherwise go unnoticed.
§How we checked it before rollout
Before we rolled it out, we wanted to see whether the two evaluators agreed on live traffic.
- We compared local and remote decisions on a sample of live traffic and sent an alert when they disagreed.
- We rolled it out one flag at a time, behind its own flag. Yes, feature-flagged feature flags.
- We wrote a migration log that explains the decisions for teammates who join later.
The code change was small. Most of the work went into checking how it would behave in production.2
§What I took from it
I now ask whether an API call has to happen on every request. Removing one from a step that runs several times can save more time than making the API a little faster.
I also make more time for dashboards, migration notes, and talking to the people affected before I open the PR.
Architecture is mostly the choice of where to put the seams. Everything else is taste.
If flag checks run on every request, measure what they cost and check whether the app can evaluate the rules locally.