Why You Should Use Feature Flags and What They Are

Why You Should Use Feature Flags and What They Are

Introduction

Ever launched a feature and then wished you hadn't? Or wanted to test a new feature with just 10% of your users to test it out before rolling it out to everyone?

Feature flags can help.

What Are Feature Flags?

Feature flags are like switches in your code that can turn features on or off. They are conditional statements that let you change features without having to redeploy your application.

// Without feature flags
function showNewDesign() {
  return <NewDesign />;
}

// With feature flags
function showNewDesign() {
  if (isFeatureEnabled("new-design")) {
    return <NewDesign />;
  }
  return <OldDesign />;
}

Why Use Feature Flags?

  1. Kill Switch: Have you ever released code that let users make free purchases by mistake? A feature flag lets you quickly turn off these features without needing a deployment.

  2. Gradual Rollouts: Try out new features with a small group of users (like 10% of your users) to see how they work and find problems early.

  3. Beta Testing: Allow certain users to try new features while keeping them hidden from everyone else.

  4. Safe Refactoring: Test new versions of your code alongside the old ones without impacting users.

function fetchUsers() {
  const users = await oldQuery();

  if (isFeatureEnabled("new-query")) {
    const newUsers = await newQuery();
    // Compare results, log differences
    return users;
  }

  return users;
}

Implementation Options

1. Environment Variables

const flags = {
  newDesign: process.env.ENABLE_NEW_DESIGN === "true",
};

Pros: Simple, no infrastructure needed

Cons: Requires deployment to change, limited to boolean flags

2. Database-Driven

interface FeatureFlag {
  name: string;
  enabled: boolean;
  rolloutPercentage?: number;
  enabledForUsers?: string[];
}

Pros: Dynamic updates, complex rules possible

Cons: Requires database setup, potential performance impact

3. Third-Party Services

Services like LaunchDarkly, Posthog or ConfigCat

Pros: Full-featured, managed solution

Cons: Cost, vendor lock-in

Conclusion

The aim isn't to use feature flags everywhere, but to apply them strategically where they provide the most value.