From the blog

Feature Flags vs Entitlements in Phoenix: When to Use Which, and How to Combine Them

By Liam Killingback ·

Feature Flags vs Entitlements in Phoenix: When to Use Which, and How to Combine Them

It starts with one line. A new AI report builder is not ready for everyone, so it goes behind if FunWithFlags.enabled?(:ai_reports, for: org). A month later it ships, and someone decides it should be a Pro feature. The quickest change is to leave the flag in place and switch it on for paying customers by hand. Six months on, sales enables it for a prospect “just for the demo”, a customer who cancelled still has it, the pricing page lists it under Pro, and nobody can say which of the 340 enabled organisations are actually paying for it.

Nothing in that story is a bug in the flag library. It is a category error. Feature flags and entitlements both end in an if, which makes them look like the same tool, but they answer different questions, change for different reasons and belong to different people. This post draws the line between feature flags vs entitlements in Phoenix, shows what each looks like in Elixir, and then builds one small module that combines them so the rest of your app asks a single question.

The entitlement examples use Aurora Meter, the free MIT metering and entitlements library for Phoenix. The flag examples use FunWithFlags, the most widely used flag library in the Elixir ecosystem. The design works the same with a hand-rolled version of either.

Two questions that look the same

A feature flag answers: is this code ready to run for this audience? It is a release tool. Engineering owns it, it changes many times in a week, and its ideal lifespan is short. When the rollout reaches 100% the flag should be deleted.

An entitlement answers: has this customer paid for this? It is a commercial fact. It is derived from a plan and a subscription, it changes when money changes (an upgrade, a cancellation, a failed payment), and it lives as long as the product does.

Feature flag Entitlement
Question Is the code ready for this audience? Has this customer paid for it?
Owner Engineering, product Pricing, billing
Source of truth A flag store you toggle The plan definition plus the subscription
Changes when Someone flips it A subscription event happens
Typical audience A percentage, a beta group, internal staff Everyone on a plan
Lifespan Days to weeks, then deleted Permanent
Safe default if unknown Off (old behaviour) Off (no access)
What the user sees when off Nothing. The feature does not exist yet An upgrade prompt

The last row is the one that shows up in your UI. A customer who is not in a beta should not see a locked button for a feature that is not finished. A customer on the Free plan absolutely should see the locked button for a Pro feature, because that button is your upgrade funnel. One boolean cannot express both.

What goes wrong when one tool does both jobs

Plan gating in the flag store

This is the story from the introduction, and it fails in predictable ways:

  • Nothing revokes access. A flag enabled for an actor stays enabled when the subscription is cancelled, because the flag store has never heard of Stripe.
  • The pricing page and the code drift apart. “Pro includes AI reports” is now a sentence on a web page and a set of rows in a toggles table, with nothing connecting them.
  • Access becomes untraceable. There is no way to ask “why does this organisation have AI reports?” and get the answer “because they are on Pro”. The answer is “because someone clicked a button in March”.
  • Limits do not fit. A flag is on or off. “1,000 generations a month on Pro” is not a flag, so quota logic ends up somewhere else and the two halves of one plan live in two systems.

Rollouts in the plan definition

The opposite mistake is rarer but just as awkward. If the only gate you have is the plan module, then a gradual rollout means inventing a :pro_beta plan, moving customers onto it, and moving them back. Plan changes are compiled into your release, so turning a broken feature off means a deploy at the worst possible moment. And “10% of organisations” is not something a plan can express at all.

The flag that became a contract

The subtlest failure is time. A beta flag left on for a year stops being a rollout and becomes an entitlement nobody wrote down. Customers who had it during the “beta” reasonably believe it is part of what they bought. When you finally put it behind a paid plan, you are not launching a feature. You are taking one away.

Entitlements in Phoenix: derived from the plan

An entitlement should never be toggled. It should be computed from two things: what each plan grants, and which plan the customer is on. In Aurora Meter the first lives in a plan module that is validated at compile time:

defmodule MyApp.Plans do
  use AuroraMeter.Plans

  plan :free do
    price 0
    limit :ai_generations, 50, :hard
    feature :ai_reports, false
    feature :api_access, false
    feature :seats, 1
  end

  plan :pro do
    price 4_900
    limit :ai_generations, 1_000, :hard
    feature :ai_reports, true
    feature :api_access, true
    feature :seats, 5
  end
end

The second is one call, made from wherever your subscription state changes (a Stripe webhook, an admin action, a trial ending):

AuroraMeter.subscribe(org, :pro)

After that, every check is a read:

AuroraMeter.entitled?(org, :ai_reports)       # true on :pro, false on :free
AuroraMeter.feature_value(org, :seats, 1)     # 5 on :pro
AuroraMeter.check(org, :ai_generations)       # :ok | {:error, :limit_exceeded | :not_entitled}

Plan lookups are cached in ETS and evicted when a subscription changes, so the check costs no database call on the request path. More to the point for this discussion: there is no way to give one organisation :ai_reports without changing their plan. That constraint is the feature. Access always has a reason you can read off the subscription.

The fuller design, including the difference between a customer who is over their limit and one who never had the feature, is in plan-based feature gating and entitlements in Phoenix.

Feature flags in Phoenix: toggled at runtime

Flags want the opposite properties: changed at runtime, with no deploy, for an arbitrary audience. FunWithFlags stores toggles in your database and caches them in ETS:

# mix.exs
{:fun_with_flags, "~> 1.12"}

# config/config.exs
config :fun_with_flags, :persistence,
  adapter: FunWithFlags.Store.Persistent.Ecto,
  repo: MyApp.Repo

config :fun_with_flags, :cache_bust_notifications,
  enabled: true,
  adapter: FunWithFlags.Notifications.PhoenixPubSub,
  client: MyApp.PubSub

(The library’s README has the migration for its toggles table.) Tell it how to identify the thing you roll out to. Roll out to the organisation, not the user, so everyone on a team sees the same product:

defimpl FunWithFlags.Actor, for: MyApp.Accounts.Org do
  def id(%{id: id}), do: "org:#{id}"
end

Then the rollout is a series of commands from IEx or an admin page, with no deploy between them:

FunWithFlags.enable(:release_ai_reports, for_actor: internal_org)          # staff first
FunWithFlags.enable(:release_ai_reports, for_percentage_of: {:actors, 0.1}) # then 10%
FunWithFlags.enable(:release_ai_reports)                                    # then everyone

FunWithFlags.enabled?(:release_ai_reports, for: org)

Two habits keep flags from turning into the mess described above.

Name flags for their job. A prefix such as release_ for rollouts and kill_ for operational switches tells a reader what a flag is for and, by implication, that there is no plan_ prefix because plans do not live here.

Know the precedence rules before you rely on a kill switch. In FunWithFlags an explicit actor gate takes precedence over the global boolean, so disabling a flag globally does not turn it off for an organisation you enabled by name. That is sensible for rollouts and dangerous for an emergency stop. Use a separate kill_ flag that only ever has a global gate, and check the precedence section of the library’s README for the version you install.

Combine them behind one question

Call sites should not know there are two systems. Give them one module with one function, and make the order of the checks a deliberate decision:

defmodule MyApp.Access do
  @moduledoc "The single answer to: can this org use this feature right now?"

  # Features still rolling out. Delete the entry when the rollout reaches 100%.
  @release_flags %{ai_reports: :release_ai_reports}

  # Operational switches for features that depend on something that can break.
  @kill_flags %{ai_reports: :kill_ai_reports}

  @type reason :: :unavailable | :not_released | :not_entitled

  @spec check(term(), atom()) :: :ok | {:error, reason()}
  def check(org, feature) do
    cond do
      killed?(feature) -> {:error, :unavailable}
      not released?(org, feature) -> {:error, :not_released}
      not AuroraMeter.entitled?(org, feature) -> {:error, :not_entitled}
      true -> :ok
    end
  end

  def allowed?(org, feature), do: check(org, feature) == :ok

  defp killed?(feature) do
    case @kill_flags do
      %{^feature => flag} -> FunWithFlags.enabled?(flag)
      _ -> false
    end
  end

  defp released?(org, feature) do
    case @release_flags do
      %{^feature => flag} -> FunWithFlags.enabled?(flag, for: org)
      _ -> true
    end
  end
end

The order matters. The kill switch comes first because an outage applies to everyone, including people who paid. The release flag comes second because an unreleased feature should be invisible whatever the plan. The entitlement comes last, and it is the only failure the customer can fix themselves.

Three reasons, three different responses in the UI:

Result What to render
{:error, :not_released} Nothing. No menu item, no locked state, a 404 on the route
{:error, :not_entitled} The locked feature with an upgrade prompt naming the plan
{:error, :unavailable} The feature, disabled, with “temporarily unavailable” and a status link

Quota is deliberately not in this function. Access.check/2 decides whether a customer can see and open a feature. Whether they have usage left is decided at the moment the work runs, with AuroraMeter.with_quota(org, :ai_generations, fn -> ... end), which reserves a unit and refuses with {:error, :limit_exceeded} at the cap. Keeping the two apart means a customer at their limit still sees the feature and gets a message about usage instead of a page that vanished. Rate limits vs quotas in Phoenix covers that layer.

Enforce it at the boundary

Hiding a button is presentation. The check has to run where the request enters. For LiveView, an on_mount hook:

defmodule MyAppWeb.RequireAccess do
  import Phoenix.LiveView

  def on_mount({:feature, feature}, _params, _session, socket) do
    case MyApp.Access.check(socket.assigns.current_org, feature) do
      :ok ->
        {:cont, socket}

      {:error, :not_entitled} ->
        {:halt, redirect(socket, to: "/billing/upgrade?feature=#{feature}")}

      {:error, :unavailable} ->
        {:halt, socket |> put_flash(:error, "Temporarily unavailable.") |> redirect(to: "/")}

      {:error, :not_released} ->
        raise MyAppWeb.NotFoundError
    end
  end
end
live_session :ai_reports,
  on_mount: [MyAppWeb.RequireAuth, {MyAppWeb.RequireAccess, {:feature, :ai_reports}}] do
  live "/reports/ai", ReportLive.AI
end

MyAppWeb.NotFoundError is a small exception of your own that implements Plug.Exception with a 404 status. Write the same four clauses once more as a plug for controllers and API routes, where :not_entitled becomes a 403 with a machine readable reason. Background jobs call MyApp.Access.check/2 at the top of perform/1, because a job enqueued while a customer was on Pro can run after they have downgraded.

The cases that sit on the line

A beta feature that will become paid

Decide the plan before the beta starts, and say so in the beta invitation: “AI reports are free during the beta and will be part of Pro.” Then the two systems hand over cleanly.

  1. During the beta, grant feature :ai_reports, true on every plan and gate on the release flag alone. Entitlement passes for everyone. The flag chooses the audience.
  2. At launch, in one deploy, change the Free plan to feature :ai_reports, false and remove :ai_reports from @release_flags. From that moment the plan decides.
  3. After launch, delete the flag from the store with FunWithFlags.clear(:release_ai_reports).

If you want beta participants on Free to keep access for a grace period, that is a time-limited entitlement (see the next case), not a reason to keep the flag alive.

One customer gets something their plan does not include

An enterprise deal includes API access on a plan that normally lacks it. It is tempting to reach for an actor flag, and it is the exact mistake this post is about: this is a commercial grant with a contract behind it, so it is an entitlement.

There are two honest ways to model it. If the deal is a real, repeatable package, give it a plan (plan :enterprise do ... end) and subscribe the customer to it. If it is a one-off, keep a small overrides table in your app and consult it before the plan:

defmodule MyApp.Access.Overrides do
  import Ecto.Query

  @doc "An explicit grant or denial for one org, or nil to fall through to the plan."
  def lookup(org_id, feature, now \\ DateTime.utc_now()) do
    MyApp.Repo.one(
      from o in "entitlement_overrides",
        where: o.org_id == ^org_id and o.feature == ^to_string(feature),
        where: is_nil(o.expires_at) or o.expires_at > ^now,
        select: o.granted
    )
  end
end
defp entitled?(org, feature) do
  case MyApp.Access.Overrides.lookup(org.id, feature) do
    nil -> AuroraMeter.entitled?(org, feature)
    granted when is_boolean(granted) -> granted
  end
end

Give each override row a reason, a granted_by and an optional expires_at. That table is application code you own, not something Aurora Meter provides, and it adds a database read to the check, so cache it per organisation if the feature sits on a hot path. What you get in return is the property the flag approach lacks: every exception has an author, a reason and an end date.

A kill switch on a paid feature

Your AI provider is having an incident and report generation is timing out. Flip kill_ai_reports on, and Access.check/2 returns {:error, :unavailable} for everyone. This is a legitimate use of a flag over a paid feature, because the question really is “can this code run right now?” The entitlement is untouched. When the switch goes off, everyone has exactly the access they had before, with no reconciliation.

Trials and promotions

“Pro features free for 14 days” is not a flag either. It expires on a date, it converts into a paid plan, and it should be visible in billing. Model it as a subscription to the paid plan with an end date, or with usage limits in place of a calendar, as described in usage-based free trials in Phoenix.

A five question test

When a new if is about to be written, these settle which system it belongs to:

  1. Will this condition still exist in a year? Yes: entitlement. No: flag.
  2. Does it appear on the pricing page? Yes: entitlement.
  3. Should it change automatically when a subscription changes? Yes: entitlement.
  4. Do you need to target a percentage, or turn it off in seconds without a deploy? Yes: flag.
  5. When it is off, should the user see an upgrade prompt? Yes: entitlement. If they should see nothing: flag.

If the answers split, you have both: a release flag now, an entitlement at launch, and a date in the calendar for the handover.

Test the matrix

The combination is small enough to test exhaustively, and the test doubles as documentation of the order of precedence:

defmodule MyApp.AccessTest do
  use MyApp.DataCase, async: false

  setup do
    org = insert(:org)
    FunWithFlags.clear(:release_ai_reports)
    FunWithFlags.clear(:kill_ai_reports)
    {:ok, org: org}
  end

  test "an unreleased feature is hidden even from a paying customer", %{org: org} do
    AuroraMeter.subscribe(org, :pro)
    assert {:error, :not_released} = MyApp.Access.check(org, :ai_reports)
  end

  test "a released feature still needs the plan", %{org: org} do
    FunWithFlags.enable(:release_ai_reports)
    AuroraMeter.subscribe(org, :free)
    assert {:error, :not_entitled} = MyApp.Access.check(org, :ai_reports)

    AuroraMeter.subscribe(org, :pro)
    assert :ok = MyApp.Access.check(org, :ai_reports)
  end

  test "the kill switch wins over everything", %{org: org} do
    FunWithFlags.enable(:release_ai_reports)
    FunWithFlags.enable(:kill_ai_reports)
    AuroraMeter.subscribe(org, :pro)
    assert {:error, :unavailable} = MyApp.Access.check(org, :ai_reports)
  end
end

The tests run with async: false because the flag store is global state. Add one more test that matters commercially: subscribe an organisation to Pro, downgrade it to Free, and assert the feature is gone on the next check. That single assertion is the thing a flag-only design cannot pass.

Keep flags short-lived

Entitlements accumulate by design. Flags should not. A few cheap rules stop the drift:

  • Every entry in @release_flags carries a comment with an owner and a removal date.
  • A test fails if a release flag has been fully enabled for more than 30 days. FunWithFlags can list flags and their gates, so this is a short query.
  • Removing a flag is one pull request: delete the map entry, delete the old code path, clear the flag from the store.

When a flag refuses to die because “some customers depend on it”, read that as a signal. It has become an entitlement, and it should move into the plan module where the pricing page and the code can agree about it.

Where Aurora Meter fits

Everything on the entitlement side of this post runs on the free core: the plan module, entitled?/2, feature_value/3, check/2, hard limits and with_quota. It is MIT, on GitHub, and the core docs take about ten minutes from mix deps.get to a working gate. Aurora Meter does not ship feature flags and is not trying to: pair it with FunWithFlags or your own flag store, joined by a module like MyApp.Access.

The part the core leaves to you is the line AuroraMeter.subscribe(org, :pro): something has to call it when Stripe says a subscription started, changed, lapsed or ended. Aurora Meter Pro is that something. It adds Stripe Checkout, webhook-driven plan sync, usage reporting to Stripe billing meters and quota alerts, so entitlements follow the subscription without hand-written webhook handlers. Pro is licensed per app from $99 a month, with a 14-day free trial (one trial per customer).

Summary

Feature flags and entitlements end in the same if and should never share a store. A flag is a temporary, runtime answer to “is this code ready for this audience?”, owned by engineering and deleted when the rollout finishes. An entitlement is a permanent answer to “has this customer paid for it?”, derived from the plan and the subscription and never toggled by hand. In Phoenix, keep entitlements in a compile-time plan module, keep flags in a flag store, and put one Access.check/2 in front of both that returns a reason: unavailable, not released or not entitled. Render each reason differently, enforce the check at the LiveView, controller and job boundary, hand a beta feature over from flag to plan on a planned date, and model one-off deals as audited overrides. Do that and the pricing page, the code and the customer’s invoice all describe the same product.