Feature Flags
- Introduction
- A rollout in four steps
- Configuration
- Defining features
- Rich values
- Checking features
- Updating values
- Flags by name
- Custom stores
- Testing
Introduction
Feature flags let you roll out new functionality gradually without redeploying at each step. You can enable a new API for staff first, expand it to one customer in a hundred, and eventually turn it on for everyone. You can also run A/B experiments, such as showing each user one of three button colors and keeping the version that converts best.
In dust-framework, a feature flag is a Rust function that determines the initial value for a user, a team, or the entire application. dust-framework stores that resolved value so the user receives a consistent experience on every subsequent request until you explicitly update or purge it.
A rollout in four steps
A flag has a lifecycle, and each step uses a different part of the API:
- Decide the scope. A user flag takes
&User, a team flag takes&Team, and an application-wide flag takes nothing. Pick the smallest scope that answers the question. - Define the rule. Write the
#[flag]function with your staff, percentage, or data condition. It runs once per scope and the result is stored. - Observe and adjust. Check the flag in handlers and share it with the page. Use
feature::everyone()to move every already-checked scope to the new value when you are confident. - Remove the flag. Delete the branch and the
#[flag]function, then runfeature:purgeto clean up the stored rows.
[!WARNING] A feature flag controls presentation and rollout, not authorization. A user who cannot see a button can still call its route, so enforce permissions with a policy in the handler.
RequireFeatureis a rollout guard, not a security boundary.
Flags also cost a store lookup. Checking the same flag repeatedly for one user is free within a request, but checking many users in a loop is not; use feature::load to batch it.
Configuration
By default, dust-framework persists feature values in your database so every server agrees on each user's flag state and values survive deployments. Configure feature storage with these environment variables:
| Variable | Default | Purpose |
|---|---|---|
FEATURE_STORE |
database |
database, memory, or the name of a custom store. |
DB_FEATURE_CONNECTION |
Default connection | Database connection used by the database store. |
DB_FEATURE_TABLE |
features |
Table name used by the database store. |
The memory store keeps resolved values in each process's memory and discards them on restart. It is ideal for local development and tests, and is used automatically when your application has no database configured.
The features table
The database store requires a features table, which is not created by default. Create it in a migration with dust::feature::table!():
// database/migrations/2026_01_01_000000_create_features_table.rsdust::feature::table!();If you'd like to customize the table, such as using a different table name or adding a column, replace the macro with the migration it stands for and edit it:
// database/migrations/2026_01_01_000000_create_features_table.rsuse dust::db::AnyTransaction;pub async fn migrate(tx: &mut AnyTransaction<'_>) -> dust::Result<()> { tx.schema() .create("features", |table| { table.id(); table.string("name"); table.string("scope"); table.text("value"); table.timestamps(); table.unique(["name", "scope"]); }) .await}Keep the unique index on name and scope so concurrent first-time checks for the same user always converge on a single stored value.
Defining features
Define a feature by annotating a function with #[flag]. dust-framework discovers every #[flag] function automatically without manual registration, and you can organize them together in src/features.rs. The function receives the scope it evaluates for (typically &User) and returns whether the feature is active. For example, this flag enables a new API for staff and 1% of other users:
// src/features.rsuse dust::feature::flag;use dust::lottery::Lottery;use crate::models::User;#[flag]pub fn new_api(user: &User) -> bool { user.is_staff || Lottery::odds(1, 100).draw()}The function runs once per user on their first check, and dust-framework stores what it returns. Subsequent checks read the stored value directly without invoking the function again, so each user gets a single lottery draw and keeps that outcome.
#[flag] generates a unit struct with the same name as the function, which you pass when checking the feature. Misspelling a feature name fails at compile time.
[!NOTE] Because
#[flag]defines a unit struct with the function's name, writinglet new_api = user.features().active(new_api).await?will not compile because Rust treatsnew_apiin theletpattern as the struct. Import the module instead and referencefeatures::new_api.
Stored names
dust-framework stores each flag under its function name unless you override it with name. Because renaming a function would orphan existing stored rows, preserve the original stored name when refactoring:
use dust::feature::flag;use crate::models::User;#[flag(name = "new_api")]pub fn new_servers_api(user: &User) -> bool { user.is_staff}You can also use name to give a flag a cleaner identifier for templates or admin pages, such as purchase-button.
Async features, services, and config
A #[flag] function may be async and return a dust::Result, allowing it to query the database or external services. For example, this flag enables a new editor for authors with at least ten published posts:
use dust::feature::flag;use crate::models::{Post, User};#[flag]pub async fn new_editor(user: &User) -> dust::Result<bool> { let published = Post::query() .filter(Post::user_id.eq(user.id)) .filter(!Post::published_at.is_null()) .count() .await?; Ok(published >= 10)}If the function returns an error, the check propagates that error without storing anything, and the next check invokes the function again.
After the scope parameter, a flag function may also accept Inject<T> services and Section<T> config sections in any order. dust-framework resolves these only when the function runs on a scope's first check, so changing configuration later does not alter already-stored values.
Rich values
Not every feature is a simple boolean. For multi-variant experiments (such as testing three colors for a "Buy now" button), return Option<T> where Some(value) is active with that variant and None is inactive. The value type must implement Serialize, Deserialize, and Clone:
use dust::feature::flag;use serde::{Deserialize, Serialize};use crate::models::User;#[derive(Clone, Serialize, Deserialize)]#[serde(rename_all = "kebab-case")]pub enum ButtonColor { BlueSapphire, SeafoamGreen, TartOrange,}#[flag(name = "purchase-button")]pub fn purchase_button(user: &User) -> Option<ButtonColor> { Some(match user.id % 3 { 0 => ButtonColor::BlueSapphire, 1 => ButtonColor::SeafoamGreen, _ => ButtonColor::TartOrange, })}dust-framework stores rich values as JSON, such as "seafoam-green". If a stored value can no longer be deserialized into the expected type (for example, after you remove an enum variant), dust-framework re-runs the flag function and stores the new result.
Checking features
Every check pairs a feature with a scope, such as a user or a team. Call .features() on the scope (provided by the HasFeatures trait in the prelude), then call active or value.
Users
User models support .features() automatically. In a handler, extract Authenticated<User> and call active:
use dust::prelude::*;use crate::features;use crate::models::User;pub async fn index(user: Authenticated<User>) -> dust::Result<Response> { if user.features().active(features::new_api).await? { return servers::v2::index().await; } servers::v1::index().await}Use value to retrieve the typed result returned by the flag function, whether bool or a rich value:
match user.features().value(features::purchase_button).await? { Some(color) => { // Show the button in this color... } None => { // Don't show the button... }}dust-framework caches each resolved value in memory for the remainder of the current request, so checking the same feature multiple times for the same user queries the store only once. Subsequent requests read from the store again.
Teams and other scopes
To scope a feature to an entire team, such as a new billing page that every team member should see together, implement HasFeatures on your Team model. feature_key returns the stable identifier dust-framework uses to store that team's values:
use dust::feature::{HasFeatures, ScopeKey};use crate::models::Team;impl HasFeatures for Team { fn feature_key(&self) -> ScopeKey { ScopeKey::new("Team", self.id) }}Use a short, permanent scope kind such as "Team". Changing the scope kind orphans previously stored values for that type.
A team-scoped flag function takes &Team. For example, this flag enables a new billing page for teams with 50 or more seats plus 1% of smaller teams:
use dust::feature::flag;use dust::lottery::Lottery;use crate::models::Team;#[flag]pub fn billing_v2(team: &Team) -> bool { team.seats >= 50 || Lottery::odds(1, 100).draw()}Check the feature directly on a loaded Team:
if team.features().active(features::billing_v2).await? { return Ok(Redirect::to("/billing/v2").into_response());}Each flag is typed to its scope, so checking a team feature on a User fails to compile.
Guests
Flags that take &User evaluate to inactive for guests without running the function. To evaluate a flag for guests as well, accept Option<&User>. dust-framework passes None for guests, and all guests share a single stored value:
use dust::feature::flag;use crate::models::User;#[flag]pub fn holiday_banner(user: Option<&User>) -> bool { user.is_none_or(|user| !user.is_staff)}In handlers accessible to both signed-in users and guests, extract Auth<User> and call .features() directly on the Option<User> returned by auth.user() (when None, dust-framework evaluates the flag for a guest):
use dust::auth::Auth;use dust::prelude::*;use crate::features;use crate::models::User;pub async fn home(auth: Auth<User>) -> dust::Result<Response> { let user = auth.user().await?; if user.features().active(features::holiday_banner).await? { // Show the banner... } Ok(view("home", ()).into_response())}When you want to check or update the guest scope directly without an Option<User>, call feature::guest::<User>().
Application-wide features
When a feature has a single value for everyone, such as a scheduled maintenance banner, define a #[flag] function with no scope parameter:
use dust::feature::flag;#[flag]pub fn maintenance_banner() -> bool { false}Check and update application-wide features using the top-level functions in dust::feature:
use dust::feature;if feature::active(features::maintenance_banner).await? { // ...}Middleware
To restrict a route to users who have a feature enabled, attach RequireFeature middleware. When the feature is inactive, dust-framework responds with 400 Bad Request:
use dust::feature::RequireFeature;use dust::prelude::*;use crate::features;pub fn routes(route: &mut Router) { route .get("/api/servers", servers::index) .middleware(RequireFeature::new(features::new_api));}To require multiple features, attach one RequireFeature per feature. To return a custom response when the feature is inactive, chain .otherwise(..) with a handler:
route .get("/servers", servers::index) .middleware( RequireFeature::new(features::new_api) .otherwise(async || Redirect::to("/upgrade")), );RequireFeature supports user features and application-wide features. For team-scoped features, write custom middleware that resolves the team and calls team.features().active(..).
Sharing features with pages
Frontend pages frequently need feature flags to show or hide UI elements. Calling .all() returns every feature defined for that scope type as a JSON object keyed by stored name, with inactive flags set to false and rich values serialized to JSON:
{ "new_api": true, "purchase-button": "seafoam-green", "holiday_banner": false }Pass the map to the page that renders the controls:
use dust::prelude::*;use crate::models::User;pub async fn dashboard(user: Authenticated<User>) -> dust::Result<View> { let features = user.features().all().await?; Ok(view("dashboard", data! { features }))}For server-rendered templates, append ShareFeatures to your web middleware group in src/app.rs instead of loading the map in every handler:
use dust::feature::ShareFeatures;.with_middleware(|middleware, _| { middleware.web(|web| { web.append(ShareFeatures::<User>::new()); });})Templates can then call feature(name) with a flag's stored name. Passing an undefined flag name fails template rendering:
{% if feature("new_api") %}
<a href="/api/docs">Try the new API</a>
{% endif %}
{% if feature("purchase-button") == "tart-orange" %}
<button class="bg-orange-500">Buy now</button>
{% endif %}[!WARNING] Hiding a link or button in the UI does not protect the route behind it. Always check the feature in the route's handler or guard it with
RequireFeature.
Eager loading
When rendering a list of scopes (such as a table of teams) and checking a feature on each, querying one by one causes an N+1 lookup against the store. Call feature::load before the loop to fetch every scope's value in a single query:
use dust::feature;feature::load(features::billing_v2, &teams).await?;for team in &teams { let billing = team.features().active(features::billing_v2).await?; // ...}Updating values
You can update a scope's stored value programmatically (for example, granting a customer early access to a feature) from a handler, command, or job:
use crate::features::{self, ButtonColor};user.features().activate(features::new_api).await?;user.features() .activate_with(features::purchase_button, ButtonColor::TartOrange) .await?;user.features().deactivate(features::new_api).await?;user.features().forget(features::purchase_button).await?;Use activate for boolean flags and activate_with for rich-value flags. Calling forget deletes the stored row so the next check re-runs the flag function. For application-wide features, call the matching top-level functions such as feature::deactivate(features::maintenance_banner).await?.
Every scope at once
Once a feature is ready for general release or an experiment has a winner, call feature::everyone() to update every stored entry for that flag at once:
use dust::feature;use crate::features::{self, ButtonColor};feature::everyone().activate(features::new_api).await?;feature::everyone() .activate_with(features::purchase_button, ButtonColor::SeafoamGreen) .await?;activate, activate_with, and deactivate only modify entries already stored in the database. Users who have never been checked will still receive the flag function's result on their first check, so update the function as well when finalizing a rollout. Calling forget deletes every stored entry so all scopes re-evaluate the function on their next check.
Purging features
Use the feature:purge command to delete stored feature rows from the store. Purging a feature that is still defined in your code causes it to be re-computed from its #[flag] function on the next check, while purging a removed feature cleans up its old rows:
dust feature:purge new_api purchase-buttonRunning feature:purge with no names purges all stored features so every defined flag is re-evaluated. Pass --except to keep specific names, or pass --except-defined (for example, during deployment) to purge only flags that are no longer defined in your application:
dust feature:purge --except-definedFlags by name
An admin dashboard or API receives flag names as strings rather than compile-time #[flag] types. Call feature::find to look up a flag by its stored name as an AnyFlag (returning None if undefined). Every check and mutation method accepts AnyFlag, with rich values passed as JSON.
For example, this handler updates a flag for a user at PUT /admin/users/{user}/flags (protect the route with admin authorization):
use dust::feature;use dust::http::NoContent;use dust::prelude::*;use crate::models::User;#[dust::input]#[validate(anyone)]pub struct UpdateFlag { #[validate(required)] name: String, value: Option<serde_json::Value>,}pub async fn update( user: User, Valid(input): Valid<UpdateFlag>,) -> dust::Result<NoContent> { let flag = feature::find(&input.name).or_abort(404)?; match input.value { Some(value) => user.features().activate_with(flag, value).await?, None => user.features().deactivate(flag).await?, } Ok(NoContent)}The JSON value must deserialize into the flag's expected type (such as "seafoam-green" for ButtonColor::SeafoamGreen). An invalid JSON value returns a 422 response naming the flag without modifying the store. To list every flag defined in your application, call feature::defined().
Custom stores
To persist feature flags in another backend, such as Redis or an external feature-flag service, implement dust::feature::FeatureStore. Values are passed as JSON strings keyed by feature name and scope:
use dust::feature::{FeatureStore, ScopeKey, StoredValues};pub struct RedisFeatureStore;impl FeatureStore for RedisFeatureStore { async fn get_many( &self, features: &[&str], scopes: &[ScopeKey], ) -> dust::Result<StoredValues> { // Read every pair's value in one round trip... todo!() } async fn add( &self, feature: &str, scope: &ScopeKey, value: &str, ) -> dust::Result<Option<String>> { // Store the value unless the scope has one, returning any existing value... todo!() } async fn set( &self, feature: &str, scope: &ScopeKey, value: &str, ) -> dust::Result<()> { // Store the value, replacing any earlier one... todo!() } async fn update_all(&self, feature: &str, value: &str) -> dust::Result<()> { // Replace every stored value of the feature... todo!() } async fn forget(&self, feature: &str, scope: &ScopeKey) -> dust::Result<()> { // Delete the scope's value... todo!() } async fn purge(&self, features: &[&str]) -> dust::Result<()> { // Delete every value of these features... todo!() } async fn stored_names(&self) -> dust::Result<Vec<String>> { // Return the name of every feature that has a stored value... todo!() }}add must check and insert atomically (such as an insert ignoring unique-key conflicts) so concurrent first-time checks agree on one value. Stores backed by a remote feature flag service can also implement defined_for to expose flags not declared in Rust, which callers can look up via user.features().find(name).
Register your custom store in src/app.rs inside with_services, then select it with FEATURE_STORE=redis:
Application::configure() .with_services(|app| { app.features() .extend("redis", |_app| async { Ok(RedisFeatureStore) }); })Packages can register custom stores inside their service provider's register method via app.features().extend(..).
Testing
Tests use the memory store by default, and each test runs with an isolated application starting from an empty store, so no features table is required.
Use feature::fake to pin a feature's value across all scopes for the remainder of the test:
use dust::feature;use dust::testing::prelude::*;use app::features::{self, ButtonColor};#[dust::test]async fn the_new_api_lists_servers(app: Application) { feature::fake(features::new_api, true); feature::fake(features::purchase_button, Some(ButtonColor::TartOrange)); app.get("/api/servers").await.assert_ok();}To return different values per scope, call feature::fake_using with a closure taking the flag's scope parameter (such as &User):
feature::fake_using(features::new_api, |user| user.id == 1);For features using a lottery, you can call Lottery::always_win() or Lottery::always_lose(). In HTTP tests where a specific flag matters, prefer feature::fake over Lottery::fix, because session garbage collection and ShareFeatures may consume fixed lottery draws before your handler runs.