Feature Flags & Gradual Rollouts — DevOps

A feature flag is a switch inside the code that separates deploy (the code reaches the server) from release (users can use the feature). So a feature can be…

The PDF export is deployed on Monday morning. By ten, reports come in: every time someone presses the PDF button, the server gets so slow that it almost stops. A rollback means waiting minutes for the pipeline to run again, and meanwhile everyone using the app has the problem.

With a feature flag, one switch is enough. A feature flag is a switch inside the code that decides whether a feature is on, and for whom, without a new deploy. Picture the wiring in a new house. The electrician has laid the cables and put lights in every room (that's the deploy), but a light only comes on when you press its switch (that's the release). You can switch on one room first to try it. And if there's a short circuit, you switch off the circuit breaker (the main safety switch): the power goes off at once, without removing any cable (the breaker is the kill switch). In the code, the cables and lights are the feature's code on the server, a switch is a flag, and one room is some of the people using the app.

Deploy is not release

In the What is CI/CD and Deployment Strategies lessons, notes-api's new code reached web-1 through the pipeline. That's a deploy: the code is on the server. A release is when people can actually use the feature. A feature flag separates those two moments.

The notes-api team builds a new feature: exporting a note as a PDF. The code is deployed on Monday, but hidden behind a flag called pdf-export. Here is the endpoint (the code that answers requests to /notes/:id/pdf):

app.get("/notes/:id/pdf", (req, res) => {
  if (!evaluateFlag(flags["pdf-export"], req.user)) {
    return res.status(404).json({ error: "Feature not available yet" });
  }
  // ... build the PDF from the note
});

Four rules, checked in order

One flag in notes-api looks like this:

const flag = {
  enabled: true,        // the main switch, a.k.a. the kill switch
  percentage: 25,       // what percentage of users get it, 0 to 100
  allowlist: ["dewi"],  // always get it: dewi is the in-house tester
  blocklist: ["bayu"],  // never get it: bayu's PDF crashed once
};

The evaluator (the evaluateFlag function) checks its rules one at a time, in this order. The first rule that matches decides the answer:

  1. enabled is false (the kill switch is off)? The answer is false for everyone, dewi included.
  2. user.id is in the blocklist? false.
  3. user.id is in the allowlist? true.
  4. Percentage: 100 or more means true, 0 or less means false. Otherwise the answer is true when the user's bucket (a fixed number from 0 to 99, see the next section) is smaller than the percentage.

For the flag above (percentage: 25), the results are:

User Bucket Rule that decides Result
dewi 55 3. allowlist true
bayu 3 2. blocklist (even though 3 < 25) false
sari 21 4. 21 < 25 true
budi 60 4. 60 is not < 25 false

The order matters. If the allowlist were checked before enabled, the kill switch couldn't turn the feature off for dewi, because the allowlist would already have answered true.

Bucket: a fixed number for every user

Why not just Math.random() * 100 < 25? Math.random() gives a new random number every time it is called, so the draw is repeated on every request: sari sees the PDF button, refreshes, it's gone, refreshes again, it's back. What you need is a number that is always the same for the same user. To get it, compute a hash of user.id. A hash is a number calculated from text, and the same text always gives the same number. Here the hash is always 0 to 99, and that number is called the bucket.

The formula: start at hash = 0, then for every character, hash = (hash * 31 + character code) % 100. The character code (each letter's number) comes from charCodeAt(0). % gives the remainder of a division, so 562 % 100 is 62. For "sari":

Character Code Calculation Hash
s 115 (0 × 31 + 115) % 100 15
a 97 (15 × 31 + 97) % 100 = 562 % 100 62
r 114 (62 × 31 + 114) % 100 = 2036 % 100 36
i 105 (36 × 31 + 105) % 100 = 1221 % 100 21

Sari's bucket is 21. At 25%, 21 < 25, so sari gets it. Raised to 50%, 21 < 50, so sari keeps it. Her bucket doesn't change, only the limit does. Going from 25 to 50 only adds the users with buckets 25 to 49. Raising the percentage never takes the feature away from a user who has it.

Why multiply by 31 instead of just adding? If you add the character codes, "ab" and "ba" get the same bucket (97 + 98). With the multiplication, the order of the letters changes the result too.

The complete evaluator

Here is the whole evaluateFlag function, with two example calls below it:

function evaluateFlag(flag, user) {
  if (!flag.enabled) return false;                    // 1. kill switch
  if (flag.blocklist.includes(user.id)) return false; // 2. blocklist
  if (flag.allowlist.includes(user.id)) return true;  // 3. allowlist
  if (flag.percentage >= 100) return true;            // 4. percentage
  if (flag.percentage <= 0) return false;

  let hash = 0;
  for (const char of user.id) {
    hash = (hash * 31 + char.charCodeAt(0)) % 100;
  }
  return hash < flag.percentage;
}

const flag = { enabled: true, percentage: 25, allowlist: ["dewi"], blocklist: ["bayu"] };
console.log(evaluateFlag(flag, { id: "sari", plan: "free" })); // true
console.log(evaluateFlag(flag, { id: "budi", plan: "pro" }));  // false

Raising a rollout safely

notes-api's gradual rollout: dewi first through the allowlist, then 5%, 25%, 50% and 100%. At every stage, watch the PDF endpoint's error rate. With the Lab's 20 users:

Stage Users who get it PDF errors
0% 1 (dewi, through the allowlist) 0%
25% 5 (intan, tari, reza, sari, plus dewi) 0%
50% 10 (joko joins) 10%

At 50%, joko's PDFs crash on his big attachments, just like bayu's did, and the error rate jumps to 10%. Turn off the kill switch: set enabled: false. Within seconds nobody calls the PDF code any more, and the team can find the bug calmly.

Real flag services also have target rules based on the user's attributes (data), for example "users on the pro plan always get it" or "only users in Germany". The idea is the same: rules are checked in order, and the percentage is checked last.

Flag debt: cleaning up flags

Once PDF export has run at 100% for two weeks without trouble, the pdf-export flag has no purpose left. If you leave it, the code fills with ifs for flags that are always true. The flag combinations to test also grow very fast: 10 flags mean 2 to the power of 10 = 1,024 on/off combinations. This problem is called flag debt, the main risk of feature flags that aren't managed. Remove the if and the flag, like cleaning up dead code (code that never runs any more).

💡 Kinds of flags

Give temporary flags an expiry date and a cleanup ticket (a task in the team's work list) on the day they're created.

⚠️ Flags that miscount or pile up

TL;DR: A feature flag is a switch inside the code that separates deploy (the code reaches the server) from release (users can use the feature). So a feature can be switched on gradually and off within seconds without a rollback. The evaluator (the function that decides) checks rules in order. enabled false (the kill switch is off) means false for everyone. Then the blocklist (users who never get it) answers false, and the allowlist (users who always get it) answers true. Last comes the percentage: >= 100 is true, <= 0 is false, otherwise bucket < percentage. The bucket is a number from 0 to 99 calculated from a hash of user.id (hash = (hash * 31 + character code) % 100). The same text always gives the same hash. So the same user always gets the same answer, and raising the percentage never takes the feature away from anyone who has it. Remove temporary flags after 100% so they don't become flag debt (old flags that pile up in the code).

⚡ Deploy is not release

Write:

app.get("/notes/:id/pdf", (req, res) => {
  if (!evaluateFlag(flags["pdf-export"], req.user)) {
    return res.status(404).json({ error: "Feature not available yet" });
  }
  // ... build the PDF from the note
});

Meaning: A feature flag is a switch inside the code that decides whether a feature is on, and for whom. Here evaluateFlag checks the pdf-export flag for the user (a person using the app) who asks for the PDF. When the flag is off, the code answers 404 (not found). The code is already on the server (deploy), but users can only use it once the flag is on (release). The flag's value lives outside the code, so changing it needs no deploy.

⚡ Four rules, checked in order

Write:

if (!flag.enabled) return false;
if (flag.blocklist.includes(user.id)) return false;
if (flag.allowlist.includes(user.id)) return true;
Guess first: when the kill switch is off (enabled: false), the feature is off for every user. dewi is on the allowlist (the users who always get it). If the allowlist were checked before enabled, what would break?

The kill switch couldn't turn the feature off for dewi, because the allowlist would already have answered true. The first rule that matches decides, so enabled must be at the top.

Meaning: The blocklist lists the users who never get it, and is checked before the allowlist. Only after those three rules comes the percentage (the share of users who get it): >= 100 is true, <= 0 is false, otherwise the user's bucket (a fixed number from 0 to 99) is compared with the percentage.

⚡ A fixed bucket for every user

Write:

let hash = 0;
for (const char of user.id) {
  hash = (hash * 31 + char.charCodeAt(0)) % 100;
}
return hash < flag.percentage;

Meaning: If the bucket came from Math.random() (a random number), it would change on every request, so the feature appears and disappears in turns. A hash (a number calculated from text) of user.id is always the same for the same id. % 100 (the remainder after dividing by 100) keeps it between 0 and 99, and that number is called the bucket. A user gets the feature when their bucket is under the percentage. Sari's bucket is 21, so when the percentage goes from 25% to 50%, she keeps it.

⚡ Switch it off within seconds

Meaning: The percentage is raised step by step. At 50%, the PDF error rate (the percentage of PDF requests that fail) jumps to 10%. Turn off the kill switch (set enabled: false), and within seconds nobody calls the PDF code any more, with no rollback. Once the feature is safe at 100%, remove the if that checks the flag, and the flag, so they don't become flag debt (old flags that pile up in the code).

What you will learn