Feature Flag
Feature Flag
A technique that decouples code deployment from feature release. Used for A/B testing.
Feature Flag
A technique that decouples code deployment from feature release. Used for A/B testing.
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:
Key use cases:
Feature Flag management tools:
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.
// 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 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 />;
}
}
// 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);
});
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."
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."
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