πŸ”§ DevOps

Feature Flag

Feature Flag

A technique that decouples code deployment from feature release. Used for A/B testing.

πŸ“– Detailed Explanation

Feature Flag is a software development technique that separates code deployment from feature release. You deploy the code, but control specific features with a flag (on/off switch) so they can be activated at the desired time. It is also called Feature Toggle or Feature Switch.

Core concepts:

  • Release Flag: Hide unfinished features and release them gradually
  • Experiment Flag: Expose features to different user groups for A/B testing
  • Ops Flag: Adjust performance and disable features in the production environment
  • Permission Flag: Provide features based on permissions, such as for paying users and beta testers

Key use cases:

  • Canary Release: Deploy a new feature to only some users, then expand
  • Kill Switch: Disable a feature immediately when a problem occurs
  • Trunk-Based Development: Keep merging into the main branch without long-lived branches
  • A/B Testing: Compare two versions to make data-driven decisions

Feature Flag management tools:

  • LaunchDarkly: Enterprise-grade Feature Management platform
  • Unleash: Open-source Feature Flag server
  • Split: A/B testing + Feature Flag integration
  • Firebase Remote Config: Free solution for mobile apps
  • ConfigCat: Simple, developer-friendly service

Relationship with Trunk-Based Development: Feature Flags eliminate long-lived feature branches and allow all developers to merge into the main branch frequently. Because unfinished features can simply be hidden behind flags, merge conflicts decrease and the CI/CD pipeline becomes simpler.

πŸ’» Code Example

Simple Feature Flag implementation

// TypeScript - κ°„λ‹¨ν•œ Feature Flag μ„œλΉ„μŠ€
interface FeatureFlags {
  newDashboard: boolean;
  darkMode: boolean;
  betaFeatures: boolean;
  maxUploadSize: number;
}

class FeatureFlagService {
  private flags: FeatureFlags;
  private userOverrides: Map<string, Partial<FeatureFlags>> = new Map();

  constructor() {
    // κΈ°λ³Έκ°’ (ν™˜κ²½λ³€μˆ˜λ‚˜ μ„€μ • νŒŒμΌμ—μ„œ λ‘œλ“œ)
    this.flags = {
      newDashboard: process.env.FF_NEW_DASHBOARD === 'true',
      darkMode: true,
      betaFeatures: false,
      maxUploadSize: 10 * 1024 * 1024, // 10MB
    };
  }

  // κΈ€λ‘œλ²Œ ν”Œλž˜κ·Έ 확인
  isEnabled(flag: keyof FeatureFlags): boolean {
    return Boolean(this.flags[flag]);
  }

  // μ‚¬μš©μžλ³„ ν”Œλž˜κ·Έ 확인 (μ˜€λ²„λΌμ΄λ“œ 지원)
  isEnabledForUser(flag: keyof FeatureFlags, userId: string): boolean {
    const userFlags = this.userOverrides.get(userId);
    if (userFlags && flag in userFlags) {
      return Boolean(userFlags[flag]);
    }
    return this.isEnabled(flag);
  }

  // νΌμ„ΌνŠΈ 기반 둀아웃 (Canary)
  isEnabledForPercentage(flag: keyof FeatureFlags, userId: string, percentage: number): boolean {
    const hash = this.hashUserId(userId);
    return hash % 100 < percentage && this.isEnabled(flag);
  }

  private hashUserId(userId: string): number {
    let hash = 0;
    for (let i = 0; i < userId.length; i++) {
      hash = ((hash << 5) - hash) + userId.charCodeAt(i);
      hash |= 0;
    }
    return Math.abs(hash);
  }

  // νŠΉμ • μ‚¬μš©μžμ—κ²Œ κΈ°λŠ₯ ν™œμ„±ν™” (베타 ν…ŒμŠ€ν„° λ“±)
  enableForUser(userId: string, flags: Partial<FeatureFlags>) {
    const existing = this.userOverrides.get(userId) || {};
    this.userOverrides.set(userId, { ...existing, ...flags });
  }
}

// μ‚¬μš© μ˜ˆμ‹œ
const featureFlags = new FeatureFlagService();

// React μ»΄ν¬λ„ŒνŠΈμ—μ„œ μ‚¬μš©
function Dashboard({ userId }: { userId: string }) {
  // 10% μ‚¬μš©μžμ—κ²Œλ§Œ μƒˆ λŒ€μ‹œλ³΄λ“œ λ…ΈμΆœ
  if (featureFlags.isEnabledForPercentage('newDashboard', userId, 10)) {
    return <NewDashboard />;
  }
  return <LegacyDashboard />;
}

React Hook with Context

// React Feature Flag Context
import { createContext, useContext, ReactNode } from 'react';

interface FeatureFlagContextType {
  isEnabled: (flag: string) => boolean;
  getVariant: (flag: string) => string | null;
}

const FeatureFlagContext = createContext<FeatureFlagContextType | null>(null);

export function FeatureFlagProvider({
  children,
  flags
}: {
  children: ReactNode;
  flags: Record<string, boolean | string>;
}) {
  const value: FeatureFlagContextType = {
    isEnabled: (flag) => Boolean(flags[flag]),
    getVariant: (flag) => typeof flags[flag] === 'string' ? flags[flag] : null,
  };

  return (
    <FeatureFlagContext.Provider value={value}>
      {children}
    </FeatureFlagContext.Provider>
  );
}

// Custom Hook
export function useFeatureFlag(flag: string): boolean {
  const context = useContext(FeatureFlagContext);
  if (!context) throw new Error('useFeatureFlag must be used within FeatureFlagProvider');
  return context.isEnabled(flag);
}

// μ»΄ν¬λ„ŒνŠΈμ—μ„œ μ‚¬μš©
function CheckoutButton() {
  const newCheckoutEnabled = useFeatureFlag('new-checkout-flow');

  if (newCheckoutEnabled) {
    return <NewCheckoutButton />;
  }
  return <LegacyCheckoutButton />;
}

// A/B ν…ŒμŠ€νŠΈ λ³€ν˜• 확인
function PricingPage() {
  const context = useContext(FeatureFlagContext);
  const variant = context?.getVariant('pricing-experiment');

  switch (variant) {
    case 'control': return <PricingA />;
    case 'variant-b': return <PricingB />;
    case 'variant-c': return <PricingC />;
    default: return <PricingA />;
  }
}

Using the LaunchDarkly SDK

// Node.js - LaunchDarkly SDK
import * as ld from 'launchdarkly-node-server-sdk';

const ldClient = ld.init(process.env.LAUNCHDARKLY_SDK_KEY!);

// μ„œλ²„ μ‹œμž‘ μ‹œ μ΄ˆκΈ°ν™” λŒ€κΈ°
await ldClient.waitForInitialization();

// μ‚¬μš©μž μ»¨ν…μŠ€νŠΈ μ •μ˜
const user = {
  key: 'user-123',
  email: 'user@example.com',
  custom: {
    plan: 'premium',
    country: 'KR',
    signupDate: '2024-01-15',
  },
};

// Boolean ν”Œλž˜κ·Έ 확인
const showNewFeature = await ldClient.variation('new-feature', user, false);

// λ‹€λ³€ν˜• ν”Œλž˜κ·Έ (A/B/C ν…ŒμŠ€νŠΈ)
const checkoutVariant = await ldClient.variation('checkout-experiment', user, 'control');

// ν”Œλž˜κ·Έ λ³€κ²½ μ‹€μ‹œκ°„ 감지
ldClient.on('update:new-feature', async () => {
  const newValue = await ldClient.variation('new-feature', user, false);
  console.log('Feature flag updated:', newValue);
});

// Express 미듀웨어
function featureFlagMiddleware(flagKey: string, defaultValue: boolean) {
  return async (req, res, next) => {
    const user = { key: req.user?.id || 'anonymous' };
    req.featureFlags = req.featureFlags || {};
    req.featureFlags[flagKey] = await ldClient.variation(flagKey, user, defaultValue);
    next();
  };
}

// λΌμš°νŠΈμ—μ„œ μ‚¬μš©
app.get('/api/checkout', featureFlagMiddleware('new-checkout', false), (req, res) => {
  if (req.featureFlags['new-checkout']) {
    return handleNewCheckout(req, res);
  }
  return handleLegacyCheckout(req, res);
});

πŸ—£οΈ Examples of Practical Conversations

Release strategy meeting

PM: "When are we releasing the new payment system? QA said they need 2 weeks."

Developer: "I'll deploy the code this week and block it behind a Feature Flag. QA can turn the flag on in staging and test, and once it's ready, we'll start with 1% of users in production and ramp up gradually."

PM: "What if there's a problem?"

Developer: "Just turn off the flag in the dashboard and it rolls back immediately. No code rollback needed β€” it's restored in 3 seconds."

Technical Interview

Interviewer: "What should you watch out for when using Feature Flags?"

Candidate: "First, flags pile up and become technical debt. After a full rollout, you must remove the flag code. Second, as flag combinations grow, the number of test cases increases exponentially. Third, it can affect performance, so flag evaluations should be cached, and flag calls should be minimized on hot paths."

Interviewer: "How do you clean up flags?"

Candidate: "When creating a flag, we set an expiration date, and we added a lint rule that warns in CI when an expired flag is used. Every quarter we hold a 'flag cleanup day' and remove legacy flags in bulk."

Incident response

On-call: "The error rate has spiked! It seems to have started after the new recommendation algorithm was deployed."

Developer: "I'll turn off the 'new-recommendation-v2' flag in the LaunchDarkly dashboard. It'll take effect in 3 seconds."

On-call: "The error rate is back to normal!"

Developer: "Let's put out the immediate fire first, and tomorrow I'll analyze the logs to find the cause. Thanks to the flag, it was resolved in 1 minute without a code rollback."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

Blue-Green Deployment Canary Release A/B Testing CI/CD Trunk-Based Development Progressive Delivery

πŸ“š Learn More