Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Feature Flags and Config

Module 8 Lesson 8.c 50 min Difficulty 3/5

Prerequisites 8.a, 8.b

The idea in one minute#

A feature flag lets you turn behaviour on or off — for everyone, for a percentage of users, for one customer — without deploying. Flags make releases safer (ship dark, roll out gradually, turn off instantly) and are one of the best mitigations there is.

But flags and configuration are changes too, and they are often more dangerous than code: they skip the build, the tests and the canary, and they reach every server in seconds. Many of the largest outages of the last decade were configuration pushes. The rule: treat config and flag changes exactly like code changes — reviewed, validated, versioned, rolled out progressively, with automatic rollback.

An analogy#

A theatre’s lighting desk. Lights can be changed instantly during a show without rebuilding the set — that is the point. But a lighting operator who pushes a new cue to every light in the building at once, untested, can black out the whole theatre mid-performance.

A picture#

flowchart LR
  E[":i-user: Engineer"] --> PR[":github: <b>Config PR</b><br/><small>review</small>"]
  PR --> V[":i-check: <b>Validate</b><br/><small>schema, semantics,<br/>start a real process with it</small>"]
  V --> ST["Staged push<br/><small>canary cell → 1 zone → region → all</small>"]
  ST --> W[":prometheus: <b>Watch</b><br/><small>SLIs per stage</small>"]
  W -->|"bad"| RB["Automatic revert<br/><small>to last known good</small>"]
  W -->|"good"| ST
  class E neutral
  class PR,V compute
  class ST queue
  class W memory
  class RB warn

How it really works#

Kinds of flag#

KindLifetimeExample
Release flagDays–weeks; removed after full rolloutcheckout-v2-ui
Experiment flagWeeks; A/B testranking-model-b
Ops flag / kill switchPermanentdisable-recommendations, read-only-mode, static-mode
Permission flagPermanententerprise-sso-enabled per customer

Kill switches are reliability features. Every expensive or risky non-essential feature should have one, documented in the runbook (4.b) and tested.

Percentage rollouts must be sticky#

Roll out by hashing a stable key (user ID, account ID) into a bucket from 0–99, and enabling the flag for buckets below the percentage. Each user then gets a consistent experience as the percentage grows, and you can compare enabled and disabled users fairly. Hash with the flag’s name as salt so different flags do not always pick the same users.

Flag hygiene#

  • Owner and expiry on every release flag; a CI check or report for flags past expiry.
  • Remove dead flags: each one doubles the code paths someone must reason about. Knight Capital lost $440 million in 45 minutes in 2012 partly because a repurposed old flag reactivated dead code on one server that had not been updated.
  • Audit log of every flag change, in the shared change log (4.c).
  • Defaults that are safe when the flag service is unreachable: the SDK must fall back to a built-in default, never block requests.
  • OpenFeature (a CNCF project) is a vendor-neutral flag API with providers for LaunchDarkly, Flagsmith, Unleash, flagd, GrowthBook and others, so application code does not depend on one vendor.

Why config pushes are so dangerous#

PropertyCode deployTypical config push
Built and testedYesOften only syntax-checked
CanaryYesOften not
Rollout speedMinutes to hoursSeconds, globally
ReviewedYesSometimes
RollbackRoutineOften manual

Public examples:

  • Cloudflare, 2 July 2019: a new WAF rule with a regular expression that backtracked catastrophically was deployed globally at once; CPU on every edge server hit 100% and traffic dropped for about 27 minutes. Changes to WAF rules then moved to staged rollouts.
  • Facebook, 4 October 2021: a command meant to assess backbone capacity withdrew the backbone connections; an audit tool that should have blocked it had a bug. DNS servers then withdrew their BGP routes, and Facebook, Instagram and WhatsApp were unreachable for about six hours.
  • CrowdStrike, 19 July 2024: a content update (a “channel file”, treated as configuration, not code) to the Falcon sensor caused an out-of-bounds memory read and crashed about 8.5 million Windows machines worldwide. The update went to all customers at once; the remediation included staged deployment of content updates and customer control over timing.

Safe config rollout#

  1. Config as code: in a repository, reviewed, versioned.
  2. Validate semantics, not just syntax. Schema checks, range checks, cross-field checks — and the strongest check: start a real instance with the new config in CI and run a smoke test (the INC-2231 action item in 5.c).
  3. Stage it exactly like code: canary cell → one zone → one region → everywhere, with SLI checks between stages and automatic halt.
  4. Keep last known good on every instance; if a new config fails to load or a health check fails after loading, revert to it automatically.
  5. Fail static: if the config source is unreachable, keep running with the current config — never fail closed because the config server is down.
  6. Rate-limit global changes and require extra approval for anything that applies everywhere at once (DNS, BGP, global firewall rules, IAM).

A worked example#

A team wants to enable a new search ranking for all users.

  1. Release flag search-ranking-v3, owner and expiry set, default off.
  2. Enable for employees (permission targeting) for two days.
  3. 1% → 10% → 50% → 100% of users by hashed user ID, one step per day, watching the search latency SLI and a quality metric (click-through rate) for enabled versus disabled users.
  4. At 10%, p99 latency for enabled users is 40% higher. The flag is turned back to 0% in seconds; nobody deploys anything. The fix ships the next week.
  5. After 100% for a week, the flag and the old code path are removed.

The program implements sticky percentage rollout, a kill switch, and a config validator that catches the kind of mistake behind several of the outages above.

Code#

Go
// flags.go — sticky percentage rollout by hashing, a kill switch, and semantic config validation.
package main

import (
	"fmt"
	"hash/fnv"
	"regexp"
	"time"
)

type Flag struct {
	Name    string
	Percent int  // 0–100
	Killed  bool // kill switch: overrides everything
	Owner   string
	Expires time.Time
}

// bucket maps (flag, user) to 0–99. The flag name salts the hash so flags pick different users.
func bucket(flag, user string) int {
	h := fnv.New32a()
	h.Write([]byte(flag + ":" + user))
	return int(h.Sum32() % 100)
}

func (f Flag) Enabled(user string) bool {
	if f.Killed {
		return false
	}
	return bucket(f.Name, user) < f.Percent
}

type WAFRule struct {
	Name    string
	Pattern string
	Regions []string // empty means "all regions"
}

// validate checks semantics, not just syntax: the kind of checks that stop a global outage.
func validate(r WAFRule) []string {
	var problems []string
	if _, err := regexp.Compile(r.Pattern); err != nil {
		return append(problems, "pattern does not compile: "+err.Error())
	}
	// Go's regexp is linear-time (RE2), but rules may run on an engine that backtracks.
	// Flag the classic catastrophic shapes: nested quantifiers like (a+)+ or .*.*=.*
	if regexp.MustCompile(`\([^)]*[+*]\)[+*]|\.\*.*\.\*.*\.\*`).MatchString(r.Pattern) {
		problems = append(problems, "pattern has nested or repeated unbounded quantifiers: catastrophic backtracking risk")
	}
	if len(r.Regions) == 0 {
		problems = append(problems, "applies to all regions at once: stage it (canary region first)")
	}
	return problems
}

func main() {
	f := Flag{Name: "search-ranking-v3", Percent: 10, Owner: "search-team", Expires: time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)}
	users := []string{"u-1001", "u-1002", "u-1003", "u-1004", "u-1005", "u-1006", "u-1007", "u-1008"}

	on := 0
	for i := 0; i < 100_000; i++ {
		if f.Enabled(fmt.Sprintf("user-%d", i)) {
			on++
		}
	}
	fmt.Printf("%s at %d%%: %.2f%% of 100,000 users enabled\n", f.Name, f.Percent, float64(on)/1000)

	fmt.Println("\nsticky: the same users stay enabled as the percentage grows")
	for _, pct := range []int{10, 25, 50} {
		f.Percent = pct
		fmt.Printf("  %3d%%: ", pct)
		for _, u := range users {
			mark := "·"
			if f.Enabled(u) {
				mark = "■"
			}
			fmt.Print(mark, " ")
		}
		fmt.Println()
	}
	f.Killed = true
	fmt.Printf("  kill switch on: u-1001 enabled = %v\n", f.Enabled("u-1001"))

	fmt.Println("\nconfig validation")
	rules := []WAFRule{
		{"block-sqli", `(?i)union\s+select`, []string{"canary-eu"}},
		{"xss-2019-style", `(?:(?:\"|'|\]|\}|\\|\d|(?:nan|infinity|true|false|null|undefined|symbol|math)|\` + "`" + `|\-|\+)+[)]*;?((?:\s|-|~|!|{}|\|\||\+)*.*(?:.*=.*)))`, nil},
		{"broken", `(unclosed`, []string{"us-east"}},
	}
	for _, r := range rules {
		probs := validate(r)
		if len(probs) == 0 {
			fmt.Printf("  ✓ %s\n", r.Name)
			continue
		}
		for _, p := range probs {
			fmt.Printf("  ✗ %s: %s\n", r.Name, p)
		}
	}
}

The second rule is modelled on the expression behind Cloudflare’s 2019 outage: .*(?:.*=.*) is the part that backtracks catastrophically on a backtracking engine. A semantic check like this one is crude, but combined with “never apply to all regions at once” it turns a global outage into a failed canary.

Remember this#

  • Flags separate deploy from release and are among the best mitigations; kill switches are reliability features.
  • Percentage rollouts must be sticky (hash a stable key, salted by flag name).
  • Every flag has an owner and expiry; dead flags are removed; SDKs fail to safe defaults.
  • Config and flag changes are code changes: review, validate semantics, stage, auto-revert, keep last known good, fail static.

Try it#

  1. Run flags.go. Change the hash salt so it no longer includes the flag name. What goes wrong when two flags are both at 10%?
  2. List every way configuration reaches production in a system you know. Which ones are staged?
  3. Write the kill-switch section of a runbook for one expensive feature.

Check yourself#

  1. Why must percentage rollouts be sticky?
  2. Name three ways a typical config push is riskier than a code deploy.
  3. What does “fail static” mean for a config client?
  4. What should happen when a flag service is unreachable?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in