106
LVL 04 — SENIOR-IN-TRAININGSESSION 106DAY 106

FEATURE FLAGS

🎫 PIXELCRAFT-092
Feature | 🔴 Expert | Priority: 🟠 High

We want to ship "AI Enhance" but it's risky. If it crashes, all users are affected. Deploy without releasing. Hide features behind flags. Roll out to 10% of users first. Kill switch if errors spike. Measure conversion before full release.
CONCEPTS.UNLOCKED
🏁
Feature Flags
Deploy code without releasing it to users. Code is in production but hidden behind a boolean. Flip the flag → feature appears. Flip it back → feature disappears. Deployment ≠ release.
📈
Progressive Rollout
1% → 10% → 50% → 100%. Start with internal team. Then 1% of users. Monitor errors and metrics. Gradually increase. If anything goes wrong, roll back instantly — no redeploy needed.
🐤
Canary Deployments
Send a small percentage of traffic to the new version. Like a canary in a coal mine: if the canary (small group) is fine, send everyone. If it dies, pull back. Combines with feature flags.
🔴
Kill Switches
Instantly disable a feature in production. Error rate spikes? Flip the flag off. No deploy, no CI pipeline, no waiting. Instant rollback measured in seconds, not minutes.
🧪
A/B Testing
Show version A to half, version B to half. Measure which wins. Feature flags enable A/B testing infrastructure: same codebase, different experiences, data-driven decisions.
🔧
Flag Services
LaunchDarkly, Unleash, Flagsmith — or build your own. Managed services offer dashboards, targeting rules, audit logs. Custom implementations work for simpler needs using Redis or database flags.
HANDS-ON.TASKS
01
Build a Feature Flag System
// lib/featureFlags.ts interface FeatureFlag { name: string; enabled: boolean; rolloutPercentage: number; allowedUserIds: string[]; } const flags: Record<string, FeatureFlag> = { 'ai-enhance': { name: 'AI Image Enhancement', enabled: true, rolloutPercentage: 10, allowedUserIds: [ 'admin-1', 'beta-tester-1' ], }, 'new-export-dialog': { name: 'Redesigned Export', enabled: false, rolloutPercentage: 0, allowedUserIds: [], }, };
02
Flag Evaluation Logic
// lib/featureFlags.ts (continued) function isFeatureEnabled( flagName: string, userId: string ): boolean { const flag = flags[flagName]; if (!flag || !flag.enabled) return false; // Always-on for specific users if (flag.allowedUserIds .includes(userId)) return true; // Percentage rollout: // Hash the userId to get a // consistent 0-100 number. // Same user always gets same result. const hash = simpleHash( `${flagName}:${userId}`); const bucket = hash % 100; return bucket < flag.rolloutPercentage; } function simpleHash(str: string) { let hash = 0; for (const char of str) { hash = ((hash << 5) - hash) + char.charCodeAt(0); hash |= 0; // Convert to 32-bit int } return Math.abs(hash); } // Same user, same flag → always // same result. No randomness. // Deterministic by user ID.
03
React Hook for Feature Flags
// hooks/useFeatureFlag.ts import { useAuth } from './useAuth'; export function useFeatureFlag( flagName: string ): boolean { const { user } = useAuth(); if (!user) return false; return isFeatureEnabled( flagName, user.id); } // In a component: function Toolbar() { const showAiEnhance = useFeatureFlag('ai-enhance'); return ( <nav> <button>Brightness</button> <button>Contrast</button> {showAiEnhance && ( <button className="new-badge"> ✨ AI Enhance </button> )} </nav> ); } // 10% of users see the button. // 90% see the same toolbar as before. // No separate codepaths. No branches.
04
Admin Dashboard: Kill Switch
// API: toggle flag // POST /api/admin/flags/:name app.post('/api/admin/flags/:name', requireAdmin, async (req, res) => { const { name } = req.params; const { enabled, rolloutPercentage } = req.body; await db.collection('featureFlags') .updateOne( { name }, { $set: { enabled, rolloutPercentage, updatedAt: new Date(), updatedBy: req.user.id, }}, ); // Log for audit trail logger.info('Flag updated', { flag: name, enabled, rolloutPercentage, by: req.user.email, }); res.json({ success: true }); }); // Kill switch: one click → // enabled: false → // feature disappears for everyone. // No deploy. No CI. Instant.
05
Progressive Rollout Plan
// Rollout plan for "AI Enhance": // Day 1: Internal team only // allowedUserIds: ['team-1', ...] // rolloutPercentage: 0 // Day 2: 1% of users // rolloutPercentage: 1 // Monitor: error rate, latency // Day 4: 10% of users // rolloutPercentage: 10 // Monitor: conversion, engagement // Day 7: 50% of users // rolloutPercentage: 50 // A/B test: compare metrics // Day 10: 100% (full release) // rolloutPercentage: 100 // Remove flag from code (cleanup)
Important: remove flags after full rollout. Stale flags accumulate as technical debt. Track flag age and clean up regularly. A flag that's been at 100% for 30+ days should be removed.
06
Close the Ticket
git switch -c feature/PIXELCRAFT-092-feature-flags git add src/lib/ src/hooks/ src/api/ git commit -m "Add feature flag system + AI Enhance rollout (PIXELCRAFT-092)" git push origin feature/PIXELCRAFT-092-feature-flags # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Deployment ≠ Release.

Feature flags decouple deployment from release. Code ships to production but users don't see it until you decide. This changes everything about how teams ship software.

// Without feature flags:
  Deploy = Release
  Ship → everyone gets it
  Bug → everyone hit
  Rollback → full redeploy (minutes)

// With feature flags:
  Deploy ≠ Release
  Ship → nobody sees it
  Enable → 1% sees it
  Bug → flip flag off (seconds)

// Used by:
Facebook: Gatekeeper system
  Every feature behind a flag
Netflix: A/B test everything
  UI, algorithms, pricing
Google: Experiments framework
  Thousands of concurrent tests

// Feature flags enable:
// trunk-based development,
// continuous deployment,
// data-driven decisions,
// instant rollback.
"Flags Lab"
[A]Build an A/B test: show two different export dialog designs (A: current, B: redesigned). Track which version has a higher completion rate. Use feature flags to split users 50/50. Report results after one week.
[B]Add user targeting rules: enable a feature for users in a specific country, on a specific plan, or who signed up after a certain date. Extend the flag evaluation with targeting conditions.
[C]Research: what is trunk-based development? How do feature flags enable it? Compare to GitFlow (long-lived feature branches). Why do companies like Google and Facebook prefer trunk-based development?
REF.MATERIAL
ARTICLE
Pete Hodgson / Martin Fowler
The canonical article on feature flags: release toggles, experiment toggles, ops toggles, permission toggles. Categories and lifecycle management.
FLAGSTHEORYESSENTIAL
VIDEO
DevOps Toolkit
Practical feature flag patterns: progressive delivery, canary releases, A/B testing. When to use flags and when to avoid them.
FLAGSPRACTICAL
ARTICLE
Unleash
Open-source feature flag platform: strategies, variants, constraints, and SDK integration. Self-hosted alternative to LaunchDarkly.
UNLEASHOPEN SOURCE
ARTICLE
Paul Hammant
The development model that feature flags enable: everyone commits to main, features hidden behind flags. Used by Google, Facebook, and Netflix.
TRUNKWORKFLOW
VIDEO
Fireship
Quick overview of A/B testing: hypothesis, variants, metrics, statistical significance. How top companies make data-driven product decisions.
A/BQUICK
// LEAVE EXCITED BECAUSE
"AI Enhance" is in production but only 10% of users see it. Kill switch ready. Error rate monitored. This is how Facebook, Netflix, and Google ship features — and now you do too.