Understanding Feature Flags

Contents

Introduction

I looked into feature flags and built something that actually works with CakePHP and Unleash. In this post, I lay out the concept of feature flags and then write up how I implemented them.

What are feature flags?

Feature flags separate deploying from releasing a feature. You make a feature switchable ON/OFF with a conditional branch, so you can change behavior after a deploy just by changing a setting.

Flag ONFlag OFFNo redeploy neededDeployCode (with flag)Show new featureShow old featureChange setting
Mermaid source
flowchart LR
    Deploy["Deploy"] --> Code["Code (with flag)"]
    Code -->|"Flag ON"| New["Show new feature"]
    Code -->|"Flag OFF"| Old["Show old feature"]
    Toggle["Change setting"] -.->|"No redeploy needed"| Code

The idea:

if (FeatureToggle::isEnabled('new_checkout')) {
    return $newCheckoutService->execute();
}
return $legacyCheckoutService->execute();

According to Pete Hodgson's categories, flags fall into four types by lifetime and purpose.

Type Lifetime Example
Release Toggle Short Deploy a new feature still in development while keeping it hidden
Experiment Toggle Medium A/B testing
Ops Toggle Long Kill Switch (emergency stop during an incident)
Permission Toggle Long Features only for a premium plan

When are they useful?

  • You released a new feature and it caused an incident in production. Instead of waiting for a rollback deploy, you can stop the feature just by turning the flag OFF (Kill Switch).
  • Releasing to all users at once is scary. You can roll out gradually, 1% → 10% → 100%, and go back to 0% if there's a problem.
  • The feature isn't finished, but you don't want a long-lived feature branch. You can merge it into main while it stays hidden behind a flag (trunk-based development).
Note: percentage rollouts and the "reload problem"

If you try to implement "release to 10% of users" with a random number like rand() < 10, the same user sees the new feature on some reloads and not on others, and it breaks.

Feature flag services use a hash function so that the same user always gets the same result.

function isEnabled(string $flagKey, string $userId, int $percent): bool
{
    $bucket = abs(crc32($flagKey . ':' . $userId)) % 100;
    return $bucket < $percent;
}

Because the hash is computed from the user ID and the flag name, the same user gets the same result every time. It also has the property that when you raise 10% to 25%, the original 10% of users stay included.

Note that PHP's crc32() can return negative values, so abs() turns it into a positive value. Real services use hash functions with better uniform distribution, such as MurmurHash3, instead of crc32, and LaunchDarkly officially states that it uses MurmurHash3.

At this point you might think, "Couldn't I just branch on an environment variable?" But implementing percentage rollouts or targeting by user attributes yourself with environment variables is a lot of work, and every switch needs a redeploy. So from the point of view of separating deploys from feature releases, you end up needing a feature flag service.

Trying an implementation in CakePHP that makes flags easy to remove

Feature flags are handy, but if you write the conditional directly in a Controller, the places you need to change are scattered when the flag is no longer needed, and that gets painful.

// When the flag check is written directly in the Controller
class SomeController extends AppController
{
    public function index(): void
    {
        if (FeatureToggle::isEnabled('new_feature')) {
            $result = (new NewFeature())->execute();
        } else {
            $result = (new OldFeature())->execute();
        }

        $this->set('result', $result);
        $this->viewBuilder()->setOption('serialize', ['result']);
    }
}

Written this way, removing the flag means deleting the if/else in the Controller, deleting the reference to new OldFeature(), and rewriting the tests too. If the flag is scattered across several Controllers, the number of places to fix grows accordingly.

This time I implemented it in CakePHP, based on the Interface + DI design introduced in the talk "Feature Toggle は捨てやすく使おう" ("Build feature toggles to be thrown away", Japanese).

Define an Interface for the feature you want to switch, and prepare an old implementation and a new implementation.

interface SomeFeature
{
    public function execute(): array;
}

class OldFeature implements SomeFeature { /* old logic */ }
class NewFeature implements SomeFeature { /* new logic */ }

In the DI container, switch which one gets injected based on the flag.

public function services(ContainerInterface $container): void
{
    $container->add(SomeFeature::class, function () {
        if (FeatureToggle::disabled('new_feature')) {
            return new OldFeature();
        }

        return new NewFeature();
    });
}

The Controller knows nothing about the flag. It depends only on the Interface.

class SomeController extends AppController
{
    public function index(SomeFeature $feature): void
    {
        $result = $feature->execute();
        $this->set('result', $result);
        $this->viewBuilder()->setOption('serialize', ['result']);
    }
}

When you remove the flag

This design pays off when you remove the flag. The only file you change is Application.php. You don't touch the Controller.

  public function services(ContainerInterface $container): void
  {
-     $container->add(SomeFeature::class, function () {
-         if (FeatureToggle::disabled('new_feature')) {
-             return new OldFeature();
-         }
-
-         return new NewFeature();
-     });
+     $container->add(SomeFeature::class, NewFeature::class);
  }

Then you delete the whole OldFeature.php file and remove the flag from Unleash (covered later), and you're done. You don't need to touch the Controller, the Interface, or the new implementation.

What I tried: applying it to a book recommendation API

This time I used a book recommendation API as the subject and switched between "old logic that returns new books" and "new logic that returns personalized recommendations" with a flag.

interface RecommendationEngine
{
    /** @return array<int, array{title: string, score: float, reason?: string}> */
    public function recommend(string $userId): array;
}
// Old implementation: returns new books
class RecentBooksRecommendationEngine implements RecommendationEngine
{
    public function recommend(string $userId): array
    {
        return [
            ['title' => 'CakePHP 5 入門', 'score' => 0.80],
            ['title' => 'PHP 8.3 の新機能', 'score' => 0.75],
            ['title' => 'Docker 実践ガイド', 'score' => 0.70],
        ];
    }
}
// New implementation: returns personalized recommendations
class PersonalizedRecommendationEngine implements RecommendationEngine
{
    public function recommend(string $userId): array
    {
        return [
            ['title' => 'デザインパターン入門', 'score' => 0.95, 'reason' => '購入履歴に基づくおすすめ'],
            ['title' => 'リファクタリング 第2版', 'score' => 0.90, 'reason' => '閲覧履歴に基づくおすすめ'],
            ['title' => 'Clean Architecture', 'score' => 0.88, 'reason' => '似たユーザーが購入'],
        ];
    }
}

Switching in the DI container:

$container->add(RecommendationEngine::class, function () {
    if (FeatureToggle::disabled('new_recommendation')) {
        return new RecentBooksRecommendationEngine();
    }

    return new PersonalizedRecommendationEngine();
});

The Controller doesn't know about the flag and depends only on RecommendationEngine:

class RecommendationsController extends AppController
{
    public function index(RecommendationEngine $engine): void
    {
        $recommendations = $engine->recommend('user-1');

        $this->set('recommendations', $recommendations);
        $this->viewBuilder()->setOption('serialize', ['recommendations']);
    }
}

Managing flags externally with Unleash

This time I used Unleash, an open-source feature flag platform, so that flags can be switched from an admin screen without redeploying.

If UNLEASH_URL is set, the app uses Unleash; if not, it falls back to environment variables. I implemented it this way so I can use environment variables during development and Unleash in production.

Fetch flags with the PHPSDKTurn flags ON/OFF in theadmin screenCakePHP appUnleash ServerPostgreSQLAdmin
Mermaid source
flowchart LR
    App["CakePHP app"] -->|"Fetch flags with the PHP SDK"| Unleash["Unleash Server"]
    Unleash --> DB["PostgreSQL"]
    Admin["Admin"] -->|"Turn flags ON/OFF in the admin screen"| Unleash
FeatureFlagSource implementation
interface FeatureFlagSource
{
    public function isEnabled(string $flag): bool;
}
// Implementation that reads from Unleash
class UnleashFeatureFlagSource implements FeatureFlagSource
{
    public function __construct(private Unleash $unleash) {}

    public function isEnabled(string $flag): bool
    {
        return $this->unleash->isEnabled($flag);
    }
}
// Fallback implementation that reads from environment variables (for development and testing)
class EnvFeatureFlagSource implements FeatureFlagSource
{
    public function isEnabled(string $flag): bool
    {
        $key = 'FEATURE_' . strtoupper($flag);

        return env($key, 'false') === 'true';
    }
}

FeatureToggle is a facade that delegates to this FeatureFlagSource. If no source is set, it falls back to EnvFeatureFlagSource.

class FeatureToggle
{
    private static ?FeatureFlagSource $source = null;

    public static function setSource(FeatureFlagSource $source): void
    {
        static::$source = $source;
    }

    public static function isEnabled(string $flag): bool
    {
        if (static::$source === null) {
            static::$source = new EnvFeatureFlagSource();
        }

        return static::$source->isEnabled($flag);
    }

    public static function disabled(string $flag): bool
    {
        return !static::isEnabled($flag);
    }
}
Wiring it up in the DI container

If UNLEASH_URL is set, it uses Unleash; if not, it falls back to environment variables.

public function services(ContainerInterface $container): void
{
    // Flag source: use Unleash if available, otherwise fall back to environment variables
    $container->add(FeatureFlagSource::class, function () {
        $unleashUrl = env('UNLEASH_URL');
        if ($unleashUrl) {
            $unleash = UnleashBuilder::create()
                ->withAppName('api-a')
                ->withAppUrl((string)$unleashUrl)
                ->withInstanceId('api-a-local')
                ->withHeader('Authorization', (string)env('UNLEASH_API_KEY', ''))
                ->build();

            return new UnleashFeatureFlagSource($unleash);
        }

        return new EnvFeatureFlagSource();
    });

    // Recommendation engine: switch the implementation based on the flag
    $container->add(RecommendationEngine::class, function () use ($container) {
        $flagSource = $container->get(FeatureFlagSource::class);
        FeatureToggle::setSource($flagSource);

        if (FeatureToggle::disabled('new_recommendation')) {
            return new RecentBooksRecommendationEngine();
        }

        return new PersonalizedRecommendationEngine();
    });
}
docker-compose.yml (the Unleash part)
services:
  unleash-db:
    image: postgres:15
    environment:
      POSTGRES_USER: unleash
      POSTGRES_PASSWORD: unleash
      POSTGRES_DB: unleash

  unleash:
    image: unleashorg/unleash-server:latest
    ports:
      - "4242:4242"
    environment:
      DATABASE_URL: postgres://unleash:unleash@unleash-db:5432/unleash
      DATABASE_SSL: "false"
      UNLEASH_DEFAULT_ADMIN_USERNAME: admin
      UNLEASH_DEFAULT_ADMIN_PASSWORD: unleash4all
    depends_on:
      - unleash-db

After starting it with docker compose up -d, the admin screen is available at http://localhost:4242.

Trying it out

I confirmed that just turning the flag ON/OFF in the Unleash admin screen switches the API response without a redeploy. The Unleash PHP SDK polls the flag state, so you do need to wait a little after switching.

Admin screen

Unleash admin screen for the new_recommendation flag, with ON/OFF toggles for the development and production environments

Screen

With the old logic

Response with the old logic: a "Recent Books" label and three new books with their scores

With the new logic

Response with the new logic: a "Personalized" label and three recommended books, each with a reason and a score

I confirmed that I could switch the feature without a deploy.

Note that this time I only tried a global ON/OFF. To do the percentage rollout from the first half with Unleash, you need to pass the user ID to isEnabled() in a Context object.

Conclusion

I laid out the concept of feature flags and built something that actually works with CakePHP + Unleash.

By keeping the flag check inside the DI container with Interface + DI, I could limit the changes needed to remove a flag to Application.php alone. Not having to touch the Controller or the new implementation's code was easier than I expected once I actually did it.

References

Translated from the Japanese original.

Thanks. I'll look into it.

Spotted a mistake?

Tell me what's wrong and I'll fix it. Only I see what you send.