← All posts

SaaS feature flags: rolling out new features one customer at a time

Ship a feature to a few pilot customers, then 10%, then everyone, with an off switch that needs no redeploy: a simple database-backed flag system, no third-party service, plus the traps we've learned to avoid.

SaaS feature flags: rolling out new features one customer at a time

Key points

  • In B2B SaaS, flag by customer account, not by user: a whole team should see the same product.
  • Three tables are enough: a rollout percentage per flag, per-customer overrides, and a change history.
  • Test both code paths, enforce flags on the server, and give every flag a removal date.

The new feature is ready, but switching it on for every customer at once is a gamble: one edge case at a big account or one slow query on a heavy tenant, and your support team takes the hit. Feature flags split two decisions that are usually bundled together: deploying the code, and releasing it to customers. The code ships switched off alongside everything else, then gets opened up gradually. There are dedicated services for this, but for most of the applications we work on, a few tables and a small class do the job well, as long as you follow a handful of rules.

Flag accounts, not users

In a B2B product, the account is the unit that matters. If half a team sees the new screen and the other half doesn’t, your customer’s internal conversations get confusing and support starts receiving screenshots it can’t explain. So on our projects, flags are always evaluated against the account ID, even when a feature only concerns one role.

Keep flags separate from plan entitlements, too. A plan says what a customer has paid for; a flag says what’s ready to ship. Mix them, say by gating a premium feature behind a flag, and you can no longer tell whether a customer has access because they pay or because they’re in the test group. The day the flag is removed, free accounts end up with a paid feature.

The data model

A rollout percentage per flag, an overrides table to force a feature on (pilot customers) or off (the account where it misbehaves), and a change history:

CREATE TABLE feature_flags (
  flag_key        VARCHAR(64) PRIMARY KEY,
  rollout_percent TINYINT UNSIGNED NOT NULL DEFAULT 0,
  remove_by       DATE NULL,
  description     VARCHAR(255) NOT NULL DEFAULT ''
);

CREATE TABLE feature_flag_overrides (
  flag_key  VARCHAR(64) NOT NULL,
  tenant_id INT UNSIGNED NOT NULL,
  enabled   BOOLEAN NOT NULL,
  PRIMARY KEY (flag_key, tenant_id),
  FOREIGN KEY (flag_key) REFERENCES feature_flags (flag_key) ON DELETE CASCADE
);

CREATE TABLE feature_flag_changes (
  id         BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  flag_key   VARCHAR(64) NOT NULL,
  tenant_id  INT UNSIGNED NULL,          -- NULL: global change
  old_value  VARCHAR(32) NOT NULL,
  new_value  VARCHAR(32) NOT NULL,
  changed_by INT UNSIGNED NOT NULL,
  changed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

The history table feels unnecessary until your first incident. When a customer reports that a screen changed on Tuesday morning, being able to say “that flag went from 10% to 25% at 9:12 on Tuesday” saves real time. The remove_by column is what stops you from still branching on long-shipped features two years from now.

A stable answer for each customer

The tricky part is the percentage. A customer included at 10% must still be included at 20%, and their answer must not flip between page loads, which rules out rolling the dice on every request. Instead, derive a fixed position from the flag name and the account ID:

final class Features
{
    private array $memo = [];

    public function __construct(private PDO $db) {}

    public function enabled(string $flag, int $tenantId): bool
    {
        return $this->memo["$flag:$tenantId"] ??= $this->resolve($flag, $tenantId);
    }

    private function resolve(string $flag, int $tenantId): bool
    {
        $stmt = $this->db->prepare(
            'SELECT o.enabled AS forced, f.rollout_percent
               FROM feature_flags f
               LEFT JOIN feature_flag_overrides o
                      ON o.flag_key = f.flag_key AND o.tenant_id = :tenant
              WHERE f.flag_key = :flag'
        );
        $stmt->execute(['flag' => $flag, 'tenant' => $tenantId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row === false) {
            return false; // unknown flag: feature off
        }
        if ($row['forced'] !== null) {
            return (bool) $row['forced']; // explicit choice for this customer
        }
        // Same customer, same flag: always the same answer
        return crc32("$flag:$tenantId") % 100 < (int) $row['rollout_percent'];
    }
}

Mixing the flag name into the hash means it isn’t the same unlucky customers who meet every new feature first. The $memo array saves you from running the same query ten times while rendering one page. And an unknown flag returns false, so a typo in the name switches a feature off rather than opening it to everyone.

Enforce it server-side and test both paths

Hiding a button isn’t enough. The underlying action has to be refused by the server, or a direct API call walks straight past the flag. We also expose flag states in the response that drives the UI, so the front end never has to guess:

// On the server, where the action is actually handled
if (!$features->enabled('scheduled_export', $tenant->id)) {
    http_response_code(404);
    exit;
}

// And in the API response that drives the UI
return [
    'user'     => $user->toArray(),
    'features' => [
        'scheduled_export' => $features->enabled('scheduled_export', $tenant->id),
    ],
];

A trap we’ve hit more than once: the new path gets tested thoroughly, the old one stops being tested at all, and it’s the old one that breaks for the 90% of customers still on it. So every flag means two tests, one per path:

public function test_export_is_refused_when_flag_is_off(): void
{
    $this->flags->force('scheduled_export', $this->tenant->id, false);

    $this->post('/exports/schedule', ['frequency' => 'weekly'])
         ->assertStatus(404);
}

public function test_export_is_accepted_when_flag_is_on(): void
{
    $this->flags->force('scheduled_export', $this->tenant->id, true);

    $this->post('/exports/schedule', ['frequency' => 'weekly'])
         ->assertStatus(201);
}

Running flags, then retiring them

A few operating rules that have served us well:

  • Start with your own accounts, then two or three pilot customers who know what’s coming, before opening a percentage.
  • Ramp up in steps and watch error rates and response times between each one, not just the support inbox.
  • Restrict who can change a flag: changing a percentage is a production release and deserves the same care.
  • Keep a kill switch: setting the percentage to 0 must be enough to restore the old behaviour, no deploy needed.

Once a feature has been at 100% and stable for a few weeks, remove the condition and the old code first, then the database row. We list overdue flags in the internal admin; it’s the one reminder that reliably gets acted on.

FAQ

Should we just use a feature flag service?

It starts paying off when you have many flags, several apps to coordinate, or need fine targeting such as country or mobile app version. For a handful of flags per quarter in one application, three tables are easier to maintain and to understand.

What happens if I lower the percentage?

Customers whose position is above the new threshold lose access. That’s by design, but if the feature creates data (a scheduled export, say), decide upfront what happens to it when the flag is switched off.

Do flags slow the application down?

With per-request memoisation the cost is negligible. If a page checks a lot of flags, load all of a customer’s flags in one query, or cache them for a few seconds.

Want to ship more often without gambling with your customers? We design and evolve SaaS products with gradual, tested and reversible releases built in.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →